Reputation: 8315
I want to create a global logging object in a Python module that is imported by many small scripts. The Python module is designed to provide a consistent setup of things like logging, logos, timing etc. for all scripts. I'm trying to set up the logging in this module in order to make it easy to change the logging characteristics of all of these scripts at once.
The relevant part of the Python module is as follows:
if engageLog:
global log
log = logging.getLogger(__name__)
logging.root.addHandler(technicolor.ColorisingStreamHandler())
How could I write this such that the logging object is available in the scripts without requiring any setup beyond importing the module?
In the following example script, the module is called propyte
:
#!/usr/bin/env python
"""
################################################################################
# #
# script-1 #
# #
################################################################################
Usage:
script-1 [options]
Options:
-h, --help display help message
--version display version and exit
-v, --verbose verbose logging
-u, --username=USERNAME username
--data=FILENAME input data file [default: data.txt]
"""
name = "script-1"
version = "2015-10-21T1331Z"
import os
import sys
import time
import docopt
import propyte
def main(options):
global program
program = propyte.Program(options = options)
# access options and arguments
input_data_filename = options["--data"]
log.info("")
log.info("input data file: {filename}".format(
filename = input_data_filename
))
print("")
program.terminate()
if __name__ == "__main__":
options = docopt.docopt(__doc__)
if options["--version"]:
print(version)
exit()
main(options)
Upvotes: 0
Views: 145
Reputation: 1123930
Just use the log
attribute on the module:
import propyte
propyte.log # the global log object in the propyte module
Note however that the logging
module configuration is already global. You can use logging.getLogger('somename')
and it'll return a singleton logger object associated with that name. Configuration applied to that object will still be present when you retrieve the same logger in another module.
Upvotes: 1