6

私は次のloggingようなPythonのモジュールを使用しています:

class InitLogging():
    def LogModule(self):
        self.Logger          = logging.getLogger("_TCP_Logger")
        self.Logger.LogLevel = logging.DEBUG
        self.Logger.setLevel(self.Logger.LogLevel)
        self.fh              = logging.FileHandler("Log.txt")
        self.fh.level        = logging.DEBUG
        self.formatter       = logging.Formatter('%(asctime)s %(levelname)s %(message)8s')
        self.Logger.addHandler(self.fh)        
        self.Logger.log(logging.INFO,"=====================================")
        self.Logger.log(logging.INFO,"Start Logging Module!!")
        self.Logger.log(logging.INFO,"=====================================")
        self.fh .setFormatter(self.formatter)
        self.Logger.log(logging.INFO,"Enrty to Logging Module!!")

class LogMsg(InitLogging):
    def Logit(self):
        self.LogModule()
        self.Logger.log(logging.DEBUG,'This is Debugging Message!!')
        self.Logger.log(logging.INFO,"This is Info Message!!")
        self.Logger.log(logging.WARNING,"This is WARNING Message!!")

LoggingInstance = LogMsg()
LoggingInstance.Logit()

コードを実行すると、以下の出力が得られますLog.txt

=====================================
Start Logging Module!!
=====================================

2013-03-20 17:51:35,135 INFO Enrty to Logging Module!!
2013-03-20 17:51:35,135 DEBUG This is Debugging Message!!
2013-03-20 17:51:35,135 INFO This is Info Message!
2013-03-20 17:51:35,135 WARNING This is WARNING Message!!

しかし、さまざまなログ レベルのメッセージをまとめて、以下のような出力を生成したいと考えています。

=====================================
Start Logging Module!!
=====================================
2013-03-20 17:51:35,135 INFO       Enrty to Logging Module!!
2013-03-20 17:51:35,135 DEBUG      This is Debugging Message!!
2013-03-20 17:51:35,135 INFO       This is Info Message!
2013-03-20 17:51:35,135 WARNING    This is WARNING Message!!

これどうやってするの?

4

1 に答える 1

14

levelnameフォーマッタのフォーマット文字列でフィールドに幅を追加します。

これは左揃えです:

self.formatter = logging.Formatter('%(asctime)s %(levelname)-10s %(message)s')

                         levelname
                       |----------|
2013-03-20 16:46:50,573 INFO       Enrty to Logging Module!!
2013-03-20 16:46:50,573 DEBUG      This is Debugging Message!!
2013-03-20 16:46:50,573 INFO       This is Info Message!!
2013-03-20 16:46:50,573 WARNING    This is WARNING Message!!

これは右揃えです:

self.formatter = logging.Formatter('%(asctime)s %(levelname)10s %(message)s')

                         levelname
                       |----------|
2013-03-20 16:51:04,648       INFO Enrty to Logging Module!!
2013-03-20 16:51:04,650      DEBUG This is Debugging Message!!
2013-03-20 16:51:04,650       INFO This is Info Message!!
2013-03-20 16:51:04,650    WARNING This is WARNING Message!!
                       |0123456789|
                       | width=10 |

文字列フォーマットのドキュメント

于 2013-03-20T12:48:12.980 に答える