簡體   English   中英

日志不在控制台中打印,也不在日志文件中寫入日志

[英]logs not printing in console nor writing in log file in logging

我有一個名為helper.py的文件

import logging
import os
from json import load

def get_config(value):
    with open('config.json','r') as f:
        result=load(f)[value]
    return result


def get_logger(name,level):
    logpath=get_config("log_path")
    if not os.path.exists(logpath):
        os.mkdir(logpath)
    logger = logging.getLogger(name)
    if not bool(logger.handlers):
        formatter = logging.Formatter('%(asctime)s.%(msecs)03d - %(name)s - %(levelname)s - %(message)s',datefmt='%Y-%m-%d %H:%M:%S')
        fh = logging.FileHandler(os.path.join(logpath,f'{get_config("log_file_name")}.log'),mode="w",encoding='utf-8')
        fh.setFormatter(formatter)
        logger.addHandler(fh)
        ch = logging.StreamHandler()
        ch.setFormatter(formatter)
        ch.setLevel(level)
        logger.addHandler(ch)
    return logger


LOGGER=get_logger("MyLogger",logging.INFO)

這是config.json

{
    "save_path" : "results/",
    "log_path" : "logs/",
    "log_file_name" : "MyLog"
}

假設我在x.py中使用來自helperLOGGER

from helper import LOGGER

logger=LOGGER

def div(x,y):
    try:
        logger.info("inside div")
        return x/y
    except Exception as e:
        logger.error(f"div failed due to {e.message if 'message' in dir(e) else e}")


我通過導入helper.LOGGER來在其他文件中使用此 LOGGER 用於記錄目的,但它沒有在控制台上打印任何內容,也沒有寫入日志文件

我的嘗試:

  • 我嘗試在StreamHandler()中添加sys.stdout它不起作用
  • 然后我嘗試設置 fh 的級別,但沒有任何效果
  • 我嘗試添加basicConfig()而不是fileHandler()但然后使用print()打印到控制台,並且日志的輸出順序不正確

請讓我知道我哪里出錯了

任何幫助表示贊賞:)

謝謝 :)

您沒有在LOGGER上設置級別,默認情況下是警告。 這就是您的信息級別日志沒有出現的原因。 Python 文檔有一個流程圖,說明何時記錄日志: https ://docs.python.org/3/howto/logging.html#logging-flow

它做的第一件事是,在 logger 向其處理程序發送日志之前,它會檢查是否為 logger啟用了級別。 您應該在 get_logger() 中添加logger.setLevel(level) get_logger()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM