{"id":86761,"date":"2023-02-09T09:00:38","date_gmt":"2023-02-09T03:30:38","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=86761"},"modified":"2023-02-09T09:00:38","modified_gmt":"2023-02-09T03:30:38","slug":"logging-in-python","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/logging-in-python\/","title":{"rendered":"Logging in Python"},"content":{"rendered":"<p><span style=\"font-weight: 400\">Logging is a powerful tool in any programming language, and Python is no exception. It allows you to record important events that occur in your programs, such as exceptions or messages, and save them to a log file or output them to the console. This can be especially useful when debugging or when you want to keep track of the progress of your program.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">How to use Logging in Python:<\/span><\/h3>\n<p><span style=\"font-weight: 400\">To use it in Python, you first need to import the module. Then, you can use the basic config function to set up the default logging configuration. This function takes several optional arguments, such as the log level, the log format, and the log file name.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Here is an example of how to set it up in Python:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import logging\n\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(TechVidvan)s')\n<\/pre>\n<p><span style=\"font-weight: 400\">Once the configuration is set up, you can use the various functions to log messages at different levels of severity. The most commonly used functions are debugging, info, warning, error, and critical.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Here is an example of how to log messages at different levels:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import logging\n\nlogging.debug('This is a debug message')\nlogging.info('This is an info message')\nlogging.warning('This is a warning message')\nlogging.error('This is an error message')\nlogging.critical('This is a critical message')\n<\/pre>\n<p><span style=\"font-weight: 400\">You can also use logging.exception function to log an exception, along with a traceback, to the log. We can use it for debugging and troubleshooting.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Here is an example of how to log an exception:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import logging\n\ntry:\n    # Some code that may raise an exception\nexcept for Exception as e:\n    logging.exception('An error occurred: %s', e)\n<\/pre>\n<p><span style=\"font-weight: 400\">In addition to logging messages to the console or a log file, you can also configure it to send messages to other destinations, such as email or a database. This can be especially useful for monitoring and alerting purposes.<\/span><\/p>\n<p><span style=\"font-weight: 400\">To send log messages to destinations other than the console or a log file, you can use the logging.handlers module in Python. This module provides various handler classes that you can use to send log messages to different destinations.<\/span><\/p>\n<p><span style=\"font-weight: 400\">For example, to send log messages to an email address, you can use the SMTPHandler class. This class sends log messages to an SMTP server, which can then forward the messages to an email address.<\/span><\/p>\n<p><span style=\"font-weight: 400\">To use the SMTPHandler class, you will need to import it from the logging.handlers module and create an instance of the class, passing in the necessary arguments such as the SMTP server details and the email address to which the messages should be sent.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Here is an example of how to send log messages to an email address using the SMTPHandler class:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import logging\nfrom logging.handlers import SMTPHandler\n\n# Set up the SMTP handler\nsmtp_handler = SMTPHandler(\n    mailhost='smtp.example.com',\n    fromaddr='logger@example.com',\n    toaddrs=['admin@example.com'],\n    subject='Application Log'\n)\n\n# Set the log level for the handler\nsmtp_handler.setLevel(logging.ERROR)\n\n# Add the handler to the logger\nlogger = logging.getLogger('my_logger')\nlogger.addHandler(smtp_handler)\n\n# Log a message\nlogger.error('This is an error message\u2019)\n<\/pre>\n<p><span style=\"font-weight: 400\">To send log messages to a database, you can use the DatabaseHandler class, which writes log records to a database table. This class is not a part of the Python standard library, but you can use third-party libraries such as Logbook or LoggingDB to achieve this.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">Various logging functions in Python<\/span><\/h3>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-87037\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/01\/various-logging-functions.webp\" alt=\"various logging functions\" width=\"845\" height=\"509\" \/><\/p>\n<h4><span style=\"font-weight: 400\">1. debug() in Python<\/span><\/h4>\n<p><span style=\"font-weight: 400\">Python&#8217;s logging module includes a function called debug() that is used to log messages with the DEBUG severity level. It is typically used to record detailed information that is useful for debugging the program.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Here is an illustration of how to utilize the Python script debug() function:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import logging\n\n# Configure the logging system\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(TechVidvan)s')\n\n# Log a debug message\nlogging.debug('This is a debug message.')\n<\/pre>\n<p><span style=\"font-weight: 400\">In this example, we set the level to logging.DEBUG, which means that all log messages with a level of DEBUG or higher will be logged. The format argument specifies the type of format of the log messages including the timestamp, the log level, and the log message itself.<\/span><\/p>\n<p><span style=\"font-weight: 400\">It&#8217;s important to note that the debug() function will only log messages if the level is set to logging.DEBUG or higher. If it is set to a lower value (e.g., logging.INFO or logging.WARNING), the debug() function will not log any messages.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">2. warning() in Python<\/span><\/h3>\n<p><span style=\"font-weight: 400\">The warning() function is a part of the module in Python and is used to log messages with a severity level of WARNING. It is typically used to record messages that indicate a potential problem that needs to be addressed.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Here is an illustration of how to employ the Python script&#8217;s warning() function:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import logging\n# Configure the logging system\nlogging.basicConfig(level=logging.WARNING, format='%(asctime)s - %(levelname)s - %(TechVidvan)s')\n\n# Log a warning message\nlogging.warning('This is a warning message.')\n<\/pre>\n<p><span style=\"font-weight: 400\">In this example, we set the level to logging.WARNING, which means that all log messages with a level of WARNING or higher will be logged. The format argument specifies the type of format of the log messages including the timestamp, the log level, and the log message itself.<\/span><\/p>\n<p><span style=\"font-weight: 400\">It&#8217;s important to note that the warning() function will only log messages if the level is set to logging.WARNING or higher. If the level is set to a lower value (e.g., logging.INFO or logging.DEBUG), the warning() function will not log any messages.<\/span><\/p>\n<h4>3. info() in Python<\/h4>\n<p><span style=\"font-weight: 400\">The info() function is a part of the module in Python and is used to log messages with a severity level of INFO. It mostly serves to keep track of general program execution data.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Here is a sample Python script that uses the info() method:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import logging\n\n# Configure the logging system\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(TechVidvan)s')\n\n# Log an info message\nlogging.info('This is an info message.')\n<\/pre>\n<p><span style=\"font-weight: 400\">In this example, we set the level to logging.INFO, which means that all log messages with a level of INFO or higher will be logged. The format argument specifies the type of format of the log messages including the timestamp, the log level, and the log message itself.<\/span><\/p>\n<p><span style=\"font-weight: 400\">It&#8217;s important to note that the info() function will only log messages if the level is set to logging.INFO or higher. If the level is set to a lower value (e.g., logging.DEBUG or logging.WARNING), the info() function will not log any messages.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">4. error() in Python<\/span><\/h3>\n<p><span style=\"font-weight: 400\">The error() function is a part of the module in Python and is used to log messages with a severity level of ERROR. It is typically used to record messages that indicate a problem that needs to be addressed.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Here is an illustration of how to employ the Python script&#8217;s error() function:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import logging\n\n# Configure the logging system\nlogging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(TechVidvan)s')\n\n# Log an error message\nlogging.error('This is an error message.')\n<\/pre>\n<h3><span style=\"font-weight: 400\">5. critical() in Python<\/span><\/h3>\n<p><span style=\"font-weight: 400\">The critical() function is a part of the module in Python and is used to log on to messages with a CRITICAL severity level. It is typically used to record messages that indicate a critical problem that needs to be addressed immediately.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Here is an illustration of how to use the Python script&#8217;s crucial() function.:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import logging\n\n# Configure the logging system\nlogging.basicConfig(level=logging.CRITICAL, format='%(asctime)s - %(levelname)s - %(TechVidvan)s')\n\n# Log a critical message\nlogging.critical('This is a critical message.')\n<\/pre>\n<p><span style=\"font-weight: 400\">In this example, we set the level to logging.CRITICAL, which means that all log messages with a level of CRITICAL or higher will be logged. The format argument specifies the type of format of the log messages including the timestamp, the log level, and the log message itself.<\/span><\/p>\n<p><span style=\"font-weight: 400\">It&#8217;s important to note that the critical() function will only log messages if the level is set to logging.CRITICAL or higher. If the level is set to a lower value (e.g., logging.ERROR or logging.WARNING), the critical() function will not log any messages.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">Conclusion:<\/span><\/h3>\n<p><span style=\"font-weight: 400\">In this TechVidvan article, we have learned that the logging module in Python provides a flexible and powerful way to track events and record log messages in your code. It is an essential tool for debugging, monitoring, and understanding what&#8217;s happening in your program.<\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Logging is a powerful tool in any programming language, and Python is no exception. It allows you to record important events that occur in your programs, such as exceptions or messages, and save them&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":87036,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[4839,4840],"class_list":["post-86761","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-logging-in-python","tag-python-logging-functions"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Logging in Python - TechVidvan<\/title>\n<meta name=\"description\" content=\"Logging module in Python provides flexible &amp; powerful way to track events &amp; record log messages in your code. See various logging functions.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/logging-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Logging in Python - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Logging module in Python provides flexible &amp; powerful way to track events &amp; record log messages in your code. See various logging functions.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/logging-in-python\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-02-09T03:30:38+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/logging-in-python.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Logging in Python - TechVidvan","description":"Logging module in Python provides flexible & powerful way to track events & record log messages in your code. See various logging functions.","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:\/\/techvidvan.com\/tutorials\/logging-in-python\/","og_locale":"en_US","og_type":"article","og_title":"Logging in Python - TechVidvan","og_description":"Logging module in Python provides flexible & powerful way to track events & record log messages in your code. See various logging functions.","og_url":"https:\/\/techvidvan.com\/tutorials\/logging-in-python\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2023-02-09T03:30:38+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/logging-in-python.webp","type":"image\/webp"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/logging-in-python\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/logging-in-python\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Logging in Python","datePublished":"2023-02-09T03:30:38+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/logging-in-python\/"},"wordCount":1139,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/logging-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/logging-in-python.webp","keywords":["Logging in Python","python logging functions"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/logging-in-python\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/logging-in-python\/","url":"https:\/\/techvidvan.com\/tutorials\/logging-in-python\/","name":"Logging in Python - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/logging-in-python\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/logging-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/logging-in-python.webp","datePublished":"2023-02-09T03:30:38+00:00","description":"Logging module in Python provides flexible & powerful way to track events & record log messages in your code. See various logging functions.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/logging-in-python\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/logging-in-python\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/logging-in-python\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/logging-in-python.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/logging-in-python.webp","width":1200,"height":628,"caption":"logging in python"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/logging-in-python\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Logging in Python"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/86761","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=86761"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/86761\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/87036"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=86761"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=86761"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=86761"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}