zoukankan      html  css  js  c++  java
  • logging将日志写入文件filehandler

    import logging
    logger = logging.getLogger()
    logger.setLevel(level = logging.INFO) #可以不设,默认是WARNING级别
    handler = logging.FileHandler("log.txt")
    handler.setLevel(logging.INFO)#可以不设,默认是WARNING级别
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 
    handler.setFormatter(formatter) #设置文件的log格式
    logger.addHandler(handler)
    logger.info(
    "Start print log") logger.debug("Do something") logger.warning("Something maybe fail.") logger.info("Finish")

    利用FileHandler将log写入文件,比basicConfig的好处是想写到哪个文件就写到哪个,basicConfig是一旦设置就不能更改

    注:个人理解:handler是控制log文件的,logger是控制程序文件的,logger.addHandler(handler)确定程序的log要写到哪个文件

     注:

    logger.setLevel(level = logging.INFO)和
    handler.setLevel(logging.INFO)
    

     都会生效,最后写入的是满足两个要求的数据

    注意一点,FileHandler里面默认写log文件中中文的编码方式是GBK,而Python读取文件方式是utf-8,所以如果用默认的编码方式的话,pycharm读取log文件后会乱码

    解决方式是,进到FileHandler中,把初始化函数改成如下

    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):

     多个log文件的例子

    下面程序是将一个程序内的不同log写到两个文件

    import logging
    logger=logging.getLogger()
    logger.setLevel(level=logging.INFO)
    filehandle01=logging.FileHandler("log01.txt")
    filehandle02=logging.FileHandler("log02.txt")
    
    filehandle02.setLevel(logging.ERROR)
    formatter01=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    formatter02=logging.Formatter('%(asctime)s - %(filename)s - %(levelname)s - %(lineno)s-%(message)s')
    
    filehandle01.setFormatter(formatter01)
    filehandle02.setFormatter(formatter02)
    
    logger.addHandler(filehandle01)
    logger.addHandler(filehandle02)
    
    logger.info("Start print log")
    logger.debug("Do something")
    logger.warning("Something maybe fail")
    logger.info("Finish")
    logger.error("error print log")

    log01文件内容

    2020-03-25 15:52:41,006 - root - INFO - Start print log
    2020-03-25 15:52:41,006 - root - WARNING - Something maybe fail
    2020-03-25 15:52:41,006 - root - INFO - Finish
    2020-03-25 15:52:41,006 - root - ERROR - error print log

    log02文件内容

    2020-03-25 15:52:41,006 - trylog.py - ERROR - 22-error print log

     下面是将两个程序文件的log写到一个log文件

    程序文件1

    import logging
    file1logger=logging.getLogger()
    file1logger.setLevel(level=logging.INFO)
    handler=logging.FileHandler("log.txt")
    handler.setLevel(logging.INFO)
    formatter=logging.Formatter('time:%(asctime)s  - %(levelname)s-line:%(lineno)s - %(message)s')
    handler.setFormatter(formatter)
    file1logger.addHandler(handler)
    
    
    print("this is file1's log")
    file1logger.warning("this is file1's log")

    程序文件2

    import logging
    file1logger=logging.getLogger()
    file1logger.setLevel(level=logging.INFO)
    handler=logging.FileHandler("log.txt")
    handler.setLevel(logging.INFO)
    formatter=logging.Formatter('time:%(asctime)s  - %(levelname)s-line:%(lineno)s - %(message)s')
    handler.setFormatter(formatter)
    file1logger.addHandler(handler)
    
    
    print("this is file2's log")
    file1logger.warning("this is file2's log")

    以上两个文件分别执行一次

    log文件:

    time:2020-07-21 17:10:00,718  - WARNING-line:12 - this is file1's log
    time:2020-07-21 17:10:04,150  - WARNING-line:12 - this is file2's log

    注:

    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')这里引号里的格式是随便的,最后程序会用Formatter参数格式化替换
    里面的格式化标准
    栗子:
    formatter = logging.Formatter('time:%(asctime)s - %(name)s - lineno:%(lineno)s - %(message)s')

    Formatter参数的官方文档

     https://docs.python.org/3.7/library/logging.html#logrecord-attributes

    Attribute name

    Format

    Description

    args

    You shouldn’t need to format this yourself.

    The tuple of arguments merged into msg to produce message, or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary).

    asctime

    %(asctime)s

    Human-readable time when the LogRecord was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond portion of the time).

    created

    %(created)f

    Time when the LogRecord was created (as returned by time.time()).

    exc_info

    You shouldn’t need to format this yourself.

    Exception tuple (à la sys.exc_info) or, if no exception has occurred, None.

    filename

    %(filename)s

    Filename portion of pathname.

    funcName

    %(funcName)s

    Name of function containing the logging call.

    levelname

    %(levelname)s

    Text logging level for the message ('DEBUG''INFO''WARNING''ERROR''CRITICAL').

    levelno

    %(levelno)s

    Numeric logging level for the message (DEBUGINFOWARNINGERRORCRITICAL).

    lineno

    %(lineno)d

    Source line number where the logging call was issued (if available).

    message

    %(message)s

    The logged message, computed as msg args. This is set when Formatter.format() is invoked.

    module

    %(module)s

    Module (name portion of filename).

    msecs

    %(msecs)d

    Millisecond portion of the time when the LogRecord was created.

    msg

    You shouldn’t need to format this yourself.

    The format string passed in the original logging call. Merged with args to produce message, or an arbitrary object (see Using arbitrary objects as messages).

    name

    %(name)s

    Name of the logger used to log the call.

    pathname

    %(pathname)s

    Full pathname of the source file where the logging call was issued (if available).

    process

    %(process)d

    Process ID (if available).

    processName

    %(processName)s

    Process name (if available).

    relativeCreated

    %(relativeCreated)d

    Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.

    stack_info

    You shouldn’t need to format this yourself.

    Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record.

    thread

    %(thread)d

    Thread ID (if available).

    threadName

    %(threadName)s

    Thread name (if available).

  • 相关阅读:
    ACM-ICPC 2018 徐州赛区网络预赛 F Features Track(STL模拟)
    ACM-ICPC 2018 徐州赛区网络预赛 H Ryuji doesn't want to study (树状数组差分)
    数位dp
    Number String
    The King’s Ups and Downs
    容斥定理
    Anagram(山东省2018年ACM浪潮杯省赛)
    STL——queue
    lower_bound和upper_bound使用说明
    int string相互转换
  • 原文地址:https://www.cnblogs.com/mghhzAnne/p/12307751.html
Copyright © 2011-2022 走看看