Untitled Document
Logging Advanced - Loggers,Handlers and Formatters
1. Introduction Click Here
#********* Source Code From Website - Mangadaku - visit us at -http://mangadaku.com/ ***** 
# Introduction

import logging 

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s')

file_handler = logging.FileHandler('sample.log')
file_handler.setFormatter(formatter)

logger.addHandler(file_handler)

num1 = 10
num2 = 20

add_result = num1 + num2
mul_result = num1 * num2
logger.info(f"Sum of Two numbers {num1} * {num2} = mul_result")
logger.warning(f"Sum of Two numbers {num1} + {num2} = add_result")
logger.debug(f"This is Simple Debug Statement")

       
2. Program - Adding Logging level at File Handler Level Click Here
#********* Source Code From Website - Mangadaku - visit us at -http://mangadaku.com/ *****      
# Program - Adding Logging level at File Handler Level  

import logging 

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s')

file_handler = logging.FileHandler('sample.log')
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(formatter)

logger.addHandler(file_handler)

num1 = 10
num2 = 0

try:
	divide = num1 / num2
except ZeroDivisionError:
	logger.error('Tried to divide by Zero')
else:
	print(divide)

# Getting Trace Back error in log file 

try:
	divide = num1 / num2
except ZeroDivisionError:
	logger.exception('Tried to divide by Zero')
else:
	print(divide)

       
3. Program - Adding Stream Handler to prrint logging details on Console Click Here
#********* Source Code From Website - Mangadaku - visit us at -http://mangadaku.com/ *****      
# Program - Adding Stream Handler to print logging details on Console

import logging 

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s')

file_handler = logging.FileHandler('sample.log')
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(formatter)

stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)

logger.addHandler(file_handler)
logger.addHandler(stream_handler)

num1 = 10
num2 = 0

try:
	divide = num1 / num2
except ZeroDivisionError:
	logger.error('Tried to divide by Zero')
else:
	print(divide)

# Getting Trace Back error in log file 

try:
	divide = num1 / num2
except ZeroDivisionError:
	logger.exception('Tried to divide by Zero')
else:
	print(divide)

       
Untitled Document