Jaydeep Profile picture
Apr 15, 2022 32 tweets 24 min read Read on X
Logging in #Python is something I want to master. So, starting #30DaysOfLogging from tomorrow.

Time to go from Zero(almost) To Hero.
#Day1 Basics Of Logging

1. We need logging to tell us what's happening in our code
2. Python has an inbuilt logging module which can be imported
3. DEBUG, INFO, WARNING, ERROR & CRITICAL are the level of logging available.
4. WARNING is the default logging level
#100DaysOfCode Image
#Day2

The whole purpose of logging is to be able to write events to a file. This is how you can do it

If you are Python Version > 3.9 then you can use the logging.basicConfig

#100DaysOfCode #Python Image
If you are on a version lower than 3.9 then the encoding option is not available in basicConfig and you can use the alternate option Image
#Day3 Formatting Log Messages & Default Format

We can customize the format in which log is displayed

>> logging.basicConfig(format="") allows you to set what you want to see in the log

>> The default format i.e. if you do not set any format is as shown below

#100DaysOfCode Image
#Day4
Various possible attributes available for format are as below

> You can combine them to generate logs as suitable for your application

> Logging is optimized to use %s strings over f-strings

e.g. logging.basicConfig(format='%(asctime)s-%(name)s')

#100DaysOfCode #Python Attributes available to for...
Day 5 :

>> Continuing with formatting of log outputs the date format displayed in the log using %(asctime)s can be altered using the datefmt argument

>> The format of the datefmt argument is the same as supported by time.strftime() [docs.python.org/3/library/time…]

#100DaysOfCode Image
Day 6:

#Python Logging module components explained ✅

Example of all logging modules combine 🎯

#100DaysOfCode ImageImage
Day 7: Using a config file for

Having a config file with all components of the logging file is ideal.
It offers:
>> Single point to configure logs, their handlers & their format
>> Ability for non-coders to change the log formats ImageImage
Day 7:

Since Python 3.2 the config file format has been moved to a YAML which we will see in the coming days
Day 8: A dive into various log handlers which with the help of 1. Have a format in which the log is displayed 2. The level of logs to be displayed decide where the log is written Image
✅StreamHandler >> Writes to the console
✅FileHandler >> Writes to a file on the disk

are the most common types of handlers used.

Below code snippet shows usage of both.

>> Error logs & above are written to a file
>> All logs are written to the console

#100DaysOfCode Image
Day 9: Implementing a SMTPHandler i.e. sending logs directly to email.

>> devanswers.co/create-applica… --> Use this to create an app specific password if you use gmail

#100DaysOfCode Day 9 code
Day10:

>> the logging.debug(), info(), etc signature shows a **kwargs parameter.

It can take in 3 arguments
1⃣ exc_info to display traceback data
2⃣ stack_info to display traceback data
3⃣ extra to display use custom formatter attribute

#100DaysOfCode ImageImageImage
Correction:

Since Python 3.8 there is a 4th argument available

4⃣ stacklevel which defaults to 1. If greater than 1, the corresponding number of stack frames are skipped when computing the line number and function name set in the LogRecord created for the logging event
Day 11:

Looking to add more information to your logs like traceback ? Here is how we can do it.

#Python #100DaysOfCode Image
Day 12:

Why not add some colors to the #Python logs ?

Use the coloredlogs packages to achieve it.

> Logging to console & each log level has a distinct color

#100DaysOfCode Image
Day 12:

Log output written to file also is neatly colored.

#100DaysOfCode #30DaysOfLogging #Python Image
Day 13:

You can use a #Dictionary to store logging config.

>> Notice the blank logger name to set the module name as the name of the logger.

#100DaysOfCode #Python #30DaysOfLogging Image
Day 14:

> The YAML is the preferred way of Python to store logging configuration

> A sample implementation is shown below

> Code available at my repo github.com/jaydeepkarale/…

#100DaysOfCode #Python #30DaysOfLogging Image
Day 15:

> Python logs are largely meant for humans but sometimes we may need to pass it to log analytics platforms as SPLUNK, Logstash, etc. These platforms consume data in JSON format

> We can use the python-json-logger module to output logs in JSON format

#100DaysOfCode Image
Day 16: LoggerAdapter for adding more info to logs

>> The logging module comes with a number of formatters but often you might need to pass additional context info to the logs & display it. This can be done using the LoggerAdapter class

Day 16: In below example

1⃣ Initialize a logger as usual

2⃣ Specify an additional attribute in the formatter

3⃣ We then pass the logger from step #1 & contextual info to LoggerAdapter class

4⃣ The info(), error() & other methods are then called on instance of LoggerAdapter Image
Day17:

>> We can override the process method in the LoggerAdapter class pass contextual/additional information with each log

>> Overriding the process method gives us the ability to pass a unique contextual info with each log ImageImageImage
Day 18: Filtering Python Logs

>> Filters allow you to
> Reject records based on certain criteria
> Add custom info to logs

>> We need to override the logging.Filter & then attach it to handler using .addFilter() >> logging.Filter class can...>> logging.Filter class can...>> logging.Filter class can...
Day 19 Of Python Logging: Filtering

>> Yesterday we saw how we can add filters to logs to prevent certain logs from showing up

>> But what if you need to log to show up but just a part of the log message to be hidden ? Just pass the LogRecord.msg to a new function to do the job ImageImageImage
Day 20 Of Python Logging:

>> Logging module is actually implemented in a thread-safe way.

>> Under the hood the logging module uses threading.RLock()

>> Lock vs RLock (stackoverflow.com/questions/2288…)

#100DaysOfCode ImageImageImage
Day 21: Logger Class
> Loggers should ALWAYS be instantiated through module-level function logging.getLogger(name)

> The name is potentially a period-separated hierarchical value like foo.bar.baz. The logger name hierarchy is analogous to the Python pkg hierarchy ImageImage
Day 22:

> error/exception occurring in he logging module methods such as info(), error(), warning() are taken care of by the Handler via the emit() method.

> The emit() calls has a handleError() in Exception block which prints the stack to the console

#100DaysOfCode Implementation of the emit(...Image showing python code &...Image showing code which ha...Image showing output of err...
Day 23: a video log about getting started with Python Logging for those who prefer learning by watching videos

#100DaysOfCode

Day24: RotatingFileHandler() To Create Log Files Of Specified Size

✅ maxBytes controls the file size
✅ backCount controls the number of file of size maxBytes. Default is 0 meaning only 1 file
✅ filename attribute is the filename

#100DaysOfCode #Python Image containing code snipp...ImageImage
Day 25: TimedRotatingFileHandler()

>> Rotate log files after certain time interval
>> Rotated files are automatically appended with a timestamp
>> Has a rich set of arguments to control the behaviour & output if the Handler.

#100DayOfCode #Python #MachineLearning #DataScience  >> Rotate log files after ...File containing Python code...Image containing signature ...Image indicating output of ...

• • •

Missing some Tweet in this thread? You can try to force a refresh
 

Keep Current with Jaydeep

Jaydeep Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @_jaydeepkarale

Jan 23
2 Month Data Engineering crash course curriculum designed specifically for Data Scientists. Image
✅ 𝗪𝗘𝗘𝗞 𝟭 & 2: 𝗗𝗔𝗧𝗔 𝗠𝗢𝗗𝗘𝗟𝗜𝗡𝗚 & 𝗔𝗥𝗖𝗛𝗜𝗧𝗘𝗖𝗧𝗨𝗥𝗘𝗦

These are the backbone of modern data platforms, and contribute directly towards how data scientists consume and interpret data.

✳️Topics

Star Schemas & Kimball approach
Normalization & denormalization
Slowly changing dimensions (SCDs)
Data Lake vs Data Warehouse vs Data Lakehouse

✳️ Resources

➡️Modern data modeling (Kahan):
youtu.be/IdCmMkQLvGA?si…

➡️Kimball Approach (Kahan):
youtu.be/gRE3E7VUzRU?si…

➡️SCDs (Tech Coach):
youtu.be/XqdZF0DJpUs?si…

➡️ Data Lakehouses explained (IBM):
youtu.be/Enu-EH7RHHM?si…
✅ 𝗪𝗘𝗘𝗞 3 & 4: 𝗗𝗜𝗦𝗧𝗥𝗜𝗕𝗨𝗧𝗘𝗗 𝗖𝗢𝗠𝗣𝗨𝗧𝗜𝗡𝗚

Distributed computing tools are critical when diving into raw and unstructured data that isn't yet pre-processed into clean feature stores or model marts.

✳️Topics

Fundamentals of distributed computing
Apache Spark
RDDs & Spark SQL

✳️Resources

➡️ Distributed Systems (freeCodeCamp):
freecodecamp.org/news/a-thoroug…

➡️ Pyspark Tutorial (datacamp):
datacamp.com/tutorial/pyspa…

➡️Spark RDD (Analytics Vidhya):
analyticsvidhya.com/blog/2021/08/u…

➡️ Spark SQL tutorial (opensource):
opensource.com/article/19/3/a…
Read 5 tweets
Jan 15
API Gateways Clearly Explained !!!

• What is an API Gateway?
• Why do we need to use API Gateway ?
• Visual Representation of API Gateway
• How does an API Gateway work ?
• Functionalities offered by API Gateway Image
#1 What Is An API Gateway ?

• API Gateways are present at layer & of the OSI model & play an important part in distributed system design & microservice architecture

• It sits between clients & servers , acting as a reverse proxy & serving as a single entry point for all requests

• It simplifies the client-server interaction by also handling tasks such as authentication, request routing, rate limiting, SSL termination, request aggregation, validation & transformation
#2 Why do we need to use an API Gateway ?

• Clients code becomes complicated as number of services grow Backend service also need to individually handle authentication, SSL termination, validation, etc

• Single operation may require multiple services to work together, in such cases client-service communication becomes subject to more round trips & higher latency

• Hard coupling between clients & the backend. The clients need to know a lot of detail about each individual backend service and implement code accordingly
Read 7 tweets
Jan 4
If you are learning DSA, you need to understand the orders of growth

Give me 2 minutes and I'll teach it to you
Order of growth describes how the runtime of an algorithm increases as the input size grows.

It focuses on the dominant term in the time complexity expression, ignoring constants and lower-order terms.
Big O notation is a popular method for calculating the orders of growth is used to describe the worst case scenario

The higher your code ranks in this table the better for you i.e. aim for logarithmic or linear time.

If you write code where time grows exponentially as input grows, your career is toastImage
Read 7 tweets
Dec 30, 2024
Python CLASSMETHOD decorator clearly explained !!!
Imagine you are working as a backend engineer for a company whose software is used by various retail outlets.

You've been tasked to create a class 'Product' which helps create a new product by taking in name, price & quantity_in_stock.

You do a simple harmless implementation ↓ Image
Your firm now get's a new retail outlet who want to use your software but need to create the product not based on name, price & quantity_in_stock but a product_code

Your 'Product' class looks at your like this
Read 6 tweets
Oct 3, 2024
API Gateways Clearly Explained !!!

• What is an API Gateway?
• Why do we need to use API Gateway ?
• Visual Representation of API Gateway
• How does an API Gateway work ?
• Functionalities offered by API Gateway Image
#1 What Is An API Gateway ?

• API Gateways are present at layer & of the OSI model & play an important part in distributed system design & microservice architecture

• It sits between clients & servers , acting as a reverse proxy & serving as a single entry point for all requests

• It simplifies the client-server interaction by also handling tasks such as authentication, request routing, rate limiting, SSL termination, request aggregation, validation & transformation
#2 Why do we need to use an API Gateway ?

• Clients code becomes complicated as number of services grow Backend service also need to individually handle authentication, SSL termination, validation, etc

• Single operation may require multiple services to work together, in such cases client-service communication becomes subject to more round trips & higher latency

• Hard coupling between clients & the backend. The clients need to know a lot of detail about each individual backend service and implement code accordingly
Read 7 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Don't want to be a Premium member but still want to support us?

Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal

Or Donate anonymously using crypto!

Ethereum

0xfe58350B80634f60Fa6Dc149a72b4DFbc17D341E copy

Bitcoin

3ATGMxNzCUFzxpMCHL5sWSt4DVtS8UqXpi copy

Thank you for your support!

Follow Us!

:(