简体   繁体   中英

Why did my log output three lines?

I want the correct output.

Why did my log output three lines?

my code is:

import logging
import logging.handlers
#LOG
import time

def log_info(log):
    LOG_FILENAME='log'
    # Set up a specific logger with our desired output level
    my_logger = logging.getLogger('log')
    my_logger.setLevel(logging.INFO)
    # Add the log message handler to the logger
    handler = logging.handlers.RotatingFileHandler(LOG_FILENAME,
                maxBytes=1048576,
                backupCount=5,
               )
    my_logger.addHandler(handler)
    # Log some messages
    my_logger.info(log)

def test(log):
    log_info(log=log)

for i in range(2):
    print i
    a = "1111111111111"
    b = test(a)

my result:

1111111111111
1111111111111
1111111111111

I was expecting this:

1111111111111
1111111111111

The problem is that each time you call log_info , you are calling addHandler . So the first time it's called, you add the first handler, and the text gets logged once. The second time, you add a second handler, so now everything gets logged twice.

Split the function into (a) a function that initializes the handler, and (b) a function that logs a new message. Call (a) once, and only once. After that, call (b) every time you want to log a new message (all it should do is call my_logger.info ).

So, @TomKarzes is instructing you to write your code like this:

import logging
import logging.handlers

def initialise_log():
    LOG_FILENAME = 'log'
    # Set up a specific logger with our desired output level
    my_logger = logging.getLogger('log')
    my_logger.setLevel(logging.INFO)
    # Add the log message handler to the logger
    handler = logging.handlers.RotatingFileHandler(LOG_FILENAME,
                maxBytes=1048576,
                backupCount=5,
               )
    my_logger.addHandler(handler)
    return my_logger

def test(log):
    # Log some messages
    my_logger.info(log)

my_logger = initialise_log()

for i in range(2):
    print i
    a = "1111111111111"
    b = test(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM