最後更新: 2020-03-27
目錄
- basicConfig
- Log Rotating
- Basic log function(不調用 logging module)
basicConfig
logging.basicConfig([**kwargs])
Does basic configuration for the logging system
by creating a StreamHandler with a default Formatter and adding it to the root logger.
keyword arguments
- filename
- filemode
- format
- datefmt
- level
- stream
mylog.py
#!/usr/bin/env python # coding=utf-8 # vim: sts=4:ts=4:sw=4:paste import logging, os def main(): scriptpath = os.path.dirname(os.path.realpath(__file__)) scriptname = os.path.splitext(os.path.basename(__file__))[0] logfile = os.path.join(scriptpath, scriptname + '.log') FORMAT = '%(asctime)s - %(name)s %(levelname)s: %(message)s' # logging.basicConfig(filename=logfile, # level=logging.DEBUG, # format=FORMAT) logging.basicConfig(filename=logfile) logging.debug('This debug message.') logging.info('No info message.') logging.warning('No warning message.') if __name__ == '__main__': main()
Settings
filemode
If filename is specified, open the file in this mode. Defaults to 'a'.
level
高過或等於這個 Level 的 log 才會有 log 到.
Default: WARNING
Other Level
- logging.INFO
- logging.DEBUG
format
Default: %(levelname)s:%(name)s:%(message)s
WARNING:root:This is warning message.
* 由於 default 係無 log 到時間, 所以最好設定 log 返它
Log Rotating
以 log size 去 rotate log
test.py
import logging, logging.handlers def main(): LogFile = 'log.txt' myLogger = logging.getLogger('MyLogger') myLogger.setLevel(logging.DEBUG) handler = logging.handlers.RotatingFileHandler( LogFile, maxBytes=20, backupCount=5) # class logging.Formatter([fmt[, datefmt]]) # If none is supplied, the default value of '%(message)s' is used. LogFormat = '%(asctime)s - %(name)s %(levelname)s: %(message)s' formatter = logging.Formatter(LogFormat) handler.setFormatter(formatter) myLogger.addHandler(handler) # Log some messages leg it over maxBytes for i in range(50): myLogger.debug('i = %d' % i) # Test if __name__ == '__main__': main()
logging.getLogger([name])
Return a logger with the specified name.
If 'name' specified, the name is typically a dot-separated hierarchical name like “a”, “a.b” or “a.b.c.d”.
%(name)s
Name of the logger used to log the call.
Output:
ls -1
log.txt log.txt.1 ... log.txt.5
msg
2022-11-02 13:06:42,969 - MyLogger DEBUG: i = 49
轉成以時間去 log Rotating
# 將 RotatingFileHandler 換成 TimedRotatingFileHandler
handler = logging.handlers.TimedRotatingFileHandler( LogFile, when='D', backupCount=7)
located in the "logging.handlers" module
"when" to specify the type of interval
- 'S' Seconds
- 'M' Minutes
- 'H' Hours
- 'D' Days
- 'W0'-'W6' Weekday (0=Monday)
- 'midnight' Roll over at midnight
On rotating it also sets the filename suffix: %Y-%m-%d_%H-%M-%S
Code to check Rollover time
current_time = int(time.time()) rollover_time = handler.computeRollover(current_time) rollover_time_midnight = handler_midnight.computeRollover(current_time)
Modify time tigger Rollover
date # Lab 的時間
Thu 03 Nov 2022 11:28:36 AM HKT
touch -m 202211011234 log.txt # 修改 modify time 測試
stat log.txt # 查看 log file 的 modify time
...
Modify: 2022-11-01 12:34:00.000000000 +0800
# After Rotate
在 3 號行 Rotate 時建立的檔案名稱後綴係 modify date (01)
log.txt.2022-11-01
Basic log function(不調用)
使用 open 及 write 完成
Code
def logf(msg): print msg import os, time today = time.strftime("%Y-%m-%d") scriptpath = os.path.dirname(os.path.realpath(__file__)) logfile = os.path.join(scriptpath, 'log.' + today + '.txt') mylog = open(logfile, 'a') mylog.write(time.strftime("%Y-%m-%H %H:%M:%S") + ": " + msg + os.linesep) mylog.close return True