Python logging - check location of log files?

2020-02-23 05:45发布

What is the methodology for knowing where Python log statements are stored?

i.e. if i do:

import logging
log = logging.getLogger(__name__)
log.info('Test')

Where could I find the logfile? Also, when I call:

logging.getLogger(__name__)

Is that somehow related to how the logger will behave/save?

4条回答
该账号已被封号
2楼-- · 2020-02-23 05:55

To get the log location of a simple file logger, try

logging.getLoggerClass().root.handlers[0].baseFilename
查看更多
在下西门庆
3楼-- · 2020-02-23 06:06

Excellent question @zallarak. Unfortunately, while they're easy to create, Loggers are difficult to inspect. This gets the filenames of all Handlers for a logger:

filenames = []
for handler in logger.handlers:
    try:
        filenames.append(handler.fh.name)
    except:
        pass

The try block handles exceptions that occur when the filename lookup fails.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-02-23 06:09

To find the logfile location, try instantiating your log object in a Python shell in your environment and looking at the value of:

log.handlers[0].stream

查看更多
手持菜刀,她持情操
5楼-- · 2020-02-23 06:19

The logging module uses handlers attached to loggers to decide how, where, or even if messages ultimately get stored or displayed. You can configure logging by default to write to a file as well. You should really read the docs, but if you call logging.basicConfig(filename=log_file_name) where log_file_name is the name of the file you want messages written to (note that you have to do this before anything else in logging is called at all), then all messages logged to all loggers (unless some further reconfiguration happens later) will be written there. Be aware of what level the logger is set to though; if memory serves, info is below the default log level, so you'd have to include level=logging.INFO in the arguments to basicConfig as well for your message to end up in the file.

As to the other part of your question, logging.getLogger(some_string) returns a Logger object, inserted in to the correct position in the hierarchy from the root logger, with the name being the value of some_string. Called with no arguments, it returns the root logger. __name__ returns the name of the current module, so logging.getLogger(__name__) returns a Logger object with the name set to the name of the current module. This is a common pattern used with logging, as it causes the logger structure to mirror your code's module structure, which often makes logging messages much more useful when debugging.

查看更多
登录 后发表回答