Python操作日志文件

创建一个简单的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 loggerhandler 设置为 filehandler,日志文件的输出会变成双倍(doubling the log output),为了防止这个发生,把 root loggerhandler 设置为 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!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

X+Y=Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值