DeveloperBreeze

Python Logging Snippet

This snippet sets up a logger that writes log messages to both the console and a file, with different log levels to capture various types of information.

import logging
import os

# Create a directory for logs if it doesn't exist
if not os.path.exists('logs'):
    os.makedirs('logs')

# Configure the logger
logging.basicConfig(
    level=logging.DEBUG,  # Set the logging level
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('logs/app.log'),  # Log to a file
        logging.StreamHandler()               # Log to the console
    ]
)

# Get the logger instance
logger = logging.getLogger('MyAppLogger')

# Example usage of the logger
def divide_numbers(x, y):
    try:
        logger.debug(f"Attempting to divide {x} by {y}")
        result = x / y
        logger.info(f"Division successful: {result}")
        return result
    except ZeroDivisionError as e:
        logger.error("Division by zero error", exc_info=True)
    except Exception as e:
        logger.exception("An unexpected error occurred")

# Demonstrate logging in action
if __name__ == "__main__":
    divide_numbers(10, 2)  # Normal operation
    divide_numbers(10, 0)  # Division by zero

Explanation

  • Log Levels: The logger is configured with different log levels:

- DEBUG: Detailed information, typically of interest only when diagnosing problems.

- INFO: Confirmation that things are working as expected.

- ERROR: A more serious problem, which prevented the program from completing a function.

- EXCEPTION: Similar to ERROR, but logs exception information.

  • Logging Handlers: The logging module is configured to handle logging in two ways:

- FileHandler: Writes logs to a file (logs/app.log), useful for long-term storage and analysis.

- StreamHandler: Outputs logs to the console, providing immediate feedback.

  • Logging Format: The format for log messages includes the timestamp, logger name, log level, and message.

  • Error Handling: The code demonstrates how to log exceptions with stack traces using exc_info=True or the exception() method.

Usage

  • Add Logging to Your Application: Use this snippet to quickly integrate logging into any Python application.

  • Monitor Application Behavior: By capturing logs, you can gain insights into application behavior, identify issues, and understand the flow of operations.

  • Debugging: Use DEBUG and INFO logs to follow the logic and data flow through your application.

  • Auditing: Keep track of important operations, errors, and exceptions for auditing purposes.

Logging is a fundamental aspect of software development, helping developers understand and maintain complex systems effectively. This snippet provides a robust starting point for adding logging capabilities to your applications.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
bash

Mastering Advanced Git Workflows for Professional Developers

Extract a subdirectory into its own repository:

git filter-repo --path path/to/subdir

Dec 10, 2024
Read More
Code
javascript

Dynamic and Responsive DataTable with Server-Side Processing and Custom Styling

  • responsive: true makes the table adapt to different screen sizes.
  • serverSide: true enables server-side pagination, sorting, and filtering.
  • processing: true displays a processing indicator while fetching data.

Oct 24, 2024
Read More
Tutorial
php

Handling HTTP Requests and Raw Responses in Laravel

When working with OAuth or JWT-based APIs, you may need to pass a Bearer Token for authentication.

use Illuminate\Support\Facades\Http;

$response = Http::withToken('your-bearer-token')->post('https://api.example.com/endpoint', [
    'key1' => 'value1',
    'key2' => 'value2',
]);

dd($response->body());

Oct 24, 2024
Read More
Article
javascript

20 Useful Node.js tips to improve your Node.js development skills:

No preview available for this content.

Oct 24, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

The Fetch API is a modern alternative to XMLHttpRequest. It's easier to use, more flexible, and based on Promises, making it simpler to handle asynchronous requests.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX with Fetch API</title>
</head>
<body>
    <button id="fetchDataBtn">Fetch Data</button>
    <div id="dataOutput"></div>

    <script>
        document.getElementById('fetchDataBtn').addEventListener('click', function() {
            fetch('https://jsonplaceholder.typicode.com/posts/1')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    document.getElementById('dataOutput').innerHTML = `
                        <h3>${data.title}</h3>
                        <p>${data.body}</p>
                    `;
                })
                .catch(error => console.error('There was a problem with the fetch operation:', error));
        });
    </script>
</body>
</html>

Sep 18, 2024
Read More
Tutorial
javascript

Advanced JavaScript Tutorial for Experienced Developers

The Fetch API does not automatically reject a promise when it receives an HTTP error status (e.g., 404 or 500). Instead, you need to check the ok property of the response to determine if the request was successful.

fetch('https://api.example.com/data')
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => console.log(data))
    .catch(error => console.error('Fetch error:', error));

Sep 02, 2024
Read More
Tutorial
javascript

Getting Started with Axios in JavaScript

  • We create an Axios instance with a base URL and custom configuration.
  • The instance can be reused for multiple requests, simplifying your code.

Axios is a powerful and flexible library for making HTTP requests in JavaScript. Whether you're fetching data, submitting forms, or handling complex API interactions, Axios simplifies the process with its clean and consistent API. By mastering the basics covered in this tutorial, you'll be well-equipped to use Axios in your own projects.

Sep 02, 2024
Read More
Tutorial
python

Setting Up and Managing Python Virtual Environments Using venv

To deactivate the virtual environment, run:

Once the virtual environment is activated, you can install packages using pip:

Aug 29, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

- string: Dynamically-sized UTF-8 encoded string

- bytes: Dynamically-sized byte array

Aug 22, 2024
Read More
Tutorial
bash

Creating and Managing Bash Scripts for Automation

   nano my_first_script.sh

The first line of a bash script should always be the shebang (#!) followed by the path to the Bash interpreter:

Aug 19, 2024
Read More
Code
javascript

React Custom Hook for API Requests

No preview available for this content.

Aug 12, 2024
Read More
Code
javascript

Fetching Chuck Norris Jokes from API in JavaScript

No preview available for this content.

Jan 26, 2024
Read More
Code
php

PHP File Upload

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Promise-based Execution of Python Code with jsPython

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript python

Execute Python Code Using Skulpt

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

POST Request with Fetch API and JSON Data

No preview available for this content.

Jan 26, 2024
Read More
Code
python

Bybit Futures API Integration Using ccxt Library with Error Handling

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!