logging set file logs code example
Example 1: python logging to file
import logging
"""
DEBUG
INFO
WARNING
ERROR
CRITICAL
"""
# asctime: time of the log was printed out
# levelname: name of the log
# datefmt: format the time of the log
# give DEBUG log
logging.basicConfig(format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
datefmt='%d-%m-%Y:%H:%M:%S',
level=logging.DEBUG,
filename='logs.txt')
logger = logging.getLogger('my_app')
logger.debug("This is a debug log")
logger.info("This is an info log")
logger.critical("This is critical")
logger.error("An error occurred")
Example 2: logging.debug vs logger
Logger logger = Logger.getLogger("com.foo");
logger.setLevel(Level.INFO);
Logger barlogger = Logger.getLogger("com.foo.Bar");
logger.warn("Low fuel level.");
logger.debug("Starting search for nearest gas station.");
barlogger.info("Located nearest gas station.");
barlogger.debug("Exiting gas station search");