同一文件中的临时记录格式

发布于 2025-02-12 06:53:04 字数 2219 浏览 1 评论 0原文

我希望我在main.log中保存在main.log中,我在loggging.basicconfig()中提到的所有模块登录。格式

是代码:

文件main.py

import module1
import logging

logging.basicConfig(
    filename="main.log", 
    format="%(asctime)s , <%(name)s> , %(levelname)s : %(message)s", 
    datefmt="%Y-%m-%d %I:%M:%S",
    level=logging.DEBUG
)

def main(ip):
    lg = logging.getLogger("main")

    newformat="%(asctime)s , <%(name)s> ,  [" + ip + "] , %(levelname)s : %(message)s", 

    # do another things
    lg.debug("somthing done...")

    # call func1
    module1.func1()

    lg.debug("service done")


def main2(ip):
    lg = logging.getLogger("main")

    newformat="%(asctime)s , <%(name)s> ,  [" + ip + "] , %(levelname)s : %(message)s", 

    # do another things
    lg.debug("somthing done...")

    # call func1
    module1.func1()

    lg.debug("service done")


main("192.168.1.100")
main2("192.168.1.101")

file module1.py

import logging

def func1():

    lg = logging.getLogger("module1.func1")
    lg.setLevel(logging.DEBUG)

    # do somthing ...

    lg.debug("done")

输出是: 文件main.log

2022-07-02 05:39:51 , <main1> , DEBUG : somthing done...
2022-07-02 05:39:51 , <module1.func1> , DEBUG : done
2022-07-02 05:39:51 , <main1> , DEBUG : service done
2022-07-02 05:39:51 , <main2> , DEBUG : somthing done...
2022-07-02 05:39:51 , <module1.func1> , DEBUG : done
2022-07-02 05:39:51 , <main2> , DEBUG : service done

但我希望使用新格式:

2022-07-02 05:39:51 , <main1> , [192.168.1.100] , DEBUG : somthing done...
2022-07-02 05:39:51 , <module1.func1> , DEBUG : done
2022-07-02 05:39:51 , <main1> , [192.168.1.100] , DEBUG : service done
2022-07-02 05:39:51 , <main2> , [192.168.1.101] , DEBUG : somthing done...
2022-07-02 05:39:51 , <module1.func1> , DEBUG : done
2022-07-02 05:39:51 , <main2> , [192.168.1.101] , DEBUG : service done

i want all modules logs that import to the main.py save in main.log that i mention in logging.basicConfig() but with their formats

here is the code:

file main.py

import module1
import logging

logging.basicConfig(
    filename="main.log", 
    format="%(asctime)s , <%(name)s> , %(levelname)s : %(message)s", 
    datefmt="%Y-%m-%d %I:%M:%S",
    level=logging.DEBUG
)

def main(ip):
    lg = logging.getLogger("main")

    newformat="%(asctime)s , <%(name)s> ,  [" + ip + "] , %(levelname)s : %(message)s", 

    # do another things
    lg.debug("somthing done...")

    # call func1
    module1.func1()

    lg.debug("service done")


def main2(ip):
    lg = logging.getLogger("main")

    newformat="%(asctime)s , <%(name)s> ,  [" + ip + "] , %(levelname)s : %(message)s", 

    # do another things
    lg.debug("somthing done...")

    # call func1
    module1.func1()

    lg.debug("service done")


main("192.168.1.100")
main2("192.168.1.101")

file module1.py

import logging

def func1():

    lg = logging.getLogger("module1.func1")
    lg.setLevel(logging.DEBUG)

    # do somthing ...

    lg.debug("done")

the output is:
file main.log

2022-07-02 05:39:51 , <main1> , DEBUG : somthing done...
2022-07-02 05:39:51 , <module1.func1> , DEBUG : done
2022-07-02 05:39:51 , <main1> , DEBUG : service done
2022-07-02 05:39:51 , <main2> , DEBUG : somthing done...
2022-07-02 05:39:51 , <module1.func1> , DEBUG : done
2022-07-02 05:39:51 , <main2> , DEBUG : service done

but i want this with new format:

2022-07-02 05:39:51 , <main1> , [192.168.1.100] , DEBUG : somthing done...
2022-07-02 05:39:51 , <module1.func1> , DEBUG : done
2022-07-02 05:39:51 , <main1> , [192.168.1.100] , DEBUG : service done
2022-07-02 05:39:51 , <main2> , [192.168.1.101] , DEBUG : somthing done...
2022-07-02 05:39:51 , <module1.func1> , DEBUG : done
2022-07-02 05:39:51 , <main2> , [192.168.1.101] , DEBUG : service done

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

诺曦 2025-02-19 06:53:05

我找到了一种使用logging.loggeradapter(Logger,{parameters})

您可以将vars传递给日志格式的

方法,因此我编写了一个函数来返回logger和format and format and andlers and Handlers。

def get_logger(name:str, path:str, ip:bool = False, format: bool or str = False) -> logging.Logger:
    
    fmt = format if format else f"%(asctime)s , <%(name)s> , {' [%(ip)s] ,' if ip else ''} , %(levelname)s : %(message)s"

    logConf = logging.getLogger(name)
    # set level of logger
    logConf.setLevel(get_log_level())
    # stream handler for Errors 
    stream_handler = logging.StreamHandler()
    # set level of this stream handler
    stream_handler.setLevel(logging.WARNING)
    stream_handler.setFormatter(logging.Formatter(fmt))
    logConf.addHandler(stream_handler)
    # file handler
    file_handler = logging.FileHandler(path)
    # set level of this file handler
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(logging.Formatter(fmt))
    logConf.addHandler(file_handler)

    return logConf

并在每个模块主体中调用此功能,并使用logging.logger.adapter()

module1.py

ip = get_ip_from_some_where()

lgConfig = get_logger(__name__, "module1.log", ip=True)
lg = logging.LoggerAdapter(lgConfig, {"ip": ip})
lg.setLevel(logging.debug) # make sure to set level

lg.info('started')
# some codes
lg.info('done')

或您可以将其用于函数和伐木链中
module2.py

ip = get_ip_from_some_where()

lgConfig = get_logger(__name__, "module1.log", ip=True)

def func1():
    lg = logging.getLogger("__name__.func1") # define func1 as a chain of __name__
    lg = logging.LoggerAdapter(lg, {"ip": ip})
    lg.setLevel(logging.debug) # make sure to set level

    # do something

    lg.info('started')
    # some codes
    lg.info('done')

func1()

I found a way with logging.LoggerAdapter(logger, {parameters})

you can pass vars to log format

so I wrote a function to return logger and format and handlers want.

def get_logger(name:str, path:str, ip:bool = False, format: bool or str = False) -> logging.Logger:
    
    fmt = format if format else f"%(asctime)s , <%(name)s> , {' [%(ip)s] ,' if ip else ''} , %(levelname)s : %(message)s"

    logConf = logging.getLogger(name)
    # set level of logger
    logConf.setLevel(get_log_level())
    # stream handler for Errors 
    stream_handler = logging.StreamHandler()
    # set level of this stream handler
    stream_handler.setLevel(logging.WARNING)
    stream_handler.setFormatter(logging.Formatter(fmt))
    logConf.addHandler(stream_handler)
    # file handler
    file_handler = logging.FileHandler(path)
    # set level of this file handler
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(logging.Formatter(fmt))
    logConf.addHandler(file_handler)

    return logConf

and call this function in each module body and pass IP with logging.Logger.Adapter()

module1.py

ip = get_ip_from_some_where()

lgConfig = get_logger(__name__, "module1.log", ip=True)
lg = logging.LoggerAdapter(lgConfig, {"ip": ip})
lg.setLevel(logging.debug) # make sure to set level

lg.info('started')
# some codes
lg.info('done')

or you can use it in functions and logging chain
module2.py

ip = get_ip_from_some_where()

lgConfig = get_logger(__name__, "module1.log", ip=True)

def func1():
    lg = logging.getLogger("__name__.func1") # define func1 as a chain of __name__
    lg = logging.LoggerAdapter(lg, {"ip": ip})
    lg.setLevel(logging.debug) # make sure to set level

    # do something

    lg.info('started')
    # some codes
    lg.info('done')

func1()
烟沫凡尘 2025-02-19 06:53:04

不是最好的解决方案,但这应该完成工作

import module1
import logging

logging.basicConfig(
    filename="main.log",
    format="%(asctime)s , <%(name)s> , %(levelname)s : %(message)s",
    datefmt="%Y-%m-%d %I:%M:%S",
    level=logging.DEBUG
)


def setBasicConfigFormat(format):
    ROOT_LOGGER = logging.getLogger()
    ROOT_LOGGER.handlers[0].setFormatter(logging.Formatter(
        format
    ))


def main(ip):
    lg = logging.getLogger("main")

    newformat = "%(asctime)s , <%(name)s> ,  [" + \
        ip + "] , %(levelname)s : %(message)s"
    setBasicConfigFormat(newformat)

    # do another things
    lg.debug("somthing done...")

    # call func1
    module1.func1()

    lg.debug("service done")


def main2(ip):
    lg = logging.getLogger("main")

    newformat = "%(asctime)s , <%(name)s> ,  [" + \
        ip + "] , %(levelname)s : %(message)s"
    setBasicConfigFormat(newformat)
    # do another things
    lg.debug("somthing done...")

    # call func1
    module1.func1()

    lg.debug("service done")


main("192.168.1.100")
main2("192.168.1.101")

Not the best solution but this should get the job done

import module1
import logging

logging.basicConfig(
    filename="main.log",
    format="%(asctime)s , <%(name)s> , %(levelname)s : %(message)s",
    datefmt="%Y-%m-%d %I:%M:%S",
    level=logging.DEBUG
)


def setBasicConfigFormat(format):
    ROOT_LOGGER = logging.getLogger()
    ROOT_LOGGER.handlers[0].setFormatter(logging.Formatter(
        format
    ))


def main(ip):
    lg = logging.getLogger("main")

    newformat = "%(asctime)s , <%(name)s> ,  [" + \
        ip + "] , %(levelname)s : %(message)s"
    setBasicConfigFormat(newformat)

    # do another things
    lg.debug("somthing done...")

    # call func1
    module1.func1()

    lg.debug("service done")


def main2(ip):
    lg = logging.getLogger("main")

    newformat = "%(asctime)s , <%(name)s> ,  [" + \
        ip + "] , %(levelname)s : %(message)s"
    setBasicConfigFormat(newformat)
    # do another things
    lg.debug("somthing done...")

    # call func1
    module1.func1()

    lg.debug("service done")


main("192.168.1.100")
main2("192.168.1.101")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文