This article mainly introduces an in-depth understanding of the python logging module. The editor thinks it is quite good. It mainly discusses how to use logging to output logs in a multi-process environment. How to safely split log files. Now I share it with you and give it as a reference. Let’s follow the editor and take a look.
Python’s logging module provides a flexible standard module, allowing any Python program to use this third party module to implement logging. python logging official documentation
The logging framework is mainly composed of four parts:
Loggers: an interface that can be directly called by the program
Handlers: Determine to distribute log records to the correct destination
Filters: Provide more fine-grained judgment on whether to output logs
Formatters: Develop the format layout for final record printing
loggers is a logging interface that the program can directly call, and can directly write log information to the logger. The logger is not directly instantiated, but the object is obtained through logging.getLogger(name)
. In fact, the logger object is a singleton mode, and logging is multi-thread safe, that is, no matter where in the program The logger objects obtained for logging are all the same. But unfortunately, logger does not support multi-process. This will be explained in the following chapters and some solutions will be given.
[Note] The loggers object has a parent-child relationship. When there is no parent logger object, its parent object is root. When there is a parent object, the parent-child relationship will be corrected. For example logging.getLogger("abc.xyz")
will create two logger objects, one is the abc parent object, and the other is the xyz child object. At the same time, abc has no parent object, so its parent object is root. . But in fact abc is a placeholder object (virtual log object), and there is no handler to process the log. However, root is not a placeholder object. If a log object logs, its parent object will receive the log at the same time. Therefore, some users find that when they create a logger object, they log twice because the logger they created logs. The log is logged once, and the root object is also logged once.
Each logger has a log level. The following levels are defined in logging
Level | Numeric value |
---|---|
NOTSET | 0 |
DEBUG | 10 |
INFO | 20 |
WARNING | 30 |
ERROR | 40 |
CRITICAL | 50 |
When a logger receives the log information, it first determines whether it meets the level. If it decides to process it, it passes the information to Handlers for processing.
Handlers accurately distributes the information sent by the logger and sends it to the right place. For example, send it to the console or file or both or other places (process pipes and the like). It determines the behavior of each log and is the key area that needs to be configured later.
Each Handler also has a log level. A logger can have multiple handlers, which means that the logger can pass logs to different handlers according to different log levels. Of course, the same level can also be passed to multiple handlers, which can be flexibly set according to needs.
Filters provides a more fine-grained judgment to decide whether the log needs to be printed. In principle, when the handler obtains a log, it will be processed uniformly according to the level, but if the handler has a Filter, it can perform additional processing and judgment on the log. For example, Filter can intercept or modify logs from a specific source or even modify their log level (the level will be judged after modification).
Both logger and handler can install filters and even multiple filters can be installed in series.
Formatters specifies the format layout for final printing of a certain record. Formatter will splice the passed information into a specific string. By default, Format will only print out the message %(message)s
directly. There are some built-in LogRecord properties that can be used in Format, as shown in the following table:
Attribute | Format | Description |
---|---|---|
%(asctime)s | Construct the log time into a readable form, by default it is '2016-02-08 12:00:00,123' accurate to milliseconds | |
%(filename)s | File name containing path | |
%(funcName )s | The log issued by which function | |
%(levelname)s | The final level of the log (received by filter modified) | |
%(message)s | Log message | |
lineno | %(lineno)d | The current log line number |
pathname | %(pathname )s | Full path |
process | %(process)s | Current process |
thread | %(thread)s | Current thread |
A Handler can only have one Formatter, so if you want to achieve output in multiple formats, you can only use multiple Handlers.
First of all, as explained in the loggers chapter, we have a default log object root. The advantage of this root log object is We can directly use logging for configuration and logging. For example:
logging.basicConfig(level=logging.INFO,filename='logger.log') logging.info("info message")
#So the simple configuration here refers to the root log object, which you can use anytime. Each logger is a singleton object, so after configuring it, it can be called anywhere in the program. We only need to call basicConfig to simply configure the root log object. In fact, this method is quite effective and easy to use. It ensures that when any logger is called, there will be at least one Handler that can handle the log.
Simple configuration can be roughly set like this:
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='[%Y-%m_%d %H:%M:%S]', filename='../log/my.log', filemode='a')
Another more detailed setting method is to configure it in the code, but this setting method is the least used method. , after all, no one wants to hard-code settings into the code. But here is a brief introduction. Although it is not used much, you can still use one when necessary. (To be added later)
The logging configuration file in python is based on the function of ConfigParser. In other words, the format of the configuration file is also written in this way. Let me first give you a more general configuration file and then explain it in detail
############################################## [loggers] keys=root, log02 [logger_root] level=INFO handlers=handler01 [logger_log02] level=DEBUG handler=handler02 qualname=log02 ############################################## [handlers] keys=handler01,handler02 [handler_handler01] class=FileHandler level=INFO formatter=form01 args=('../log/cv_parser_gm_server.log',"a") [handler_handler02] class=StreamHandler level=NOTSET formatter=form01 args=(sys.stdout,) ############################################## [formatters] keys=form01,form02 [formatter_form01] format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(process)d %(message)s datefmt=[%Y-%m-%d %H:%M:%S] [formatter_form02] format=(message)s ##############################################
I believe that after reading it again, I will also find the rules. I will use # to separate out a few big chunks. . Each logger, handler or formatter has a key name. Taking logger as an example, you first need to add the key name to the [loggers] configuration to represent the logger. Then use [loggers_xxxx] where xxxx is the key name to specifically configure this logger. In log02, I configured level and a handler name. Of course, you can configure multiple handlers. According to this handler name, go to [handlers] to find the configuration of the specific handler, and so on.
Then in the code, load the configuration file like this
logging.config.fileConfig(log_conf_file)
在handler中有一个class配置,可能有些读者并不是很懂。其实这个是logging里面原先就写好的一些handler类,你可以在这里直接调用。class指向的类相当于具体处理的Handler的执行者。在logging的文档中可以知道这里所有的Handler类都是线程安全的,大家可以放心使用。那么问题就来了,如果多进程怎么办呢。在下一章我主要就是重写Handler类,来实现在多进程环境下使用logging。 我们自己重写或者全部新建一个Handler类,然后将class配置指向自己的Handler类就可以加载自己重写的Handler了。
这部分其实是我写这篇文章的初衷。python中由于某种历史原因,多线程的性能基本可以无视。所以一般情况下python要实现并行操作或者并行计算的时候都是使用多进程。但是 python 中logging 并不支持多进程,所以会遇到不少麻烦。
本次就以 TimedRotatingFileHandler 这个类的问题作为例子。这个Handler本来的作用是:按天切割日志文件。(当天的文件是xxxx.log 昨天的文件是xxxx.log.2016-06-01)。这样的好处是,一来可以按天来查找日志,二来可以让日志文件不至于非常大, 过期日志也可以按天删除。
但是问题来了,如果是用多进程来输出日志,则只有一个进程会切换,其他进程会在原来的文件中继续打,还有可能某些进程切换的时候早就有别的进程在新的日志文件里打入东西了,那么他会无情删掉之,再建立新的日志文件。反正将会很乱很乱,完全没法开心的玩耍。
所以这里就想了几个办法来解决多进程logging问题
在解决之前,我们先看看为什么会导致这样的原因。
先将 TimedRotatingFileHandler 的源代码贴上来,这部分是切换时所作的操作:
def doRollover(self): """ do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of matching filenames, sort them and remove the one with the oldest suffix. """ if self.stream: self.stream.close() self.stream = None # get the time that this sequence started at and make it a TimeTuple currentTime = int(time.time()) dstNow = time.localtime(currentTime)[-1] t = self.rolloverAt - self.interval if self.utc: timeTuple = time.gmtime(t) else: timeTuple = time.localtime(t) dstThen = timeTuple[-1] if dstNow != dstThen: if dstNow: addend = 3600 else: addend = -3600 timeTuple = time.localtime(t + addend) dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple) if os.path.exists(dfn): os.remove(dfn) # Issue 18940: A file may not have been created if delay is True. if os.path.exists(self.baseFilename): os.rename(self.baseFilename, dfn) if self.backupCount > 0: for s in self.getFilesToDelete(): os.remove(s) if not self.delay: self.stream = self._open() newRolloverAt = self.computeRollover(currentTime) while newRolloverAt <= currentTime: newRolloverAt = newRolloverAt + self.interval #If DST changes and midnight or weekly rollover, adjust for this. if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc: dstAtRollover = time.localtime(newRolloverAt)[-1] if dstNow != dstAtRollover: if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour addend = -3600 else: # DST bows out before next rollover, so we need to add an hour addend = 3600 newRolloverAt += addend self.rolloverAt = newRolloverAt
我们观察 if os.path.exists(dfn)
这一行开始,这里的逻辑是如果 dfn 这个文件存在,则要先删除掉它,然后将 baseFilename 这个文件重命名为 dfn 文件。然后再重新打开 baseFilename这个文件开始写入东西。那么这里的逻辑就很清楚了
假设当前日志文件名为 current.log 切分后的文件名为 current.log.2016-06-01
判断 current.log.2016-06-01 是否存在,如果存在就删除
将当前的日志文件名 改名为current.log.2016-06-01
重新打开新文件(我观察到源代码中默认是”a” 模式打开,之前据说是”w”)
于是在多进程的情况下,一个进程切换了,其他进程的句柄还在 current.log.2016-06-01 还会继续往里面写东西。又或者一个进程执行切换了,会把之前别的进程重命名的 current.log.2016-06-01 文件直接删除。又或者还有一个情况,当一个进程在写东西,另一个进程已经在切换了,会造成不可预估的情况发生。还有一种情况两个进程同时在切文件,第一个进程正在执行第3步,第二进程刚执行完第2步,然后第一个进程 完成了重命名但还没有新建一个新的 current.log 第二个进程开始重命名,此时第二个进程将会因为找不到 current 发生错误。如果第一个进程已经成功创建了 current.log 第二个进程会将这个空文件另存为 current.log.2016-06-01。那么不仅删除了日志文件,而且,进程一认为已经完成过切分了不会再切,而事实上他的句柄指向的是current.log.2016-06-01。
好了这里看上去很复杂,实际上就是因为对于文件操作时,没有对多进程进行一些约束,而导致的问题。
那么如何优雅地解决这个问题呢。我提出了两种方案,当然我会在下面提出更多可行的方案供大家尝试。
先前我们发现 TimedRotatingFileHandler 中逻辑的缺陷。我们只需要稍微修改一下逻辑即可:
判断切分后的文件 current.log.2016-06-01 是否存在,如果不存在则进行重命名。(如果存在说明有其他进程切过了,我不用切了,换一下句柄即可)
以”a”模式 打开 current.log
发现修改后就这么简单~
talking is cheap show me the code:
不要以为代码那么长,其实修改部分就是 “##” 注释的地方而已,其他都是照抄源代码。这个类继承了 TimedRotatingFileHandler 重写了这个切分的过程。这个解决方案十分优雅,改换的地方非常少,也十分有效。但有网友提出,这里有一处地方依然不完美,就是rename的那一步,如果就是这么巧,同时两个或者多个进程进入了 if 语句,先后开始 rename 那么依然会发生删除掉日志的情况。确实这种情况确实会发生,由于切分文件一天才一次,正好切分的时候同时有两个Handler在操作,又正好同时走到这里,也是蛮巧的,但是为了完美,可以加上一个文件锁,if 之后加锁,得到锁之后再判断一次,再进行rename这种方式就完美了。代码就不贴了,涉及到锁代码,影响美观。
class SafeRotatingFileHandler(TimedRotatingFileHandler): def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False): TimedRotatingFileHandler.__init__(self, filename, when, interval, backupCount, encoding, delay, utc) """ Override doRollover lines commanded by "##" is changed by cc """ def doRollover(self): """ do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of matching filenames, sort them and remove the one with the oldest suffix. Override, 1. if dfn not exist then do rename 2. _open with "a" model """ if self.stream: self.stream.close() self.stream = None # get the time that this sequence started at and make it a TimeTuple currentTime = int(time.time()) dstNow = time.localtime(currentTime)[-1] t = self.rolloverAt - self.interval if self.utc: timeTuple = time.gmtime(t) else: timeTuple = time.localtime(t) dstThen = timeTuple[-1] if dstNow != dstThen: if dstNow: addend = 3600 else: addend = -3600 timeTuple = time.localtime(t + addend) dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple) ## if os.path.exists(dfn): ## os.remove(dfn) # Issue 18940: A file may not have been created if delay is True. ## if os.path.exists(self.baseFilename): if not os.path.exists(dfn) and os.path.exists(self.baseFilename): os.rename(self.baseFilename, dfn) if self.backupCount > 0: for s in self.getFilesToDelete(): os.remove(s) if not self.delay: self.mode = "a" self.stream = self._open() newRolloverAt = self.computeRollover(currentTime) while newRolloverAt <= currentTime: newRolloverAt = newRolloverAt + self.interval #If DST changes and midnight or weekly rollover, adjust for this. if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc: dstAtRollover = time.localtime(newRolloverAt)[-1] if dstNow != dstAtRollover: if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour addend = -3600 else: # DST bows out before next rollover, so we need to add an hour addend = 3600 newRolloverAt += addend self.rolloverAt = newRolloverAt
我认为最简单有效的解决方案。重写FileHandler类(这个类是所有写入文件的Handler都需要继承的TimedRotatingFileHandler 就是继承的这个类;我们增加一些简单的判断和操作就可以。
我们的逻辑是这样的:
判断当前时间戳是否与指向的文件名是同一个时间
如果不是,则切换 指向的文件即可
结束,是不是很简单的逻辑。
talking is cheap show me the code
check_baseFilename 就是执行逻辑1判断;build_baseFilename 就是执行逻辑2换句柄。就这么简单完成了。
这种方案与之前不同的是,当前文件就是 current.log.2016-06-01 ,到了明天当前文件就是current.log.2016-06-02 没有重命名的情况,也没有删除的情况。十分简洁优雅。也能解决多进程的logging问题。
class SafeFileHandler(FileHandler): def __init__(self, filename, mode, encoding=None, delay=0): """ Use the specified filename for streamed logging """ if codecs is None: encoding = None FileHandler.__init__(self, filename, mode, encoding, delay) self.mode = mode self.encoding = encoding self.suffix = "%Y-%m-%d" self.suffix_time = "" def emit(self, record): """ Emit a record. Always check time """ try: if self.check_baseFilename(record): self.build_baseFilename() FileHandler.emit(self, record) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) def check_baseFilename(self, record): """ Determine if builder should occur. record is not used, as we are just comparing times, but it is needed so the method signatures are the same """ timeTuple = time.localtime() if self.suffix_time != time.strftime(self.suffix, timeTuple) or not os.path.exists(self.baseFilename+'.'+self.suffix_time): return 1 else: return 0 def build_baseFilename(self): """ do builder; in this case, old time stamp is removed from filename and a new time stamp is append to the filename """ if self.stream: self.stream.close() self.stream = None # remove old suffix if self.suffix_time != "": index = self.baseFilename.find("."+self.suffix_time) if index == -1: index = self.baseFilename.rfind(".") self.baseFilename = self.baseFilename[:index] # add new suffix currentTimeTuple = time.localtime() self.suffix_time = time.strftime(self.suffix, currentTimeTuple) self.baseFilename = self.baseFilename + "." + self.suffix_time self.mode = 'a' if not self.delay: self.stream = self._open()
当然还有其他的解决方案,例如由一个logging进程统一打日志,其他进程将所有的日志内容打入logging进程管道由它来打理。还有将日志打入网络socket当中也是同样的道理。
python logging 官方文档
林中小灯的切分方案,方案一就是从这儿来的
The above is the detailed content of In-depth understanding of python logging module. For more information, please follow other related articles on the PHP Chinese website!