python日志logging

Posted Tarzen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python日志logging相关的知识,希望对你有一定的参考价值。

一、logging基本https://www.cnblogs.com/huaizhi/p/11245246.html


import logging

logging.basicConfig() ---默认项 只会打印在控制台,没有指定文件目录
logging.debug(\'This is a debug message\')
logging.info(\'This is an info message\')
logging.warning(\'This is a warning message\')
logging.error(\'This is an error message\')
logging.critical(\'This is a critical message\')
=========== 默认配置项,只会打印warning级别以及以上级别

WARNING:root:This is a warning message
ERROR:root:This is an error message
CRITICAL:root:This is a critical message

 

添加参数后:

import logging

logging.basicConfig(filename=\'log.text\', filemode=\'w\', format="%(asctime)s  %(name)s  %(levelname)s:%(message)s",
                    datefmt=\'%d-%M-%Y %H:%M:%S\', level=logging.INFO)     --指定了文件后,就不会再控制台打印,会直接存到指定文件中

logging.debug(\'This is a debug message\')
logging.info(\'This is an info message\')
logging.warning(\'This is a warning message\')
logging.error(\'This is an error message\')
logging.critical(\'This is a critical message\')


try:
    print(5 / 0)
except Exception as e:
    logging.exception(\'occurred\')      --可以打印出具体的问题。

 

二、logger自定义(实现控制台和输入文件中):

import logging
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter(\'%(asctime)s - %(name)s - %(levelname)s - %(message)s\')
handler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.DEBUG)

logger.addHandler(handler)
logger.addHandler(console)

logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
try:
open("sklearn.txt", "rb")
except (SystemExit, KeyboardInterrupt):
raise
except Exception:
logger.error("Faild to open sklearn.txt from logger.error", exc_info=True)

logger.info("Finish")

 

 

 

三.实现一个py文件一个日志,且日志大于5M自动覆盖https://www.cnblogs.com/yfacesclub/p/9001073.html

以上是关于python日志logging的主要内容,如果未能解决你的问题,请参考以下文章

我的Android进阶之旅NDK开发之在C++代码中使用Android Log打印日志,打印出C++的函数耗时以及代码片段耗时详情

python分析apache和nginx日志文件输出访客ip列表的代码

webstorm代码片段的创建

日志片段,类中的Logfactory声明

Shell脚本切割日志

Python logging模块日志存储位置踩坑