alizeyn
alizeyn

Reputation: 2420

Format type in logging

I know basics of string formats in python but I can't understand format used in the basicConfig method of logging !

FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT) 

see Document

What is purpose of %(string)s type format and when they are used?

Upvotes: 1

Views: 1158

Answers (1)

falsetru
falsetru

Reputation: 369494

It's printf-style formating.

The right operand of % can be tuple or a dictionary (or other mapping).

When the tuple is used, %d, %s, .... are replaced with corresponding item in order.

When the dictionary is used, %(key)d, %(key)s, ... are replaced with the value of corresponding key in the dictionary.

For example,

>>> FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
>>> FORMAT % {'asctime': '2017-02-11', 'clientip': '1.2.3.4',
              'user': 'who', 'message': 'blah'}
'2017-02-11      1.2.3.4 who      blah'

Using of %(key)d / dictionary has some benefits:

  • You don't need to specify format specifier in order.
  • You can repeat same key multiple times: '%(num)d + %(num)d = %(double)d' % {'num': 3, 'double': 3 * 2}

Upvotes: 4

Related Questions