程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

Make separate file output and behaivour depending on the logging level in python?

发布于2024-10-31 21:02     阅读(116)     评论(0)     点赞(2)     收藏(4)


I'm trying to do something which seems a bit unorthodox but makes sense for me in a project I'm working on. I have seen a lot of questions that are asking similar or parts of my question but couldn't find a method that works as I'd like. Maybe it's impossible to do without creating a whole library out of it, I think I might be trying to find a simple solution to a complicated task.

The idea is that I'd like to change the logging level when running the script for example: debug, info, warning and so on. But I'd like to have separate output files for each level, so debug.txt, info.txt, warning.txt. I would also like to have each one going to different outputs. For example, I'd like the debug and info to be sent to both file and console, while the warning to only go to console. I've found complicated methods that do this, but for example will always create a file for debug even if there are no debug messages sent, even if the whole script was set to only warning.

My application is a script that does a bunch of things and that's it. The idea is that when given to a user, I'd like them to see warnings and errors printed to a file since they don't really look at or care for a console with the exe file I send them. But then when I'm troubleshooting, I'd like to turn on debug mode and see the console output and the a debug specific log.

I tried creating different loggers and handlers, but it gets complicated. Sometimes I would get outputs in the wrong files or things don't behave as expected. I have code snippets of trials, I can clean them and post them, but I think I'm better off starting with a clean slate. The other issue is creating a file handler forces creating a new file even if it's not being used, which I don't want that. I would like to only produce a log file if there's a problem, to not confuse the user.


解决方案


If I understood correctly you want a logging system for different levels. You could use the logging module which is from pythons' standard library.

Make a class to encapsulates the logging setup. You can customize the log file name and the levels for console and file logging.

import logging

class SimpleLogger:
    def __init__(self, log_file="app.log", console_level=logging.INFO, file_level=logging.DEBUG):

        self.logger = logging.getLogger("SimpleLogger")
        self.logger.setLevel(logging.DEBUG)

        console_handler = logging.StreamHandler()
        console_handler.setLevel(console_level)

        file_handler = logging.FileHandler(log_file)
        file_handler.setLevel(file_level)

        self.logger.addHandler(console_handler)
        self.logger.addHandler(file_handler)

    def debug(self, message):
        self.logger.debug(message)

    def info(self, message):
        self.logger.info(message)

    def warning(self, message):
        self.logger.warning(message)

    def error(self, message):
        self.logger.error(message)

    def critical(self, message):
        self.logger.critical(message)

logger = SimpleLogger()

message = "string"
logger.debug(f"{message} (file only)")
logger.warning(f"{message} (console and file)")

Just simply create a SimpleLogger instance using different parameters.

error_logger = SimpleLogger("error.txt", console_level=logging.ERROR, file_level=logging.ERROR )


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/2040409/b5930c137d32987028d8/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

2 0
收藏该文
已收藏

评论内容:(最多支持255个字符)