Last active
August 26, 2024 17:15
-
-
Save Huarong/5873549 to your computer and use it in GitHub Desktop.
Python: an example of how to use logging module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def init_log(logname, filename, level=logging.DEBUG, console=True): | |
| # make log file directory when not exist | |
| directory = os.path.dirname(filename) | |
| if not os.path.exists(directory): | |
| os.makedirs(directory) | |
| # set up logging to file - see previous section for more details | |
| logging.basicConfig(level=level, | |
| format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', | |
| datefmt='%Y-%m-%d %H:%M', | |
| filename=filename, | |
| filemode='a') | |
| # Now, define a couple of other loggers which might represent areas in your | |
| # application: | |
| logger = logging.getLogger(logname) | |
| if console: | |
| # define a Handler which writes INFO messages or higher to the sys.stderr | |
| console = logging.StreamHandler() | |
| console.setLevel(logging.INFO) | |
| # set a format which is simpler for console use | |
| formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') | |
| # tell the handler to use this format | |
| console.setFormatter(formatter) | |
| # add the handler to the the current logger | |
| logger.addHandler(console) | |
| return logger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment