Question

Currently working on a Go project of about 10k lines of code. Within the project, there's a logging library that requires a couple steps of initialization in order to actually write to the log according to the project pattern, within the appropriate scope and depth of log message.

As a result, almost every function has the same couple lines of initial log code at the beginning:

    logger := log.WithJob().WithTask(log.NewTask("ArbitraryTaskName"))
    defer logger.HandleDeferLogic()

The logger object is then referenced throughout the calling function to make a log entry show up with appropriate details regarding the calling task.

e.g.

    logger.Info("foo")
    logger.Error("bar")
    logger.Debug("baz")

While it's not necessarily "bad" for these initializing lines to be at the beginning of every function, it feels irritating and somewhat like a "code smell" to see this code at the beginning of almost every function in the project. To me it seems like there must be a better solution to avoid copy-pasting these lines into every function that needs to write output to the log.

Are there existing strategies out there for dealing with log libraries that require initialization at a function-level? Am I overthinking it?

Was it helpful?

Solution

You're asking for Aspect Oriented Programming (AOP). This lets you add logging to one, some, almost all, or all functions in your codebase, in one place, without rewriting any of those functions to add it. Logging is one of the best uses of AOP.

However,

Go does not have any specific support for AOP in either the language itself or its standard library and there appears to be little interest in adding any.

Nevertheless, there are at least three third party libraries for adding AOP functionality to Go, including this one which includes a code example. However, none of them have progressed beyond 'alpha' status and, as there have been no recent commits, development may have stalled.

rosettacode.org - Aspect Oriented Programming [in] Go

Licensed under: CC-BY-SA with attribution
scroll top