pyEventLogger - a simple Python Library for making customized Logs of certain events that occur in a program

Overview

pyEventLogger v1.0

pyEventLogger is a simple Python Library for making customized Logs of certain events that occur in a program. The logs can be fully customized and can be printed in colored format or can be stored in a file.

Note: Your software or the console in which you are going to print colored logs should support the ANSI Escape Sequences or the colored logs feature may not work!

Installation

To install this library, type:

pip install pyEventLogger

in the Command Prompt or Terminal

Import

To import this library, use the following code:

from pyEventLogger import pyLogger

Logging Levels:

There are 6 different types of logs in this library. In order of increasing importance, they are:

  • Debug
  • Info
  • Warning
  • Success
  • Error
  • Critical

Print basic logs:

Use the following program to print basic logs in the Console:

from pyEventLogger import pyLogger  # Import the library

logger = pyLogger(colored_output=True)  # Make an object of the pyLogger Class
# Note: If your console doesn't support the ANSI Escape Sequences then use: colored_output=False

logger.debug(message="This is Debug Message!")  # Debug Log
logger.info(message="This is Information Message!")  # Information Log
logger.warn(message="This is Warning Message!")  # Warning Log
logger.success(message="This is Success Message!")  # Success Log
logger.error(message="This is Error Message!")  # Error Log
logger.critical(message="This is Critical Message!")  # Critical Log

The pyLogger Class

Parameters

The pyLogger Class has the following Parameters:

  • colored_output --> Set it to True if you want colored output
  • print_log --> Set it to True if you want your log to be printed out into the Console
  • make_file --> Set it to True if you want your log to be stored in a file
  • file_name --> If you set the make_file parameter to True, then you can use this parameter to change the file name
  • rewrite_file --> Set it to True if you want your log file to be rewritten after you run the program
  • file_logs --> If you want only the specified log messages in your file then pass this parameter with a list containing the log types you want. Example: If you want only the errors and critical messages in file then you pass the value of the parameter as python ['ERROR', 'CRITICAL']

Customizing the Logs:

Customizing the Log text:

To customize a log, use the format_log(log_type, format_string) function. For example, if you want to customize the log type of Debug, then use the following code:

from pyEventLogger import pyLogger

logger = pyLogger()

debug_format_string = "[log_type] [time] [message]"  # Define a variable for the format string

logger.format_log(log_type='DEBUG', format_string=debug_format_string)  # Use this function to format a log

logger.debug(message="This is Debug Message!")

See the above example. It has a variable called debug_format_string which defines how the contents of the Log should be.

Rules for format strings:

The format string should have a format like "[time] [log_type] [message]". Where the contents in the squared braces [] will be replaced with the values of the parameters you pass to that function. You can give any number of spaces you like between the contents. Example: "[log_type] [time] [message]". The log will be printed in the same format and also can be written in a file in the same format.

There are some special meanings to some parameters like log_type. The program automatically adds the log type even if the user doesn't pass that parameter's value to a function, also the time parameter will be given a default value of the time that function is called.

You can add any number of contents in a log. Example Code:

from pyEventLogger import pyLogger

logger = pyLogger()

debug_format_string = "[log_type] [time] [message] [file_name]"  # Add a 'file_name' content

logger.format_log(log_type='DEBUG', format_string=debug_format_string)

logger.debug(message="This is Debug Message!", file_name="main.py")  # Set a value to the added content

Customizing the Log text color/style:

To customize a log's color, use the format_log_color(log_type, format_string) function. For example, if you want to customize the log type of Debug, then use the following code:

from pyEventLogger import pyLogger

logger = pyLogger(colored_output=True)  # Set the colored output to True

debug_format_string = "[log_type] [time] [file_name] [message]"  # Define a variable for the format string
debug_format_color = "[bold cyan black] [normal yellow black] [italic magenta black] [normal white black]"  # Define a variable for the format color

logger.format_log(log_type='DEBUG', format_string=debug_format_string)  # Format the log
logger.format_log_color(log_type='DEBUG', format_string=debug_format_color)  # Format the color

logger.debug(message="This is Debug Message!", file_name="main.py")

In the above example, you can see that there is a variable defined for the log color.

Rules for format color:

The format of color string should be the same as text string.

The contents should be seperated by space.

The first content in square braces should be the text style like normal, bold,italic,etc.

The second content should be the text color and the third should be background color. You can also use HEX values for colors too!

These three elements should be seperated by a space.

The first content will be the style for first item in log and so on...

Changing the format of time:

To change the format of time, use the format_time variable of the pyLogger class It should be in string format and is the same format as used in Python time.strftime() function.

Including error messages in error and critical log:

To include the error messages along with the log message in error and critical logs, set the include_error_message parameter of the error and critical functions to True

Example Code:

import time
import random
from pyEventLogger import pyLogger

logger = pyLogger(colored_output=False, make_file=True, file_name='math', rewrite_file=True)

logger.format_log(log_type="INFO", format_string="[time] [log_type] [message] [answer]")
logger.format_log_color(log_type="INFO",
                        format_string="[bold yellow black][bold magenta black][normal #FFFFFF black][italic green black]")

while True:
    try:
        logger.debug(message="Taking two random numbers...")
        n1 = random.randint(-10, 10)
        n2 = random.randint(-10, 10)
        logger.debug(message="Successfully found two random numbers!")

        logger.info(message=f"Two numbers are {n1} and {n2}")

        logger.debug(message="Starting operations with two numbers...")
        addition = n1 + n2
        logger.info(message="Added two numbers:", answer=addition)
        subtraction = n2 - n1
        logger.info(message="Subtracted two numbers:", answer=subtraction)
        multiplication = n1 * n2
        logger.info(message="Multiplied two numbers:", answer=multiplication)
        division = n2 / n1
        logger.info(message="Divided two numbers:", answer=division)

        logger.success(message="Successfully completed operations with two numbers!")
    except ZeroDivisionError:
        logger.error(message="An Error Occurred!", include_error_message=True)
    time.sleep(10)

Change Log:

  • 15/01/2022(v0.1) - First made this library and updated it
  • 15/01/2022(v0.1.2) - Updated and added many features
  • 21/01/2022(v0.5.0) - Updated and added some other features
  • 23/01/2022(v0.7) - Added Exceptions
  • 27/01/2022(v0.9) - Added features to error and critical logs
  • 28/01/2022(v1.0) - Added doc-strings to code\
  • 29/01/2022(v1.0) - First Release!

Thank You!

You might also like...
Pretty-print tabular data in Python, a library and a command-line utility. Repository migrated from bitbucket.org/astanin/python-tabulate.

python-tabulate Pretty-print tabular data in Python, a library and a command-line utility. The main use cases of the library are: printing small table

Rich is a Python library for rich text and beautiful formatting in the terminal.
Rich is a Python library for rich text and beautiful formatting in the terminal.

Rich 中文 readme • lengua española readme • Läs på svenska Rich is a Python library for rich text and beautiful formatting in the terminal. The Rich API

A basic logging library for Python.
A basic logging library for Python.

log.py 📖 About: A basic logging library for Python with the capability to: save to files. have custom formats. have custom levels. be used instantiat

A lightweight logging library for python applications

cakelog a lightweight logging library for python applications This is a very small logging library to make logging in python easy and simple. config o

A Python library that tees the standard output & standard error from the current process to files on disk, while preserving terminal semantics

A Python library that tees the standard output & standard error from the current process to files on disk, while preserving terminal semantics (so breakpoint(), etc work as normal)

Python logging made (stupidly) simple
Python logging made (stupidly) simple

Loguru is a library which aims to bring enjoyable logging in Python. Did you ever feel lazy about configuring a logger and used print() instead?... I

ClusterMonitor - a very simple python script which monitors and records the CPU and RAM consumption of submitted cluster jobs
ClusterMonitor - a very simple python script which monitors and records the CPU and RAM consumption of submitted cluster jobs

ClusterMonitor A very simple python script which monitors and records the CPU and RAM consumption of submitted cluster jobs. Usage To start recording

A simple, transparent, open-source key logger, written in Python, for tracking your own key-usage statistics.
A simple, transparent, open-source key logger, written in Python, for tracking your own key-usage statistics.

A simple, transparent, open-source key logger, written in Python, for tracking your own key-usage statistics, originally intended for keyboard layout optimization.

This is a wonderful simple python tool used to store the keyboard log.

Keylogger This is a wonderful simple python tool used to store the keyboard log. Record your keys. It will capture passwords and credentials in a comp

Comments
  • Multiple format changes at once

    Multiple format changes at once

    Added a for loop and also made it such that you can input both a list and a string into the log_type param to change multiple formats at once.

    Also you can edit to change some stuff

    not tested

    use case:

    To change 2 formats:

    logger.format_log(log_type='DEBUG', format_string=debug_format_string)
    logger.format_log(log_type='ERROR', format_string=debug_format_string)
    

    Now:

    logger.format_log(log_type=['DEBUG', 'ERROR'], format_string=debug_format_string)
    

    changing 1 at a time should work as it used to because of line 164

    opened by Quantum-Codes 1
  • Idea

    Idea

    Change format string from using square brackets to curly. From [file_name] [time] to {file_name} {time}

    If you do this, then you can use format functions to replace those with real values easily "{file_name} {time}".format(time="12:00", file_name="main.py")

    opened by Quantum-Codes 1
Owner
Siddhesh Chavan
I am a 15 year old boy who loves coding!
Siddhesh Chavan
Vibrating-perimeter - Simple helper mod that logs how fast you are mining together with a simple buttplug.io script to control a vibrator

Vibrating Perimeter This project consists of a small minecraft helper mod that writes too a log file and a script that reads said log. Currently it on

Heart[BOT] 0 Nov 20, 2022
A python library used to interact with webots robocup game web logs

A python library used to interact with webots robocup game web logs

Hamburg Bit-Bots 2 Nov 5, 2021
Keylogger with Python which logs words into server terminal.

word_logger Experimental keylogger with Python which logs words into server terminal.

Selçuk 1 Nov 15, 2021
APT-Hunter is Threat Hunting tool for windows event logs

APT-Hunter is Threat Hunting tool for windows event logs which made by purple team mindset to provide detect APT movements hidden in the sea of windows event logs to decrease the time to uncover suspicious activity

null 824 Jan 8, 2023
Greppin' Logs: Leveling Up Log Analysis

This repo contains sample code and example datasets from Jon Stewart and Noah Rubin's presentation at the 2021 SANS DFIR Summit titled Greppin' Logs. The talk was centered around the idea that Forensics is Data Engineering and Data Science, and should be approached as such. Jon and Noah focused on the core (Unix) command line tools useful to anyone analyzing datasets from a terminal, purpose-built tools for handling structured tabular and JSON data, Stroz Friedberg's open source multipattern search tool Lightgrep, and scaling with AWS.

Stroz Friedberg 20 Sep 14, 2022
Splunk Add-On to collect audit log events from Github Enterprise Cloud

GitHub Enterprise Audit Log Monitoring Splunk modular input plugin to fetch the enterprise audit log from GitHub Enterprise Support for modular inputs

Splunk GitHub 12 Aug 18, 2022
Lazy Profiler is a simple utility to collect CPU, GPU, RAM and GPU Memory stats while the program is running.

lazyprofiler Lazy Profiler is a simple utility to collect CPU, GPU, RAM and GPU Memory stats while the program is running. Installation Use the packag

Shankar Rao Pandala 28 Dec 9, 2022
Simple and versatile logging library for python 3.6 above

Simple and versatile logging library for python 3.6 above

Miguel 1 Nov 23, 2022
Outlog it's a library to make logging a simple task

outlog Outlog it's a library to make logging a simple task!. I'm a lazy python user, the times that i do logging on my apps it's hard to do, a lot of

ZSendokame 2 Mar 5, 2022
metovlogs is a very simple logging library

metovlogs is a very simple logging library. Setup is one line, then you can use it as a drop-in print replacement. Sane and useful log format out of the box. Best for small or early projects.

Azat Akhmetov 1 Mar 1, 2022