Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the log level printing in python logging

Tags:

python

logging

By default when I configure the logging as below,

logging.basicConfig(filename="/tmp/Hom_Controller.log",level=logging.DEBUG)

Now in logs I get as below,

DEBUG:Hom_Controller.log:{'datetime': 'Thu Oct  5 11:27:27 2017', 'message': 'Request finished with error, response code: 401 Unauthorized', 'log_type': 'debug'}
ERROR:Hom_Controller.log:{'datetime': 'Thu Oct  5 11:28:08 2017', 'message': 'Request finished with error, response code: 401 Unauthorized', 'log_type': 'error'}

As I have already formatted my message in json format , I don't want to print the ERROR:Hom_Controller.log: or DEBUG:Hom_Controller.log

like image 203
Naggappan Ramukannan Avatar asked Apr 28 '26 05:04

Naggappan Ramukannan


2 Answers

Use the logging.formatter to format your logs to not include it.

import logging

# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

modified from : https://docs.python.org/2/howto/logging.html

like image 144
MattWBP Avatar answered Apr 29 '26 19:04

MattWBP


to fix it modify the format to your specific needs e.g.

logging.basicConfig(format='[%(asctime)s]:%(message)s',filename="/tmp/Hom_Controller.log", level=logging.DEBUG)

for more options in the format, parameter visit the official page for logging link

like image 30
rachid el kedmiri Avatar answered Apr 29 '26 18:04

rachid el kedmiri