18

I'm using the python logging module with the "native" configuration file support (config.fileconfig) as describe in the documentation here :

http://docs.python.org/library/logging.html (see the logging.conf file)

I was wondering if it's possible to supply a tabulated data format in the configuration file:

The sample configuration file is the following:

[formatter_simpleFormatter]  
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

I though that using the \t in the format would be enough but it doesn't:

format=%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s\t  

I tried a couple of things without success. I suppose it's really easy to do but I don't find it!

How can I do that?

ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
yorjo
  • 1,699
  • 3
  • 12
  • 14

2 Answers2

41

Sorry for coming late to the party, but the info could be useful for others also ...

I also wanted a tabulated looking log, especially the "levelname" field

my format was looking like this

format = %(asctime)s - %(levelname)s - %(name)s - %(message)s  

which made my logs look something like this

2014-10-01 17:42:54,261 - INFO - internal.....
2014-10-01 17:43:09,700 - DEBUG - internal.....
2014-10-01 17:44:02,994 - WARNING - internal.....
2014-10-01 17:44:31,686 - CRTITICAL - internal.....

my solution was to change the format like this

format = %(asctime)s - %(levelname)-8s - %(name)s - %(message)s  

which turned my logs in something like this

2014-10-01 17:42:54,261 - INFO     - internal.....
2014-10-01 17:43:09,700 - DEBUG    - internal.....
2014-10-01 17:44:02,994 - WARNING  - internal.....
2014-10-01 17:44:31,686 - CRITICAL - internal.....

The "8" is the length of the longest string that is expected there, in this case, "CRITICAL". The "-" tells to right-pad the string

side-note: doing

print "-%3s-" % "abcd"

will output

-abcd-

... the string doesn't get truncated

adamjhc
  • 5
  • 2
Lohmar ASHAR
  • 1,639
  • 14
  • 18
7

Have you tried entering a literal tab character in the config file instead of \t? This works for me.

Tamás
  • 47,239
  • 12
  • 105
  • 124
  • 6
    This will only work until someone who has setting in their IDE to convert tabs to spaces will open and save your file. – Alexei Tenitski Jul 15 '11 at 21:44
  • @AlexeiTenitski If you are using windows, you can enter literal tab in notepad then be careful when editing it in your preferred IDE (VSC in my case) to not replace tabs with spaces. – Anthony Sep 30 '20 at 01:40