“Protokollierung von Python” Code-Antworten

Python -Protokollierung zur Datei

import logging
import sys

logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s', 
                              '%m-%d-%Y %H:%M:%S')

stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.DEBUG)
stdout_handler.setFormatter(formatter)

file_handler = logging.FileHandler('logs.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)

logger.addHandler(file_handler)
logger.addHandler(stdout_handler)
Benja

Python -Protokollierung

# Example usage:
# For now, this is how I like to set up logging in Python:

import logging

# instantiate the root (parent) logger object (this is what gets called
# to create log messages)
root_logger = logging.getLogger()
# remove the default StreamHandler which isn't formatted well
root_logger.handlers = []
# set the lowest-severity log message to be included by the root_logger (this
# doesn't need to be set for each of the handlers that are added to the
# root_logger later because handlers inherit the logging level of their parent
# if their level is left unspecified. The root logger uses WARNING by default
root_logger.setLevel(logging.INFO)

# create the file_handler, which controls log messages which will be written
# to a log file (the default write mode is append)
file_handler = logging.FileHandler('/path/to/logfile.log')
# create the console_handler (which enables log messages to be sent to stdout)
console_handler = logging.StreamHandler()

# create the formatter, which controls the format of the log messages
# I like this format which includes the following information:
# 2022-04-01 14:03:03,446 - script_name.py - function_name - Line: 461 - INFO - Log message.
formatter = logging.Formatter('%(asctime)s - %(filename)s - %(funcName)s - Line: %(lineno)d - %(levelname)s - %(message)s')
# add the formatter to the handlers so they get formatted as desired
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)

# set the severity level of the console_hander to ERROR so that only messages
# of severity ERROR or higher are printed to the console
console_handler.setLevel(logging.ERROR)

# add the handlers to the root_logger
root_logger.addHandler(file_handler)
root_logger.addHandler(console_handler)


# given the above setup
# running this line will append the info message to the /path/to/logfile.log
# but won't print to the console
root_logger.INFO("A casual message.")
# running this line will append the error message to the /path/to/logfile.log
# and will print it to the console
root_logger.ERROR("A serious issue!")
Charles-Alexandre Roy

Python Logger Format

FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logger = logging.getLogger('tcpserver')
logger.warning('Protocol problem: %s', 'connection reset', extra=d)
Magnificent Mongoose

Python -Protokolldatei

import logging
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
logging.error('And non-ASCII stuff, too, like Øresund and Malmö')
Tense Termite

Protokollierung von Python

logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
Tender Toucan

Ausnahmeprotokollierung

import logging 
from functools import wraps

# Example from: https://www.geeksforgeeks.org/create-an-exception-logging-decorator-in-python/

def create_logger(): 
	
	# create a logger object 
	logger = logging.getLogger('exc_logger') 
	logger.setLevel(logging.INFO) 
	
	#c reate a file to store all the 
	# logged exceptions 
	logfile = logging.FileHandler('exc_logger.log') 
	
	fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
	formatter = logging.Formatter(fmt) 
	
	logfile.setFormatter(formatter) 
	logger.addHandler(logfile) 
	
	return logger 

logger = create_logger() 

# you will find a log file 
# created in a given path 
print(logger) 

def exception(logger):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except:
                issue = "exception in "+func.__name__+"\n"
                issue = issue+"=============\n"
                logger.exception(issue)
                raise
        return wrapper
    return decorator 


@exception(logger) 
def divideByZero(): 
	return 12/0

# Driver Code 
if __name__ == '__main__': 
	divideByZero() 
Ugly Unicorn

Ähnliche Antworten wie “Protokollierung von Python”

Fragen ähnlich wie “Protokollierung von Python”

Weitere verwandte Antworten zu “Protokollierung von Python” auf Python

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen