Common methods of logging in Python

Source: Internet
Author: User

Logging common
#-*-Coding:utf-8-*-__author__ = "lgj" Import osimport sysimport timeimport loggingfrom logging.handlers Import TimedRota Tingfilehandlerfrom instance.test Import log_level,log_nameset_level = GetAttr (logging, Log_level.upper (), None) if not Isinstance (set_level, int): Raise ValueError (' Invalid log level:%s '% log_level) # Get Logger instance, return root logger If parameter is empty, different modules most Good use different instance name logger = Logging.getlogger ("Camel") # Specify the lowest output level of the log, default to warn level Logger.setlevel (log_level) # Specifies the logger output format formatter = logging. Formatter ('% (asctime) s% (filename) s [line:% (Lineno) d]% (funcName) s% (levelname) s% (message) s% (process) d ') # File log log_p Ath = Os.path.realpath (OS.GETCWD ()) + '/log/' File_handler = logging. Filehandler (Log_path + log_name + ". Log") File_handler.setformatter (Formatter) # can specify output format via Setformatter # console log Console_ Handler = logging. Streamhandler (sys.stdout) Console_handler.formatter = Formatter # can also be assigned directly to formatter # log rotation--with File_ Handler will cause the log to print repeatedly when it is present--for details see the following log duplication problem Timerotatinghandler = Timedrotatingfilehandler (log_Path + '%s.log '% (log_name), when= ' Midnight ') timerotatinghandler.setformatter (formatter) Timerotatinghandler.suffix = "_%y%m%d.log" # added log processor Logger.addhandler (File_handler) Logger.addhandler (Console_handler) for logger Logger.addhandler (Timerotatinghandler) # outputs different levels of loglogger.debug (' This was debug Info ') Logger.info (' This is information ') Logger.warn (' This was warning message ') logger.error (' This is the error message ') Logger.fatal (' This is the fatal message, it is SA Me as Logger.critical ') logger.critical (' This is critical message ')
Two ways of log rotation
# MyApp Initialization Works logger = Logging.getlogger (' MyApp ') logger.setlevel (logging.info) 1, using timedrotatingfilehandler# Define a handler of 1 seconds to change the log file, leaving 3 old log files Rotating_handler = Logging.handlers.TimedRotatingFileHandler ("Log/myapp.log", When= ' S ', interval=1, backupcount=3) # set suffix name, same as strftime format rotating_handler.suffix = "%y-%m-%d_%h-%m-%s.log" Logger.addhandler (Rotating_handler) # tested, and has the effect of rotation but the number of reserved files There is a problem # Note: The format of the Filehanlder.suffix must be written so that the old file can be deleted automatically, if the setting is days, it must be written " %y-%m-%d.log ", written in other formats will cause the deletion of the old file does not take effect, this configuration can be seen in the source code. While True:time.sleep (1) logger.info ("Test") 2, writes the file using rotatingfilehandler#, and retains only 5 files if the file exceeds 100 bytes. Handler = Logging.handlers.RotatingFileHandler (' Log/myapp.log ', maxbytes=100, backupcount=5) Logger.addhandler ( Handler) # Good effect while True:time.sleep (0.01) logger.info ("File Test") timedrotatingfilehandler (filename [, when [, Interv Al [, Backupcount]]] filename is the prefix of the output log file name, such as Log/myapp.logwhen is a string defined as follows: "S": Seconds "M": Minutes "H": Hours "D": Days " W ": Week Day (0=monday)" Midnight ": Roll over at MidnightiNterval refers to the number of units waiting for when the time, logger will automatically rebuild the file, of course, the creation of this file depends on Filename+suffix, if the file has the same name as the previous file, it will automatically overwrite the previous file, So there are cases where the suffix to be defined cannot be repeated because of when. Backupcount is the number of reserved logs. The default of 0 is that logs are not deleted automatically. If you set 3, the library will determine whether there are more than 3 when the file is created, and if it is exceeded, it will be deleted from the beginning of the first creation. Note: The format of the Filehanlder.suffix must be written so that the old file can be deleted automatically, if the setting is day, it must be written "%y-%m-%d.log", written in other formats will cause the deletion of the old file does not take effect. This configuration can be seen in the source code.
Log repeat output Pit
你有可能会看到你打的日志会重复显示多次,可能的原因有很多,但总结下来就一个原因,日志中使用了重复的handler或者handler输出的文件重复了(如TimedRotatingFileHandler、RotatingFileHandler与FileHandler输出的文件相同时)。可以参考 http://python.jobbole.com/86887/ 的解释。
Reference:
    • Https://www.cnblogs.com/CJOKER/p/8295272.html
    • http://python.jobbole.com/86887/
    • 72579705

Common methods of logging in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.