DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Integrated Gradients: AI Explainability for Regulated Industries
  • Efficient String Formatting With Python f-Strings
  • What Is Pydantic?
  • OpenTelemetry Python: All You Need to Know About Tracing

Trending

  • Designing Fault-Tolerant Messaging Workflows Using State Machine Architecture
  • Data Lake vs. Warehouse vs. Lakehouse vs. Mart: Choosing the Right Architecture for Your Business
  • Next Evolution in Integration: Architecting With Intent Using Model Context Protocol
  • How Kubernetes Cluster Sizing Affects Performance and Cost Efficiency in Cloud Deployments
  1. DZone
  2. Coding
  3. Languages
  4. How To Add Custom Attributes in Python Logging

How To Add Custom Attributes in Python Logging

Logging is essential for any software system to troubleshoot a wide range of issues. Learn how to use Python logging using custom attributes effectively.

By 
Ganesh Nagarajan user avatar
Ganesh Nagarajan
·
May. 10, 24 · Code Snippet
Likes (2)
Comment
Save
Tweet
Share
5.3K Views

Join the DZone community and get the full member experience.

Join For Free

Logging is essential for any software system. Using logs, you can troubleshoot a wide range of issues, including debugging an application bug, security defect, system slowness, etc. In this article, we will discuss how to use Python logging effectively using custom attributes.

Python Logging

Before we delve in, I briefly want to explain a basic Python logging module with an example.

#!/opt/bb/bin/python3.7

import logging
import sys

root = logging.getLogger()
root.setLevel(logging.DEBUG)
std_out_logger = logging.StreamHandler(sys.stdout)
std_out_logger.setLevel(logging.INFO)
std_out_formatter = logging.Formatter("%(levelname)s - %(asctime)s  %(message)s")
std_out_logger.setFormatter(std_out_formatter)
root.addHandler(std_out_logger)

logging.info("I love Dzone!")


The above example prints the following when executed:

 
INFO - 2024-03-09 19:49:07,734  I love Dzone!


In the example above, we are creating the root logger and the logging format for log messages. On line 6, logging.getLogger() returns the logger if already created; if not, it goes one level above the hierarchy and returns the parent logger. We define our own StreamHandler to print the log message at the console.

Whenever we log messages, it is essential to log the basic attributes of the LogRecord. On line 10, we define the basic format that includes level name, time in string format, and the actual message itself. The handler thus created is set at the root logger level.

We could use any pre-defined log attribute name and the format from the LogRecord library. However, let's say you want to print some additional attributes like contextId, a custom logging adapter to the rescue.

Logging Adapter

class MyLoggingAdapter(logging.LoggerAdapter):

    def __init__(self, logger):
        logging.LoggerAdapter.__init__(self, logger=logger, extra={})

    def process(self, msg, kwargs):
        return msg, kwargs


We create our own version of Logging Adapter and pass "extra" parameters as a dictionary for the formatter.

ContextId Filter

import contextvars

class ContextIdFilter(logging.Filter):

    context_id = contextvars.ContextVar('context_id', default='')

    def filter(self, record):
        # add a new UUID to the context.
        req_id = str(uuid.uuid4())
        if not self.context_id.get():
            self.context_id.set(req_id)
        record.context_id = self.context_id.get()
        return True


We create our own filter that extends the logging filter, which returns True if the specified log record should be logged. We simply add our parameter to the log record and return True always, thus adding our unique id to the record. In our example above, a unique id is generated for every new context. For an existing context, we return already stored contextId from the contextVars.

Custom Logger

import logging

root = logging.getLogger()
root.setLevel(logging.DEBUG)
std_out_logger = logging.StreamHandler(sys.stdout)
std_out_logger.setLevel(logging.INFO)
std_out_formatter = logging.Formatter("%(levelname)s - %(asctime)s ContextId:%(context_id)s  %(message)s")
std_out_logger.setFormatter(std_out_formatter)
root.addHandler(std_out_logger)
root.addFilter(ContextIdFilter())

adapter = MyLoggingAdapter(root)

adapter.info("I love Dzone!")
adapter.info("this is my custom logger")
adapter.info("Exiting the application")


Now let's put it together in our logger file. Add the contextId filter to the root. Please note that we are using our own adapter in place of logging wherever we need to log the message.

Running the code above prints the following message:

 
INFO - 2024-04-20 23:54:59,839 ContextId:c10af4e9-6ea4-4cdf-9743-ea24d0febab6 I love Dzone!
INFO - 2024-04-20 23:54:59,842 ContextId:c10af4e9-6ea4-4cdf-9743-ea24d0febab6 this is my custom logger
INFO - 2024-04-20 23:54:59,843 ContextId:c10af4e9-6ea4-4cdf-9743-ea24d0febab6 Exiting the application


By setting root.propagate = False, events logged to this logger will be passed to the handlers of higher logging, aka parent logging class.

Conclusion

Python does not provide a built-in option to add custom parameters in logging. Instead, we create a wrapper logger on top of the Python root logger and print our custom parameters. This would be helpful at the time of debugging request-specific issues.

Attribute (computing) Python (language)

Opinions expressed by DZone contributors are their own.

Related

  • Integrated Gradients: AI Explainability for Regulated Industries
  • Efficient String Formatting With Python f-Strings
  • What Is Pydantic?
  • OpenTelemetry Python: All You Need to Know About Tracing

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!