Be taught Python – Begin with logging module in Python
logging module of python has numerous of easy method that makes our work so easy. It easily let you set the structure of log lines with help logging module’s basicConfig() method.
So log can either be error message or Information or just a warning for making this thing easier logging module contain five logging levels that you can set as to specify your log message as one of:
- DEBUG ( 0 )
- INFO ( 1 )
- WARNING ( 2 )
- ERROR ( 3 )
- CRITICAL ( 4 )
1 | <br />import logging<br />logging.basicConfig( level = logging.DEBUG ) |
1 | <br />import logging<br />logging.basicConfig( filename = "test.log", level = logging.DEBUG ) |
1 | <br /><span style="color: blue">import</span><span style="color: black"> logging</span><br /><br /><span style="color: blue">class</span><span style="color: black"> Employee:</span><br /><span style="color: black"> </span><span style="color: blue">def</span><span style="color: black"> __init__(</span><span style="color: blue">self</span><span style="color: black">,first,last):</span><br /><span style="color: black"> </span><span style="color: blue">self</span><span style="color: black">.first = first</span><span style="color: black"> </span><span style="color: blue">self</span><span style="color: black">.last = last</span><br /><span style="color: black"> logging.info(</span><span style="color: #a31515">'Create Employee : {} — {}'</span><span style="color: black">.</span><span style="color: blue">format</span><span style="color: black">(</span><span style="color: blue">self</span><span style="color: black">.first,</span><span style="color: blue">self</span><span style="color: black">.last))<br /></span><br /><br /><span style="color: black">logging.basicConfig(filename=</span><span style="color: #a31515">'test.log'</span><span style="color: black">,level=logging.DEBUG)</span><br /><span style="color: black">emp_1 = Employee(</span><span style="color: #a31515">'John'</span><span style="color: black">,</span><span style="color: #a31515">'Doe'</span><span style="color: black">)</span><br /><span style="color: black">emp_2 = Employee(</span><span style="color: #a31515">'Jane'</span><span style="color: black">,</span><span style="color: #a31515">'Austin'</span><span style="color: black">)<br /><br /></span> |
**Code above will generate a log file of name test.log in your working directory.