2016-02-20 26 views
6

Mam następujące ColoeredFormatter w moim module.Rejestrowanie python DictConfig niestandardowy formater nie jest nazywany

Ale formater nie zostanie wywołany. Oczekuję "cześć" na konsoli, ale dostaję "To jest informacja o root loggerze".

Usunąłem już wszystkie pliki .pyc, ale to nie pomogło.

mymodule/__ init__.py

from MyModule.ColoredFormatter import ColoredFormatter 

__all__ = ('ColoredFormatter') 

mymodule/ColoredFormatter.py

import logging 

class ColoredFormatter(logging.Formatter): 
    def __init__(self, default): 
     self.default = default 

    def format(self, record): 
     print("hi") 
     record.msg = "hi" 
     return self.default.format(record) 

mój skrypt

import logging, logging.config, yaml 

conf=""" 
logging: 
    version: 1 
    disable_existing_loggers: true 
    root: 
    level: !!python/name:logging.NOTSET 
    handlers: [console] 
    handlers: 
    console: 
     class: logging.StreamHandler 
     stream: ext://sys.stdout 
     formatter: myFormatter 
     level: !!python/name:logging.NOTSET 

    formatters: 
    myFormatter: 
     class: !!python/name:MyModule.ColoredFormatter 
""" 
dict = yaml.parse(conf) 
logging.config.dictConfig(dict["logging"]) 

logging.info("This is an info of the root logger") 

Odpowiedz

7

w sekcji formatowania musiałem zastąpić class przez ()

import logging, logging.config, yaml 

conf=""" 
logging: 
    version: 1 
    disable_existing_loggers: true 
    root: 
    level: !!python/name:logging.NOTSET 
    handlers: [console] 
    handlers: 
    console: 
     class: logging.StreamHandler 
     stream: ext://sys.stdout 
     formatter: myFormatter 
     level: !!python/name:logging.NOTSET 

    formatters: 
    myFormatter: 
     '()': MyModule.ColoredFormatter 
""" 
dict = yaml.parse(conf) 
logging.config.dictConfig(dict["logging"]) 

logging.info("This is an info of the root logger") 
+1

Czy należy opracować jak masz do tych informacji? Nie mogłem go znaleźć nigdzie – Hagai

+0

@Hagai niektóre informacje można znaleźć w [dokumentacji logowania Python] (https://docs.python.org/3/library/logging.config.html#dictionary-schema-details). – Evert

+0

Dzięki @Evert, Trochę trudno było znaleźć, więc dla następnych generacji: można go znaleźć w sekcji "obiekty zdefiniowane przez użytkownika" https://docs.python.org/2/library/logging.config .html # obiekty zdefiniowane przez użytkownika – Hagai