美文网首页
2019.07.28日记模块logging的使用

2019.07.28日记模块logging的使用

作者: 七天七念 | 来源:发表于2019-07-28 22:02 被阅读0次

1直接打印但是不存文件

import logging
logging.basicConfig(level=logging.DEBUG,format=('%(asctime)s - %(levelname)s - %(message)s'))
logging.debug('it is a debug')
#通过这种形式可以打印带时间的日记
2019-07-28 20:43:06,157 - DEBUG - it is a debug

2直接把数据存进文件里面

import logging
logging.basicConfig(filename='myProgramLog.txt',level=logging.DEBUG,format=('%(asctime)s - %(levelname)s - %(message)s'))
logging.debug('it is a debug')

当前目录下会自动生成一个myProgramLog.txt,并储存
值得注意的是当同时指定了目录,而目录不存在的时候是不会自动生成目录的

另一点,参数filename的引入以包顶级目录为依据进行引入
而在分文件里面只要如下就行,主程序py文件的设置会直接覆盖分文件

import logging
logging.debug('it is a debug')

3禁用日志数据输出的办法

import logging
logging.basicConfig(filename='stats/myProgramLog.txt',level=logging.DEBUG,format=('%(asctime)s - %(levelname)s - %(message)s'))
logging.disable()
logging.debug('it is a debug')

研究值得注意的一点,当主程序里面设置logging.disable()之后,被引用模块的日志都会关闭
format参数的分析系
asctime:表示的是现在的时间
levelname:表示的是命令的名字
message:表示的是命令输入的内容
只有%()s 把关键词包围的时候,才会当做相关设置
个人也可以直接在上面写其他的,比如
附命令集:

级别            日志函数                                描述
DEBUG        logging.debug()                    最低级别,用于小细节
INFO         logging.info()                     记录一般事件,确定工作正常
WARNING      logging.warning()                  表示可能的问题
ERROR        logging.error()                    用于记录错误
CRITICAL     logging.critical()                 最高级别表示致命的错误

以上也只是约定俗成的规矩

超级懒虫型解决logging的utf-8,中文输入失败问题

logging.basicConfig本身是没有参数设置utf-8的
那么解决办法呢?
直接转到底层代码,直接修改源码!
1070行

class FileHandler(StreamHandler):
    """
    A handler class which writes formatted logging records to disk files.
    """
    def __init__(self, filename, mode='a', encoding=None, delay=False):
        """
        Open the specified file and use it as the stream for logging.
        """
修改encoding='utf-8'

class FileHandler(StreamHandler):
    """
    A handler class which writes formatted logging records to disk files.
    """
    def __init__(self, filename, mode='a', encoding='utf-8', delay=False):
        """
        Open the specified file and use it as the stream for logging.
        """

如此的话,最简单的使用basicConfig就能直接输入中文了!~

import logging
logging.basicConfig(filename='stats/myProgramLog.txt',level=logging.DEBUG,format=('%(asctime)s - 测试不加类型你懂的!~ - %(message)s'))
logging.debug('你知道了吗?')

输入日记文本
2019-07-28 22:08:50,475 - 测试不加类型你懂的!~ - 你知道了吗?

相关文章

网友评论

      本文标题:2019.07.28日记模块logging的使用

      本文链接:https://www.haomeiwen.com/subject/cizprctx.html