Skip to main content
3 of 3
added 62 characters in body
Doc Brown
  • 220.5k
  • 35
  • 410
  • 625

Loggers, even if they have some global state internally, are rarely objects which change the core behaviour of a program (at least when the program itself does not behave in some crazy way like exchanging the logger object in the middle of some execution, quering the logger's state, or by postprocessing its own logging output for deciding about further actions).

Hence keeping a logger in a global variable isn't necessarily that bad - the risk of unwanted side effects is usually quite low. What you achieve by this design is a program which can only use one kind of logger in all of its modules throughout it's whole execution time. For many small-to-mid-size programs, this is fine.

Note that this design still gives you the option of easily changing the type of logger between different execution contexts, like development, test or production.

For larger program systems or programs with special requirements, however, this can start to make trouble. For example, when you have different teams working on different modules, with different logging requirements for their parts. Or, when you start to introduce multithreading, and you want to pipe the logging output of different modules into different log files to make this threadsafe, the most simple way could be to inject a differently initialized logger (with a different target file) into the objects related to each thread.

So, in short, it depends - you have to decide by yourself whether your program fits into the former or the latter category. The crucial point is often not to miss the point when a formerly small-and-simple program evolves into a large-and-complex system. But this means you will usually have to redesign certain parts either, and that's the time when you should replace a global logging variable by something more flexible.

Doc Brown
  • 220.5k
  • 35
  • 410
  • 625