创建一个简单的Logger
import logging
logging.basicConfig(filename="sample.log", level=logging.INFO) #如果不配置basicConfig,会输出到控制台
logging.debug("debug message")
logging.info("info message")
logging.error("error message")
# sample.log文件信息(注意debug信息并未在文件中)
# INFO:root:info message
# ERROR:root:error message
# log some exceptions to file
import logging
logging.basicConfig(filename="sample.log", level=logging.INFO)
log=logging.getLogger("exception")
try:
raise RuntimeError
except RuntimeError:
log.exception("Error!")
# sample.log文件信息
# Traceback (most recent call last):
# File "D:/Projects/Python/logging_test.py", line 15, in log_exceptions_to_file
# raise RuntimeError
# RuntimeError
多个模块的日志写入同一个文件
# otherMod.py
import logging
def add(x,y):
logging.info("add %s and %s to get %s"%(x,y,x+y))
return x+y
# logging_test.py
import logging
import otherMod
def main():
logging.basicConfig(filename="mySnake.log", level=logging.INFO)
logging.info("Program started")
result = otherMod.add(7, 8)
logging.info("Done!")
if __name__ == '__main__':
main()
# mySnake.log文件信息(不知道日志信息来自哪里)
# INFO:root:Program started
# INFO:root:add 7 and 8 to get 15
# INFO:root:Done!
# otherMod2.py
import logging
module_logger=logging.getLogger("exampleApp.otherMod2") # logger名字前缀必须添加exampleApp
def add(x,y):
logger=logging.getLogger("exampleApp.otherMod2.add") # logger名字前缀必须添加exampleApp
logger.info("added %s and %s to get %s" %(x,y,x+y))
return x+y
# logging_test2.py
import logging
import otherMod2
def main():
logger=logging.getLogger("exampleApp")
logger.setLevel(logging.INFO)
# 设置日志文件的格式
fh=logging.FileHandler("new_snake.log")
formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
# 其它模块的日志想要写入new_snake.log文件,则其logger名字的前缀必须添加exampleApp
logger.addHandler(fh)
logger.info("Program Started")
result=otherMod2.add(7,8)
logger.info("Done!")
if __name__ == '__main__':
main()
# new_snake.log文件信息(通过logger名字可以直到)
# 2020-07-23 05:57:53,653 - exampleApp - INFO - Program Started
# 2020-07-23 05:57:53,653 - exampleApp.otherMod2.add - INFO - added 7 and 8 to get 15
# 2020-07-23 05:57:53,653 - exampleApp - INFO - Done!
使用配置文件
logging.conf
配置文件
root logger
是必须的,否则会抛出 ValueError
,如果把 root logger
的 handler
设置为 filehandler
,日志文件的输出会变成双倍(doubling the log output
),为了防止这个发生,把 root logger
的 handler
设置为 consoleHandler
。
[loggers]
keys=root,exampleApp
[handlers]
keys=fileHandler, consoleHandler
[formatters]
keys=myFormatter
[logger_root]
level=CRITICAL
handlers=consoleHandler
[logger_exampleApp]
level=INFO
handlers=fileHandler
qualname=exampleApp
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=myFormatter
args=(sys.stdout,)
[handler_fileHandler]
class=FileHandler
formatter=myFormatter
args=("config.log",)
[formatter_myFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
# log_with_conf.py
import logging
import logging.config
import otherMod2
def main():
logging.config.fileConfig('logging.conf')
logger=logging.getLogger("exampleApp")
logger.info("Program Started")
result=otherMod2.add(7,8)
logger.info("Done!")
if __name__ == '__main__':
main()
# config.log文件信息
# 2020-07-23 05:57:53,653 - exampleApp - INFO - Program Started
# 2020-07-23 05:57:53,653 - exampleApp.otherMod2.add - INFO - added 7 and 8 to get 15
# 2020-07-23 05:57:53,653 - exampleApp - INFO - Done!