IKH

Formatting Logs

  • By using format keyword argument, we can format messages.
  • To display only level name:
Python
logging.basicConfig(format='%(levelname)s')

Output

PowerShell
WARNING
ERROR
CRITICAL
  • To display levelname and message:
Python
logging.basicConfig(format='%(levelname)s:%(message)s')

Output

PowerShell
WARNING:warning Information
ERROR:error Information
CRITICAL:critical Information

How to add timestamp in the log messages

Python
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s')

Output

PowerShell
2018-06-15 11:50:08,325:WARNING:warning Information
2018-06-15 11:50:08,372:ERROR:error Information
2018-06-15 11:50:08,372:CRITICAL:critical Information

How to change date and time format

  • We have to use special keyword argument: datefmt
Python
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', datefmt='%d/%m/%Y 
%I:%M:%S %p')
datefmt='%d/%m/%Y %I:%M:%S %p' ===>case is important

Output

PowerShell
15/06/2018 12:04:31 PM:WARNING:warning Information
15/06/2018 12:04:31 PM:ERROR:error Information
15/06/2018 12:04:31 PM:CRITICAL:critical Information

Note

  • %I—>means 12 Hours time scale
  • %H—>means 24 Hours time scale

Example

Python
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', datefmt='%d/%m/%Y 
%H:%M:%S')

Output

PowerShell
15/06/2018 12:06:28:WARNING:warning Information
15/06/2018 12:06:28:ERROR:error Information
15/06/2018 12:06:28:CRITICAL:critical Information
https://docs.python.org/3/library/logging.html#logrecord-attributes
https://docs.python.org/3/library/time.html#time.strftime

How to write Python program exceptions to the log file

  • By using the following function we can write exception information to the log file.
  • logging.exception(msg)

Q. Python Program to write exception information to the log file

Python
import logging 
logging.basicConfig(filename='mylog.txt',level=logging.INFO,format='%(asctime)s:%(leveln
ame)s:%(message)s',datefmt='%d/%m/%Y %I:%M:%S %p') 
logging.info('A new Request Came') 
try: 
x=int(input('Enter First Number:')) 
y=int(input('Enter Second Number:')) 
print('The Result:',x/y) 
 
except ZeroDivisionError as msg: 
print('cannot divide with zero') 
logging.exception(msg) 
 
except ValueError as msg: 
print('Please provide int values only') 
logging.exception(msg) 
 
logging.info('Request Processing Completed') 

Output

PowerShell
D:\durgaclasses>py test.py
Enter First Number:10
Enter Second Number:2
The Result: 5.0
D:\durgaclasses>py test.py
Enter First Number:20
Enter Second Number:2
The Result: 10.0
D:\durgaclasses>py test.py
Enter First Number:10
Enter Second Number:0
cannot divide with zero
D:\durgaclasses>py test.py
Enter First Number:ten
Please provide int values only

mylog.txt

  • 15/06/2018 12:30:51 PM:INFO:A new Request Came 15/06/2018 12:30:53 PM:INFO:Request Processing Completed 15/06/2018 12:30:55 PM:INFO:A new Request Came 15/06/2018 12:31:00 PM:INFO:Request Processing Completed 15/06/2018 12:31:02 PM:INFO:A new Request Came 15/06/2018 12:31:05 PM:ERROR:division by zero Traceback (most recent call last): File “test.py”, line 7, in print(‘The Result:’,x/y) ZeroDivisionError: division by zero 15/06/2018 12:31:05 PM:INFO:Request Processing Completed 15/06/2018 12:31:06 PM:INFO:A new Request Came 15/06/2018 12:31:10 PM:ERROR:invalid literal for int() with base 10: ‘ten’ Traceback (most recent call last): File “test.py”, line 5, in x=int(input(‘Enter First Number:’)) ValueError: invalid literal for int() with base 10: ‘ten’ 15/06/2018 12:31:10 PM:INFO:Request Processing Completed

Problems with root logger

  • If we are not defining our own logger,then bydefault root logger will be considered.
  • Once we perform basic configuration to root logger then the configurations are fixed and we cannot change.

Demo Application

student.py

  • import logging
  • logging.basicConfig(filename=’student.log’,level=logging.INFO)
  • logging.info(‘info message from student module’)

test.py

  • import logging
  • import student
  • logging.basicConfig(filename=’test.log’,level=logging.DEBUG)
  • logging.debug(‘debug message from test module’)

student.log

  • INFO:root:info message from student module
  • In the above application the configurations performed in test module won’t be reflected,b’z root
  • logger is already configured in student module.

Need of Our own customized logger

The problems with root logger are:

  • Once we set basic configuration then that configuration is final and we cannot change
  • It will always work for only one handler at a time, either console or file, but not both
    simultaneously
  • It is not possible to configure logger with different configurations at different levels
  • We cannot specify multiple log files for multiple modules/classes/methods.
    To overcome these problems we should go for our own customized loggers

Name
Email
Phone

Report an error