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

   git sparse-checkout set path/to/dir

Git hooks allow you to automate tasks during the Git lifecycle.

Dec 10, 2024
Read More
Code
javascript

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

  • drawCallback: Applies custom classes to various table elements (e.g., rows, headers, cells) after each table draw to enhance the appearance.

Oct 24, 2024
Read More
Tutorial
php

Handling HTTP Requests and Raw Responses in Laravel

If the raw response is in the form of a query string (e.g., key1=value1&key2=value2), you can use PHP’s built-in parse_str() function to convert it into an associative array.

use Illuminate\Support\Facades\Http;

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

$rawResponse = $response->body(); // Get the raw response
$parsedResponse = [];

// Parse the query string into an associative array
parse_str($rawResponse, $parsedResponse);

dd($parsedResponse); // Now you can work with the associative array

Oct 24, 2024
Read More
Article
javascript

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

These Node.js tips will help you write more robust, secure, and efficient Node.js applications and improve your development workflow.

Oct 24, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

Fetch and display search results in real-time as users type in the search box.

Fetch and update filtered data dynamically without reloading the entire page.

Sep 18, 2024
Read More
Tutorial
javascript

Advanced JavaScript Tutorial for Experienced Developers

The Reflect API, introduced in ES6, provides a set of methods for intercepting and manipulating object operations such as property assignment, function calls, and prototype management. It is often used in conjunction with Proxies to perform advanced operations.

The Reflect API provides methods that mirror the behavior of standard object operations but are more consistent and predictable. Here are a few examples:

Sep 02, 2024
Read More
Tutorial
javascript

Getting Started with Axios in JavaScript

Axios allows you to make multiple requests simultaneously using axios.all() and axios.spread().

axios.all([
    axios.get('https://jsonplaceholder.typicode.com/posts/1'),
    axios.get('https://jsonplaceholder.typicode.com/posts/2')
  ])
  .then(axios.spread((post1, post2) => {
    console.log('Post 1:', post1.data);
    console.log('Post 2:', post2.data);
  }))
  .catch(error => {
    console.error('Error fetching data:', error);
  });

Sep 02, 2024
Read More
Tutorial
python

Setting Up and Managing Python Virtual Environments Using venv

Virtual environments help maintain a clean and organized development environment by:

  • Isolating dependencies for different projects.
  • Allowing different projects to use different versions of the same package.
  • Preventing dependency conflicts that can arise from using global installations.

Aug 29, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

  • Avoid complex computations within loops.

  • Use immutable and constant for variables that do not change.

Aug 22, 2024
Read More
Tutorial
bash

Creating and Managing Bash Scripts for Automation

  • Use Comments: Document your code with comments to explain what each part of the script does.
  • Modularize with Functions: Break your script into functions to make it more readable and maintainable.
  • Test Thoroughly: Test your scripts in different environments to ensure they work as expected.
  • Use Meaningful Variable Names: Choose descriptive names for variables to improve code clarity.
  • Handle Errors Gracefully: Implement error handling to make your scripts more robust and reliable.

Bash scripting is a powerful tool that can automate tasks, improve efficiency, and enhance your productivity in the Linux environment. Whether you're managing files, performing system maintenance, or automating repetitive tasks, mastering bash scripts will allow you to achieve more with less effort. By following the techniques and best practices outlined in this guide, you can write effective and reliable bash scripts that streamline your workflow.

Aug 19, 2024
Read More
Code
javascript

React Custom Hook for API Requests

import { useState, useEffect } from 'react';

function useFetch(url, options = {}) {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        let isMounted = true; // Track if component is mounted

        const fetchData = async () => {
            setLoading(true);
            try {
                const response = await fetch(url, options);
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const result = await response.json();
                if (isMounted) {
                    setData(result);
                }
            } catch (error) {
                if (isMounted) {
                    setError(error);
                }
            } finally {
                if (isMounted) {
                    setLoading(false);
                }
            }
        };

        fetchData();

        return () => {
            isMounted = false; // Cleanup to avoid setting state on unmounted component
        };
    }, [url, options]);

    return { data, loading, error };
}

export default useFetch;

Here’s an example of how to use the useFetch hook in a React component to fetch and display data.

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


const apiUrl = 'https://api.example.com/data';
const requestData = {
    name: 'John Doe',
    age: 30,
};

// Send a POST request using fetch
fetch(apiUrl, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json', // Specify JSON content type
    },
    body: JSON.stringify(requestData), // Convert data to JSON string
})
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Success:', data); // Handle successful response
    })
    .catch(error => {
        console.error('Error:', error); // Handle errors
    });

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!