{"id":2020,"date":"2019-03-03T11:58:29","date_gmt":"2019-03-03T11:58:29","guid":{"rendered":"https:\/\/machinelearningplus.com\/?p=2020"},"modified":"2022-05-16T09:52:37","modified_gmt":"2022-05-16T09:52:37","slug":"python-logging-guide","status":"publish","type":"post","link":"https:\/\/machinelearningplus.com\/python\/python-logging-guide\/","title":{"rendered":"Python Logging &#8211; Simplest Guide with Full Code and Examples"},"content":{"rendered":"<p><em>The logging module lets you track events when your code runs so that when the code crashes you can check the logs and identify what caused it. Log messages have a built-in hierarchy &#8211; starting from debugging, informational, warnings, error and critical messages. You can include traceback information as well. It is designed for small to large python projects with multiple modules and is highly recommended for any modular python programming. This post is a simple and clear explanation of how to use the logging module.<\/em><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2019\/03\/logging_python.jpg\">Logging in Python &#8211; Simplified Guide with Full Code and Examples. Photo by Andrea Reiman.<\/img><\/p>\n<h2 id=\"content\">Content<\/h2>\n<ol>\n<li>Why logging?<\/li>\n<li>A Basic logging Example<\/li>\n<li>The 5 levels of logging<\/li>\n<li>How to log to a file instead of the console<\/li>\n<li>How to change the logging format<\/li>\n<li>Why working with the root logger for all modules isn&#8217;t the best idea<\/li>\n<li>How to create a new logger?<\/li>\n<li>What is and How to setup a File Handler and Formatter? <\/li>\n<li>How to include traceback information in logged messages<\/li>\n<li>Exercises<\/li>\n<li>Conclusion<\/li>\n<\/ol>\n<h2 id=\"1whylogging\">1. Why logging?<\/h2>\n<p>When you run a python script, you want to know what part of the script is getting executed and inspect what values the variables hold. <\/p>\n<p>Usually, you may just &#8216;<code>print()<\/code>&#8216; out meaningful messages so you can see them in the console. And this probably all you need when you are developing small programs. <\/p>\n<p>The problem is, when you use this approach on larger projects with multiple modules you want a more flexible approach. <\/p>\n<p>Why?<\/p>\n<p>Because, the code could go through different stages as in <em>development<\/em>, <em>debugging<\/em>, <em>review<\/em>, <em>testing<\/em> or in <em>production<\/em>. <\/p>\n<p>The type of messages you want to print out during development can be very different from want you to see once it goes into production. Depending on the purpose, you want the code to print out different types of messages. <\/p>\n<p>This can get cumbersome with <code>if else<\/code> and <code>print<\/code> statements. Besides, you want a certain hierarchy when it comes to printing messages. <\/p>\n<p>What I mean by that is, during a certain &#8216;testing&#8217; run, you want to see only warnings and error messages. Whereas during &#8216;debugging&#8217;, you not only want to see the warnings and error messages but also the debugging-related messages. Imagine doing this with &#8216;<code>if else<\/code>&#8216; statements on a multi-module project.<\/p>\n<p>If you want to print out which module and at what time the codes were run, your code could easily get messier. <\/p>\n<p>There is good news. All these issues are nicely addressed by the <code>logging<\/code> module. <\/p>\n<p>Using logging, you can:<\/p>\n<ol>\n<li>Control message level to log only required ones<\/li>\n<li>Control where to show or save the logs<\/li>\n<li>Control how to format the logs with built-in message templates<\/li>\n<li>Know which module the messages is coming from<\/li>\n<\/ol>\n<p>You might say &#8216;<em>I see that <code>logging<\/code> can be useful but it seems too technical and seems to be a bit difficult to grasp<\/em>&#8216;. Well, yes, <code>logging<\/code> requires a bit of learning curve but that&#8217;s what this post is here for: make logging easy to learn.<\/p>\n<p>Without further delay, let&#8217;s get right into it.<\/p>\n<h2 id=\"2abasicloggingexample\">2. A Basic logging Example<\/h2>\n<p>Python provides an in-built <code>logging<\/code> module which is part of the python standard library. So you don&#8217;t need to install anything.<\/p>\n<p>To use logging, all you need to do is setup the basic configuration using <code>logging.basicConfig()<\/code>.  Actually, this is also optional. We will see about that soon. <\/p>\n<p>Then, instead of <code>print()<\/code>, you call <code>logging.{level}(message)<\/code> to show the message in console.<\/p>\n<pre><code class=\"python language-python\">import logging\nlogging.basicConfig(level=logging.INFO)\n\ndef hypotenuse(a, b):\n    \"\"\"Compute the hypotenuse\"\"\"\n    return (a**2 + b**2)**0.5\n\nlogging.info(\"Hypotenuse of {a}, {b} is {c}\".format(a=3, b=4, c=hypotenuse(a,b)))\n#&gt; INFO:root:Hypotenuse of 3, 4 is 5.0\n<\/code><\/pre>\n<p>The printed log message has the following default format: <strong>{LEVEL}:{LOGGER}:{MESSAGE}<\/strong>.<\/p>\n<p>In the above case, the level is <code>info<\/code>, because, I called <code>logging.info()<\/code>. <\/p>\n<p>The logger is called <code>root<\/code>, because that is the default logger and I did not create a new one, yet.<\/p>\n<p>But what is a logger anyway?<\/p>\n<p>A logger is like an entity you can create and configure to log different type and format of messages. <\/p>\n<p>You can configure a logger that prints to the console and another logger that sends the logs to a file, has a different logging level and is specific to a given module. More explanations and examples coming up on this.<\/p>\n<p>Finally, the message is the string I passed to <code>logging.info()<\/code>.<\/p>\n<p>Now, what would have happened had you not setup <code>logging.basicConfig(level=logging.INFO)<\/code>? <\/p>\n<p>Answer: The log would not have been printed. <\/p>\n<p>Why?<\/p>\n<p>To know that let&#8217;s understand the levels of logging.<\/p>\n<h2 id=\"3the5levelsoflogging\">3. The 5 levels of logging<\/h2>\n<p><code>logging<\/code> has 5 different hierarchical levels of logs that a given logger may be configured to. <\/p>\n<p>Let&#8217;s see what the python docs has to say about each level:<\/p>\n<ol>\n<li>DEBUG:    Detailed information, for diagnosing problems. Value=10.<\/li>\n<li>INFO:     Confirm things are working as expected. Value=20.<\/li>\n<li>WARNING:     Something unexpected happened, or indicative of some problem. But the software is still working as expected. Value=30.<\/li>\n<li>ERROR:     More serious problem, the software is not able to perform some function. Value=40<\/li>\n<li>CRITICAL:     A serious error, the program itself may be unable to continue running. Value=50<\/li>\n<\/ol>\n<p>Now, coming back to the previous question of what would have happened had you not setup <code>logging.basicConfig(level=logging.INFO)<\/code> in the previous example. <\/p>\n<p>The answer is: the log would not have been printed because, the default logger is the &#8216;root&#8217; and its default basicConfig level is &#8216;WARNING&#8217;. That means, only messages from <code>logging.warning()<\/code> and higher levels will get logged.<\/p>\n<p>So, the message of <code>logging.info()<\/code> would not be printed. And that is why the basic config was set as <code>INFO<\/code> initially (in <code>logging.basicConfig(level=logging.INFO)<\/code>).<\/p>\n<p>Had I set the level as <code>logging.ERROR<\/code> instead, only message from <code>logging.error<\/code> and <code>logging.critical<\/code> will be logged. Clear?<\/p>\n<pre><code class=\"python language-python\">import logging\nlogging.basicConfig(level=logging.WARNING)\n\ndef hypotenuse(a, b):\n    \"\"\"Compute the hypotenuse\"\"\"\n    return (a**2 + b**2)**0.5\n\nkwargs = {'a':3, 'b':4, 'c':hypotenuse(3, 4)}\n\nlogging.debug(\"a = {a}, b = {b}\".format(**kwargs))\nlogging.info(\"Hypotenuse of {a}, {b} is {c}\".format(**kwargs))\nlogging.warning(\"a={a} and b={b} are equal\".format(**kwargs))\nlogging.error(\"a={a} and b={b} cannot be negative\".format(**kwargs))\nlogging.critical(\"Hypotenuse of {a}, {b} is {c}\".format(**kwargs))\n\n#&gt; WARNING:root:a=3 and b=3 are equal\n#&gt; ERROR:root:a=-1 and b=4 cannot be negative\n#&gt; CRITICAL:root:Hypotenuse of a, b is 5.0\n<\/code><\/pre>\n<h2 id=\"4howtologtoafileinsteadoftheconsole\">4. How to log to a file instead of the console<\/h2>\n<p>To send the log messages to a file from the root logger, you need to set the file argument in <code>logging.basicConfig()<\/code><\/p>\n<pre><code class=\"python language-python\">import logging\nlogging.basicConfig(level=logging.INFO, file='sample.log')\n<\/code><\/pre>\n<p>Now all subsequent log messages will go straight to the file &#8216;sample.log&#8217; in your current working directory. If you want to send it to a file in a different directory, give the full file path.<\/p>\n<h2 id=\"5howtochangetheloggingformat\">5. How to change the logging format<\/h2>\n<p>The logging module provides shorthands to add various details to the logged messages. The below image from Python docs shows that list.<\/p>\n<figure id=\"attachment_2028\" aria-describedby=\"caption-attachment-2028\" style=\"width: 797px\" class=\"wp-caption aligncenter\"><a href=\"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2019\/03\/logging_formats-min.png\"><img fetchpriority=\"high\" decoding=\"async\" src=\"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2019\/03\/logging_formats-min-797x1024.png\" alt=\"Logging Formats\" width=\"797\" height=\"1024\" class=\"size-large wp-image-2028\" srcset=\"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2019\/03\/logging_formats-min-797x1024.png 797w, https:\/\/machinelearningplus.com\/wp-content\/uploads\/2019\/03\/logging_formats-min-234x300.png 234w, https:\/\/machinelearningplus.com\/wp-content\/uploads\/2019\/03\/logging_formats-min-768x986.png 768w, https:\/\/machinelearningplus.com\/wp-content\/uploads\/2019\/03\/logging_formats-min-640x822.png 640w, https:\/\/machinelearningplus.com\/wp-content\/uploads\/2019\/03\/logging_formats-min-100x128.png 100w, https:\/\/machinelearningplus.com\/wp-content\/uploads\/2019\/03\/logging_formats-min-865x1111.png 865w, https:\/\/machinelearningplus.com\/wp-content\/uploads\/2019\/03\/logging_formats-min.png 1076w\" sizes=\"(max-width: 797px) 100vw, 797px\" \/><\/a><figcaption id=\"caption-attachment-2028\" class=\"wp-caption-text\">Logging Formats<\/figcaption><\/figure>\n<p>Let&#8217;s change the log message format to show the TIME, LEVEL and the MESSAGE. To do that just add the format to <code>logging.basiconfig()<\/code>&#8216;s format argument.<\/p>\n<pre><code class=\"python language-python\">import logging\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s :: %(levelname)s :: %(message)s')\nlogging.info(\"Just like that!\")\n#&gt; 2019-02-17 11:40:38,254 :: INFO :: Just like that!\n<\/code><\/pre>\n<h2 id=\"6whyworkingwiththerootloggerforallmodulesisntthebestidea\">6. Why working with the root logger for all modules isn&#8217;t the best idea<\/h2>\n<p>Because they all will share the same &#8216;root&#8217; logger.<\/p>\n<p>But why is that bad?<\/p>\n<p>Let&#8217;s look at the below code:<\/p>\n<pre><code class=\"python language-python\"># 1. code inside myprojectmodule.py\nimport logging\nlogging.basicConfig(file='module.log')\n\n#-----------------------------\n\n# 2. code inside main.py (imports the code from myprojectmodule.py)\nimport logging\nimport myprojectmodule  # This runs the code in myprojectmodule.py\n\nlogging.basicConfig(file='main.log')  # No effect, because!\n<\/code><\/pre>\n<p>Imagine you have one or more modules in your project. And these modules use the basic root module. Then, when importing the module (&#8216;<code>myprojectmodule.py<\/code>&#8216;), all of that module&#8217;s code will run and logger gets configured.<\/p>\n<p>Once configured, the root logger in the main file (that imported the &#8216;<code>myprojectmodule<\/code>&#8216; module) will no longer be able to change the root logger settings. Because, the <code>logging.basicConfig()<\/code> once set cannot be changed. <\/p>\n<p>That means, if you want to log the messages from <code>myprojectmodule<\/code> to one file and the logs from the main module in another file, root logger can&#8217;t that.<\/p>\n<p>To do that you need to create a new logger.<\/p>\n<h2 id=\"7howtocreateanewlogger\">7. How to create a new logger?<\/h2>\n<p>You can create a new logger using the &#8216;<code>logger.getLogger(name)<\/code>&#8216; method. If a logger with the same name exists, then that logger will be used.<\/p>\n<p>While you can give pretty much any name to the logger, the convention is to use the <code>__name__<\/code> variable like this:<\/p>\n<pre><code class=\"python language-python\">logger = logging.getLogger(__name__)\nlogger.info('my logging message')\n<\/code><\/pre>\n<p>But, why use <code>__name__<\/code> as the name of the logger, instead of hardcoding a name?<\/p>\n<p>Because the <code>__name__<\/code> variable will hold the name of the module (python file) that called the code. So, when used inside a module, it will create a logger bearing the value provided by the module&#8217;s <code>__name__<\/code> attribute. <\/p>\n<p>By doing this, if you end up changing module name (file name) in future, you don&#8217;t have to modify the internal code.<\/p>\n<p>Now, once you&#8217;ve created a new logger, you should remember to log all your messages using the new <code>logger.info()<\/code> instead of the root&#8217;s <code>logging.info()<\/code> method. <\/p>\n<p>Another aspect to note is, all the loggers have a built-in hierarchy to it. <\/p>\n<p>What do I mean by that?<\/p>\n<p>For example, if you have configured the root logger to log messages to a particular file. You also have a custom logger for which you have not configured the file handler to send messages to console or another log file. <\/p>\n<p>In this case, the custom logger will fallback and write to the file set by the root logger itself. Until and unless you configure the log file of your custom logger.<\/p>\n<p>So what is a file handler and how to set one up?<\/p>\n<h2 id=\"8whatisandhowtosetupafilehandlerandformatter\">8. What is and How to set up a File Handler and Formatter?<\/h2>\n<p>The <code>FileHandler()<\/code> and <code>Formatter()<\/code> classes are used to setup the output file and the format of messages for loggers other than the root logger.<\/p>\n<p>Do you remember how we setup the filename and the format of the message in the root logger (inside <code>logging.basicConfig()<\/code>) earlier? <\/p>\n<p>We just specified the <code>filename<\/code> and <code>format<\/code> parameters in <code>logging.basicConfig()<\/code> and all subsequent logs went to that file.<\/p>\n<p>However, when you create a separate logger, you need to set them up individually using the <code>logging.FileHandler()<\/code> and <code>logging.Formatter()<\/code> objects.<\/p>\n<p>A <code>FileHandler<\/code> is used to make your custom logger to log in to a different file. Likewise, a <code>Formatter<\/code> is used to change the format of your logged messages. <\/p>\n<pre><code class=\"python language-python\">import logging\n\n# Gets or creates a logger\nlogger = logging.getLogger(__name__)  \n\n# set log level\nlogger.setLevel(logging.WARNING)\n\n# define file handler and set formatter\nfile_handler = logging.FileHandler('logfile.log')\nformatter    = logging.Formatter('%(asctime)s : %(levelname)s : %(name)s : %(message)s')\nfile_handler.setFormatter(formatter)\n\n# add file handler to logger\nlogger.addHandler(file_handler)\n\n# Logs\nlogger.debug('A debug message')\nlogger.info('An info message')\nlogger.warning('Something is not right.')\nlogger.error('A Major error has happened.')\nlogger.critical('Fatal error. Cannot continue')\n<\/code><\/pre>\n<p>Notice how we set the formatter on the &#8216;<code>file_handler<\/code>&#8216; and not the &#8216;<code>logger<\/code>&#8216; directly.<\/p>\n<p>Assuming the above code is run from the main program, if you look inside the working directory, a file named <code>logfile.log<\/code> will be created if it doesn&#8217;t exist and would contain the below messages.<\/p>\n<pre><code class=\"python language-python\">#&gt; 2019-02-17 12:40:14,797 : WARNING : __main__ : Something is not right.\n#&gt; 2019-02-17 12:40:14,798 : ERROR : __main__ : A Major error has happened.\n#&gt; 2019-02-17 12:40:14,798 : CRITICAL : __main__ : Fatal error. Cannot continue\n<\/code><\/pre>\n<p>Note again, the <code>Formatter<\/code> is set on the <code>FileHandler<\/code> object and not directly on the logger. Something you may want to get used to.<\/p>\n<h2 id=\"9howtoincludetracebackinformationinloggedmessages\">9. How to include traceback information in logged messages<\/h2>\n<p>Besides &#8216;<code>debug<\/code>&#8216;, &#8216;<code>info<\/code>&#8216;, &#8216;<code>warning<\/code>&#8216;, &#8216;<code>error<\/code>&#8216;, and &#8216;<code>critical<\/code>&#8216; messages, you can log exceptions that will include any associated traceback information.<\/p>\n<p>With <code>logger.exception<\/code>, you can log traceback information should the code encounter any error. <code>logger.exception<\/code> will log the message provided in its arguments as well as the error message traceback info.<\/p>\n<p>Below is a nice example.<\/p>\n<pre><code class=\"python language-python\">import logging\n\n# Create or get the logger\nlogger = logging.getLogger(__name__)  \n\n# set log level\nlogger.setLevel(logging.INFO)\n\ndef divide(x, y):\n    try:\n        out = x \/ y\n    except ZeroDivisionError:\n        logger.exception(\"Division by zero problem\")\n    else:\n        return out\n\n# Logs\nlogger.error(\"Divide {x} \/ {y} = {c}\".format(x=10, y=0, c=divide(10,0)))\n\n#&gt; ERROR:__main__:Division by zero problem\n#&gt; Traceback (most recent call last):\n#&gt;   File \"&lt;ipython-input-16-a010a44fdc0a&gt;\", line 12, in divide\n#&gt;     out = x \/ y\n#&gt; ZeroDivisionError: division by zero\n#&gt; ERROR:__main__:None\n<\/code><\/pre>\n<h2 id=\"10exercises\">10. Exercises<\/h2>\n<ol>\n<li>Create a new project directory and a new python file named &#8216;<code>example.py<\/code>&#8216;. Import the logging module and configure the root logger to the level of &#8216;debug&#8217; messages. Log an &#8216;info&#8217; message with the text: &#8220;This is root logger&#8217;s logging message!&#8221;.<\/p>\n<\/li>\n<li>\n<p>Configure the root logger to format the message &#8220;This is root logger&#8217;s logging message!&#8221; as the following:<\/p>\n<\/li>\n<\/ol>\n<pre><code class=\"language-python\">#&gt; 2019-03-03 17:18:32,703 :: INFO :: Module &lt;stdin&gt; :: Line No 1 :: This is root logger's logging message!\n<\/code><\/pre>\n<details class=\"blogv4-expand\"><summary class=\"blogv4-expand__toggle\">Show Solution<\/summary><div class=\"blogv4-expand__body\"><\/p>\n<pre>import logging\r\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s :: %(levelname)s :: Module %(module)s :: Line No %(lineno)s :: %(message)s')\r\nlogging.info(\"This is root logger's logging mesage!\")<\/pre>\n<p><\/div><\/details>\n<ol>\n<li>Create another python file in the same directory called &#8216;<code>mymod.py<\/code>&#8216; and create a new logger bearing the module&#8217;s name. Configure it to the level of &#8216;error&#8217; messages and make it send the log outputs to a file called &#8220;mymod_{current_date}.log&#8221;.<\/p>\n<\/li>\n<li>\n<p>From &#8216;mymod&#8217; logger created above, log the following &#8216;critical&#8217; message to the said log file: &#8220;This is a critical message!. Don&#8217;t ignore it&#8221;.<\/p>\n<\/li>\n<\/ol>\n<h2 id=\"11conclusion\">11. Conclusion<\/h2>\n<p>Many congratulations if you were able to solve the exercises! <\/p>\n<p>That was quite useful and straightforward wasn&#8217;t it? <\/p>\n<p>logging is a great tool but is not popular is Data science workflows as it should be. I hope the logging concepts are clear and the next time you work on a python based project, my kind request for you is to remember to give the <code>logging<\/code> module a shot.<\/p>\n<p>Happy logging!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The logging module lets you track events when your code runs so that when the code crashes you can check the logs and identify what caused it. Log messages have a built-in hierarchy &#8211; starting from debugging, informational, warnings, error and critical messages. You can include traceback information as well. It is designed for small [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":2044,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"site-sidebar-layout":"default","site-content-layout":"default","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"default","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[21],"tags":[78,22],"class_list":["post-2020","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-logging","tag-python"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Logging - Simplest Guide with Full Code and Examples | ML+<\/title>\n<meta name=\"description\" content=\"The logging module lets you track events by logging messages when your code runs so that when the code crashes you can check the logs and identify what caused it. Log messages have a built-in hierarchy from debugging, informational, warnings, error and critical messages. You can include traceback information as well. It is designed for small to large python projects with multiple modules and is highly recommended for any modular python programming. This post is a simple and clear explanation of how to use the logging module.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/localhost:8080\/python\/python-logging-guide\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Logging - Simplest Guide with Full Code and Examples | ML+\" \/>\n<meta property=\"og:description\" content=\"The logging module lets you track events by logging messages when your code runs so that when the code crashes you can check the logs and identify what caused it. Log messages have a built-in hierarchy from debugging, informational, warnings, error and critical messages. You can include traceback information as well. It is designed for small to large python projects with multiple modules and is highly recommended for any modular python programming. This post is a simple and clear explanation of how to use the logging module.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/localhost:8080\/python\/python-logging-guide\/\" \/>\n<meta property=\"og:site_name\" content=\"machinelearningplus\" \/>\n<meta property=\"article:author\" content=\"https:\/\/www.facebook.com\/rtipaday\/\" \/>\n<meta property=\"article:published_time\" content=\"2019-03-03T11:58:29+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-05-16T09:52:37+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/localhost:8080\/wp-content\/uploads\/2019\/03\/logging_feature.png\" \/>\n\t<meta property=\"og:image:width\" content=\"560\" \/>\n\t<meta property=\"og:image:height\" content=\"315\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Selva Prabhakaran\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/R_Programming\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Selva Prabhakaran\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"TechArticle\",\"@id\":\"https:\\\/\\\/localhost:8080\\\/python\\\/python-logging-guide\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/python\\\/python-logging-guide\\\/\"},\"author\":{\"name\":\"Selva Prabhakaran\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#\\\/schema\\\/person\\\/510885c0515804366fa644c38258391e\"},\"headline\":\"Python Logging &#8211; Simplest Guide with Full Code and Examples\",\"datePublished\":\"2019-03-03T11:58:29+00:00\",\"dateModified\":\"2022-05-16T09:52:37+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/python\\\/python-logging-guide\\\/\"},\"wordCount\":1847,\"commentCount\":4,\"publisher\":{\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/python\\\/python-logging-guide\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2019\\\/03\\\/logging_feature.png\",\"keywords\":[\"logging\",\"Python\"],\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/localhost:8080\\\/python\\\/python-logging-guide\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/localhost:8080\\\/python\\\/python-logging-guide\\\/\",\"url\":\"https:\\\/\\\/localhost:8080\\\/python\\\/python-logging-guide\\\/\",\"name\":\"Python Logging - Simplest Guide with Full Code and Examples | ML+\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/python\\\/python-logging-guide\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/python\\\/python-logging-guide\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2019\\\/03\\\/logging_feature.png\",\"datePublished\":\"2019-03-03T11:58:29+00:00\",\"dateModified\":\"2022-05-16T09:52:37+00:00\",\"description\":\"The logging module lets you track events by logging messages when your code runs so that when the code crashes you can check the logs and identify what caused it. Log messages have a built-in hierarchy from debugging, informational, warnings, error and critical messages. You can include traceback information as well. It is designed for small to large python projects with multiple modules and is highly recommended for any modular python programming. This post is a simple and clear explanation of how to use the logging module.\",\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/localhost:8080\\\/python\\\/python-logging-guide\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/localhost:8080\\\/python\\\/python-logging-guide\\\/#primaryimage\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2019\\\/03\\\/logging_feature.png\",\"contentUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2019\\\/03\\\/logging_feature.png\",\"width\":560,\"height\":315,\"caption\":\"Logging in Python\"},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#website\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/\",\"name\":\"machinelearningplus\",\"description\":\"Learn Data Science (AI \\\/ ML) Online\",\"publisher\":{\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/machinelearningplus.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#organization\",\"name\":\"machinelearningplus\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2022\\\/05\\\/MachineLearningplus-logo.svg\",\"contentUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2022\\\/05\\\/MachineLearningplus-logo.svg\",\"width\":348,\"height\":36,\"caption\":\"machinelearningplus\"},\"image\":{\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#\\\/schema\\\/person\\\/510885c0515804366fa644c38258391e\",\"name\":\"Selva Prabhakaran\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/litespeed\\\/avatar\\\/a994280177da541405c016f593e86ea7.jpg?ver=1776363207\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/litespeed\\\/avatar\\\/a994280177da541405c016f593e86ea7.jpg?ver=1776363207\",\"contentUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/litespeed\\\/avatar\\\/a994280177da541405c016f593e86ea7.jpg?ver=1776363207\",\"caption\":\"Selva Prabhakaran\"},\"description\":\"Selva is an experienced Data Scientist and leader, specializing in executing AI projects for large companies. Selva started machinelearningplus to make Data Science \\\/ ML \\\/ AI accessible to everyone. The website enjoys 4 Million+ readership. His courses, lessons, and videos are loved by hundreds of thousands of students and practitioners.\",\"sameAs\":[\"https:\\\/\\\/localhost:8080\\\/\",\"https:\\\/\\\/www.facebook.com\\\/rtipaday\\\/\",\"https:\\\/\\\/x.com\\\/https:\\\/\\\/twitter.com\\\/R_Programming\"],\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/author\\\/selva86\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Logging - Simplest Guide with Full Code and Examples | ML+","description":"The logging module lets you track events by logging messages when your code runs so that when the code crashes you can check the logs and identify what caused it. Log messages have a built-in hierarchy from debugging, informational, warnings, error and critical messages. You can include traceback information as well. It is designed for small to large python projects with multiple modules and is highly recommended for any modular python programming. This post is a simple and clear explanation of how to use the logging module.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/localhost:8080\/python\/python-logging-guide\/","og_locale":"en_US","og_type":"article","og_title":"Python Logging - Simplest Guide with Full Code and Examples | ML+","og_description":"The logging module lets you track events by logging messages when your code runs so that when the code crashes you can check the logs and identify what caused it. Log messages have a built-in hierarchy from debugging, informational, warnings, error and critical messages. You can include traceback information as well. It is designed for small to large python projects with multiple modules and is highly recommended for any modular python programming. This post is a simple and clear explanation of how to use the logging module.","og_url":"https:\/\/localhost:8080\/python\/python-logging-guide\/","og_site_name":"machinelearningplus","article_author":"https:\/\/www.facebook.com\/rtipaday\/","article_published_time":"2019-03-03T11:58:29+00:00","article_modified_time":"2022-05-16T09:52:37+00:00","og_image":[{"width":560,"height":315,"url":"https:\/\/localhost:8080\/wp-content\/uploads\/2019\/03\/logging_feature.png","type":"image\/png"}],"author":"Selva Prabhakaran","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/R_Programming","twitter_misc":{"Written by":"Selva Prabhakaran","Est. reading time":"10 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"TechArticle","@id":"https:\/\/localhost:8080\/python\/python-logging-guide\/#article","isPartOf":{"@id":"https:\/\/localhost:8080\/python\/python-logging-guide\/"},"author":{"name":"Selva Prabhakaran","@id":"https:\/\/machinelearningplus.com\/#\/schema\/person\/510885c0515804366fa644c38258391e"},"headline":"Python Logging &#8211; Simplest Guide with Full Code and Examples","datePublished":"2019-03-03T11:58:29+00:00","dateModified":"2022-05-16T09:52:37+00:00","mainEntityOfPage":{"@id":"https:\/\/localhost:8080\/python\/python-logging-guide\/"},"wordCount":1847,"commentCount":4,"publisher":{"@id":"https:\/\/machinelearningplus.com\/#organization"},"image":{"@id":"https:\/\/localhost:8080\/python\/python-logging-guide\/#primaryimage"},"thumbnailUrl":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2019\/03\/logging_feature.png","keywords":["logging","Python"],"articleSection":["Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/localhost:8080\/python\/python-logging-guide\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/localhost:8080\/python\/python-logging-guide\/","url":"https:\/\/localhost:8080\/python\/python-logging-guide\/","name":"Python Logging - Simplest Guide with Full Code and Examples | ML+","isPartOf":{"@id":"https:\/\/machinelearningplus.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/localhost:8080\/python\/python-logging-guide\/#primaryimage"},"image":{"@id":"https:\/\/localhost:8080\/python\/python-logging-guide\/#primaryimage"},"thumbnailUrl":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2019\/03\/logging_feature.png","datePublished":"2019-03-03T11:58:29+00:00","dateModified":"2022-05-16T09:52:37+00:00","description":"The logging module lets you track events by logging messages when your code runs so that when the code crashes you can check the logs and identify what caused it. Log messages have a built-in hierarchy from debugging, informational, warnings, error and critical messages. You can include traceback information as well. It is designed for small to large python projects with multiple modules and is highly recommended for any modular python programming. This post is a simple and clear explanation of how to use the logging module.","inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/localhost:8080\/python\/python-logging-guide\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/localhost:8080\/python\/python-logging-guide\/#primaryimage","url":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2019\/03\/logging_feature.png","contentUrl":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2019\/03\/logging_feature.png","width":560,"height":315,"caption":"Logging in Python"},{"@type":"WebSite","@id":"https:\/\/machinelearningplus.com\/#website","url":"https:\/\/machinelearningplus.com\/","name":"machinelearningplus","description":"Learn Data Science (AI \/ ML) Online","publisher":{"@id":"https:\/\/machinelearningplus.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/machinelearningplus.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/machinelearningplus.com\/#organization","name":"machinelearningplus","url":"https:\/\/machinelearningplus.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/machinelearningplus.com\/#\/schema\/logo\/image\/","url":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/05\/MachineLearningplus-logo.svg","contentUrl":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/05\/MachineLearningplus-logo.svg","width":348,"height":36,"caption":"machinelearningplus"},"image":{"@id":"https:\/\/machinelearningplus.com\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/machinelearningplus.com\/#\/schema\/person\/510885c0515804366fa644c38258391e","name":"Selva Prabhakaran","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/machinelearningplus.com\/wp-content\/litespeed\/avatar\/a994280177da541405c016f593e86ea7.jpg?ver=1776363207","url":"https:\/\/machinelearningplus.com\/wp-content\/litespeed\/avatar\/a994280177da541405c016f593e86ea7.jpg?ver=1776363207","contentUrl":"https:\/\/machinelearningplus.com\/wp-content\/litespeed\/avatar\/a994280177da541405c016f593e86ea7.jpg?ver=1776363207","caption":"Selva Prabhakaran"},"description":"Selva is an experienced Data Scientist and leader, specializing in executing AI projects for large companies. Selva started machinelearningplus to make Data Science \/ ML \/ AI accessible to everyone. The website enjoys 4 Million+ readership. His courses, lessons, and videos are loved by hundreds of thousands of students and practitioners.","sameAs":["https:\/\/localhost:8080\/","https:\/\/www.facebook.com\/rtipaday\/","https:\/\/x.com\/https:\/\/twitter.com\/R_Programming"],"url":"https:\/\/machinelearningplus.com\/author\/selva86\/"}]}},"_links":{"self":[{"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/posts\/2020","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/comments?post=2020"}],"version-history":[{"count":0,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/posts\/2020\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/media\/2044"}],"wp:attachment":[{"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/media?parent=2020"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/categories?post=2020"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/tags?post=2020"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}