I am using the following code. Still my logs are being printed both in console and log file. Can anyone please help me to identify how to stop printing log in the console
logger = logging.getLogger('MyLog')
logger.handlers = []
hdlr = logging.handlers.RotatingFileHandler(LOG_FILE_PATH, maxBytes = ConfConst.MAX_LOG_FILE_SIZE , backupCount= ConfConst.MAX_LOG_FILE_BACKUP_COUNT)
formatter = logging.Formatter('[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s','%m-%d %H:%M:%S')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logging.StreamHandler(stream=None)
logger.setLevel(logging.INFO)
Use this it may help you
logger = logging.getLogger()
logger.disabled = True
... whatever you want ...
logger.disabled = False
Related
I need to disable Tornado from logging to STDOUT. I am using Python 3.8 and is running on Ubuntu 18.04. I want my log statements to be handled by a rotating file logger only. The issue is that logged statements are logged into the file and also to console:
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger("ex_logger")
nh = logging.NullHandler()
rfh = RotatingFileHandler(filename="./logs/process.log", mode='a', maxBytes=50000000, backupCount=25, encoding=None, delay=False)
rfh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
rfh.setFormatter(formatter)
logger.handlers = []
logger.propagete = False
logger.addHandler(rfh)
logging.getLogger("tornado.access").handlers = []
logging.getLogger("tornado.application").handlers = []
logging.getLogger("tornado.general").handlers = []
logging.getLogger("tornado.access").addHandler(nh)
logging.getLogger("tornado.application").addHandler(nh)
logging.getLogger("tornado.general").addHandler(nh)
logging.getLogger("tornado.access").propagate = False
logging.getLogger("tornado.application").propagate = False
logging.getLogger("tornado.general").propagate = False
....
def main():
######
# this message eppears in both the output log file and stdout
######
logger.info(" application init ... ")
asyncio.set_event_loop_policy(tornado.platform.asyncio.AnyThreadEventLoopPolicy())
tornado.options.parse_command_line()
app = Application()
app.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()
The problem is that from the moment you start up your IDE, logging.getLogger("tornado") may have a StreamHandler attached. This doesn't happen with every IDE but it does happen with Spyder. So that is the one you have to replace by a NullHandler:
import logging
nh = logging.NullHandler()
tornado_logger = logging.getLogger("tornado")
tornado_logger.handlers.clear()
# tornado_logger.handlers = [] # would work instead of .clear() but it's best practice to change the list and not replace it, just in case some other variable name somewhere else still refers to it.
tornado_logger.addHandler(nh)
You don't need to do anything with the children of the "tornado" logger, e.g. "tornado.access", et cetera.
You also need to define a logging policy for the root handler (logging.getLogger("")). Tornado looks at the root handler to decide whether logging has already been configured or needs a default setup.
Im in the process of setting up a logger for my programm
custom_logger = logging.getLogger(__name__)
custom_logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s;%(message)s;%(filename)s;%(lineno)d',"%Y-%m-%d %H:%M:%S")
file_handler = logging.FileHandler('beispiel.log')
file_handler.setFormatter(formatter)
custom_logger.addHandler(file_handler)
I want to logg this part custom_logger.info(z1serial.isOpen())
it adds a TRUE to the log file
2020-03-03 13:47:38;True;test.py;55
how can I insert a specific message like `device connected; True, so it apears in the log file ?
to insert a argument to the message it needs to be in format string like this
custom_logger.debug('device connected: %s',z1serial.isOpen())
nothing fancy
It seems that on a couple machines I'm getting double output like this:
INFO LED NOTIFICATION STARTED
INFO:output_logger:LED NOTIFICATION STARTED
This is the function I'm using:
def setup_logger(name, log_file, level=logging.INFO, ContentFormat='%(asctime)s %(levelname)s %(message)s', DateTimeFormat="%Y-%m-%d %H:%M:%S", CreateConsoleLogger=False):
"""Function setup as many loggers as you want"""
logger = logging.getLogger(name)
logger.setLevel(level)
if CreateConsoleLogger:
# create console handler
handler = logging.StreamHandler()
handler.setLevel(level)
formatter = logging.Formatter("%(levelname)s %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# create a file handler
handler = RotatingFileHandler(log_file, maxBytes=2000000, backupCount=5)
handler.setLevel(level)
formatter = logging.Formatter(ContentFormat, DateTimeFormat)
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
This is how I'm creating the logger:
output_logger = setup_logger('output_logger', 'log/autofy.log', level=logging.DEBUG, CreateConsoleLogger=True)
And this is how I call it:
output_logger.info("LED NOTIFICATION STARTED")
On a most of computers I just see the same message printed to the console that's saved to the file as expected ("INFO LED NOTIFICATION STARTED"), but on other computers it's doing this weird double output thing. My code is exactly the same from one computer to another, so any ideas what could be causing this on some computers and not others?
EDIT
I'm writing the script using notepad++ and running it in a terminal window on an Ubuntu 16.04 machine. I'm using python3.
Try adding this to your code:
logging._get_logger().propagate = False
I am using the logging module in Python 3.5, I feel like I have done this before, but I would like like to change the logging level with a constant supplied by my config file.
Currently I am using:
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
logger.setLevel(logging.INFO)
I would like to declare INFO, DEBUG etc in the config file and replace using the literal.
my_script_config:
LOG_LEVEL = 'DEBUG' #this value to be modified by user.
script:
import my_script_conf as msc
SET_LEVEL = 'logging.' + msc.LOG_LEVEL
BASIC_LEVEL = 'level=' + SET_LEVEL
logger = logging.getLogger(__name__)
logging.basicConfig(BASIC_LEVEL)
logger.setLevel(SET_LEVEL)
Python gets upset by this, any help on my terrible coding would be much appreciated. Any route to achieve the same result, I basically want it readable and easy to use, to have the logging modules level set in the external config file seems like the most sensible option. You pythonista's may have other ideas!
Thanks, Frank
I concatenated the string in a another variable then ran an exec on the variable.
my_script_config:
LOG_LEVEL = 'DEBUG' #this value to be modified by user.
script:
import my_script_conf as msc
SET_LEVEL = 'logger.setLevel(' + msc.LOG_LEVEL + ')
BASIC_LEVEL = 'logging.basicConfig(level=' + msc.LOG_LEVEL + ')'
logger = logging.getLogger(__name__)
exec(SET_LEVEL)
exec(BASIC_LEVEL)
First of all, sorry for my English.
i'm using Python3.x. I want to create a handler that storage the current logging
information into a table in SQLite3.
i've a handler that show by console de current logging and another that write the
same into a txt file.
I leave you my example:
import logging
class Logger(object):
'''test logger'''
def __init__(self):
'''constructor'''
self.logger = logging.getLogger('CIRE')
self.logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = '%(asctime)s. %(name)s|%(levelname)s| %(message)s'
dateFormat = '%m/%d/%Y %I:%M:%S %p'
logging.basicConfig(format=formatter, datefmt=dateFormat, filename='Logger.log')
formatter = logging.Formatter(formatter, dateFormat)
ch.setFormatter(formatter)
self.logger.addHandler(ch)
l = Logger()
l.logger.debug("test")
OUTPUT:
02/07/2017 12:54:13 PM. CIRE|DEBUG| test
thanks!!