簡體   English   中英

如何在 Python 中的日志文件中寫入標題

[英]How to Write Headers in Log File in Python

我已經做了一個日志文件。 現在我想在日志文件中打印一個標題。 這樣人們就可以確定該列的用途。

我已經提供了我編寫的代碼。

def logger(type_of_message, msg, ticket_no):   #This will create records/log in app.log file. And can be used for debuging too. 
    log_file = str(datetime.utcnow().strftime('%d_%m_%Y')) + '.log'
    if(type_of_message == 'INFO' or 'Info'):
        logger = logging.LoggerAdapter(logging.getLogger(__name__), {'ticket_no': '%s' % (ticket_no)})
        logging.basicConfig(filename = log_file, filemode = 'a', level = logging.INFO, format =  '%(ticket_no)s -  %(asctime)s -  %(name)s  -  %(levelname)s - %(message)s')    
        logger.info(msg)
    elif(type_of_message == 'ERROR' or 'Error'): 
        logger = logging.LoggerAdapter(logging.getLogger(__name__), {'ticket_no': '%s'%(ticket_no)}) 
        logging.basicConfig(filename = 'app.log', filemode = 'a', level = logging.ERROR,  format  = '%(ticket_no)s - %(asctime)s -  %(name)s  -  %(levelname)s - %(message)s')
        logger.info(msg) 

我想像這樣打印:

TICKET NO       DATE        TIME         NAME    USER   MESSAGE

INC0010265 -  2019-06-25 20:41:54,286 -  log  -  INFO - Mail Send Succesfully
INC0010265 -  2019-06-25 20:41:56,271 -  log  -  INFO - INC0010265  Ticket Update Succesfully
INC0010265 -  2019-06-25 20:41:56,271 -  log  -  INFO - -----Ticket Closed-----

這不是您所要求的 100%,而是我能想到的最接近的。

首先,您不應該為同一個程序多次調用basicConfig 它實際上什么都不做......

此外,通過定義自己的檢查消息類型的函數,您有點失去logging功能。 調用logger.info獲取錯誤消息看起來很有趣。 應該做的是使用Handler s。 看看這個代碼:

import logging

logger = logging.getLogger(__name__)
log_file = str(datetime.utcnow().strftime('%d_%m_%Y')) + '.log'

error_handler = logging.FileHandler("app.log")
error_handler.setLevel(logging.ERROR)
info_handler = logging.FileHandler(log_file)
info_handler.setLevel(logging.INFO)

logger.setLevel(logging.INFO)
logger.addHandler(info_handler)
logger.addHandler(error_handler)

header_formatter = logging.Fomatter('%(message)s')
default_formatter = logging.Formatter('%(asctime)s -  %(name)s  -  %(levelname)s - %(message)s')

error_handler.setFormatter(header_formatter)
info_handler.setFormatter(header_formatter)

logger.error("DATE\t\tTIME\t\tNAME\t\tUSER\t\tTICKET NO\tMESSAGE")

error_handler.setFormatter(default_formatter)
info_handler.setFormatter(default_formatter )

幾個解釋:

  • 我們使用兩個處理程序: error_handlerinfo_handler將不同類型的消息定向到不同的文件。 請注意,通過這種方式,錯誤消息也會出現在信息文件中。
  • 我們將logger的級別設置為它們之間的最小值(在本例中為INFO )並將我們的處理程序添加到其中。
  • 然后我們對標頭和常規消息使用特殊的formatter 我們首先將標題格式化程序分配給兩個處理程序。 然后我們打印標題(使用logger.error以便它會轉到兩個日志)。 然后使用常規格式化程序設置處理程序。
  • 從此時起記錄的所有消息都將采用常規格式。

第二個注意事項:我找不到一種方法將字段添加到 fomat 中,就像您試圖為ticket_no實現的ticket_no 正如您所看到的,我將列移到了messgae 之前,因此只需在消息的開頭添加ticke_no 例如,您可以做的是:

def log_msg(logger, type_of_message, msg, ticket_no):
    msg = "{}\t{}".format(ticket_no, msg)
    if(type_of_message == 'INFO' or 'Info'):
        logger.info(msg)
    elif(type_of_message == 'ERROR' or 'Error'): 
        logger.error(msg)

暫無
暫無

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

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