简体   繁体   中英

python's logging module is not logging to a log file

I am trying out python's logger module to log info both in console and in a log and it works fine.I wanted that script to get invoked during machine star-tup and hence invoked my script from rc.local.

And my script gets invoked during boot-up, but the problem is, only console logging is working at that time. Logging to a file is not happening. Any clue on what could be the issue.

Is it anything related to syslog daemon?

import time
import logging
import datetime

global logger
global LOG_FILE

def initialize():
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)

    time = datetime.datetime.now()
    LOG_FILE = "sample.log." + time.strftime("%Y%m%d")
    log_file_handler = logging.FileHandler(LOG_FILE)
    log_file_handler.setLevel(logging.DEBUG)
    log_file_formatter = logging.Formatter('%(message)s')
    log_file_handler.setFormatter(log_file_formatter)
    logger.addHandler(log_file_handler)

    log_file_handler = logging.StreamHandler()
    log_file_handler.setLevel(logging.INFO)
    log_file_formatter = logging.Formatter('%(message)s')
    log_file_handler.setFormatter(log_file_formatter)    
    logger.addHandler(log_file_handler)


if __name__ == '__main__':
    initialize()
    logger.info("This should go both in console and log")
    logger.debug("This should go only to Log")
import time
import logging
import datetime

def initialize():
    # because logging is global module, so you can 
    # always get logger by logging.getLogger(__name__)
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)

    time = datetime.datetime.now()
    # if you only use LOG_FILE in function, you don't
    # have to declare it outside.
    LOG_FILE = "sample.log." + time.strftime("%Y%m%d")
    log_file_handler = logging.FileHandler(LOG_FILE)
    log_file_handler.setLevel(logging.DEBUG)
    log_file_formatter = logging.Formatter('%(message)s')
    log_file_handler.setFormatter(log_file_formatter)
    logger.addHandler(log_file_handler)

    log_file_handler = logging.StreamHandler()
    log_file_handler.setLevel(logging.INFO)
    log_file_formatter = logging.Formatter('%(message)s')
    log_file_handler.setFormatter(log_file_formatter)
    logger.addHandler(log_file_handler)


if __name__ == '__main__':
    initialize()
    logger = logging.getLogger(__name__)
    logger.info("This should go both in console and log")
    logger.debug("This should go only to Log")

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