Skip to content

Commit

Permalink
Update README and Logger classes to enhance logging styles and improv…
Browse files Browse the repository at this point in the history
…e usage examples
  • Loading branch information
sexfrance committed Jan 20, 2025
1 parent 402799f commit b0df6d2
Show file tree
Hide file tree
Showing 4 changed files with 131 additions and 59 deletions.
153 changes: 110 additions & 43 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,19 @@
# LogMagix

Beautiful & Simple Python Logger

## Installation
```bash
git clone https://github.com/sexfance/logmagix
cd logmagix
pip install -e .
```
## 🚀 Quick Start

## Usage
```python
from logmagix import Logger, LogLevel

# Initialize with GitHub repository
# Choose your logging style (1 = ColorLogger, 2 = SimpleLogger)
log = Logger(
style=1, # Default colorful style
prefix="MyApp",
github_repository="https://github.com/sexfance/logmagix",
level=LogLevel.DEBUG
github_repository="https://github.com/sexfrance/logmagix",
level=LogLevel.DEBUG,
log_file="logs/app.log" # Optional log file
)

# Basic logging
Expand Down Expand Up @@ -108,41 +105,80 @@ log = Logger(level=LogLevel.WARNING)

With this setting, only `WARNING`, `SUCCESS`, `FAILURE`, and `CRITICAL` messages will display.

### Log File Saving
## 🎨 Logging Styles

You can specify a log file path to save logs to a file for further review or debugging. The logger will automatically strip ANSI color codes from messages saved to the log file for readability. Log files are appended with each new logging session.
LogMagix offers two distinct logging styles:

### Style 1: ColorLogger (Default)

```python
log = Logger(log_file="logs/app.log")
log.success("This message will also be saved to app.log")
log = Logger(style=1) # or just Logger()
```

To view logs saved to the file, open the specified path and review the recorded entries, which include timestamped log messages for tracking system state over time.
Features colorful, detailed output with customizable prefixes and ANSI color formatting.

### Style 2: SimpleLogger

### Loading Animation
```python
log = Logger(style=2)
```

The `Loader` class can be used in two ways:
Provides a minimalist, clean output format with basic color coding.

#### Using a context manager:
### Style Comparison

```python
from time import sleep
# Style 1 (ColorLogger)
log1 = Logger(prefix="ColorLogger")
log1.success("Operation successful!")
# Output: [ColorLogger] [12:34:56] [Success] -> Operation successful!

# Style 2 (SimpleLogger)
log2 = Logger(style=2, prefix="SimpleLogger")
log2.success("Operation successful!")
# Output: 12:34:56 » SUCCESS ➔ Operation successful!
```

### Log File Saving

with Loader(desc="Loading with context manager..."):
for i in range(10):
sleep(0.25)
You can specify a log file path to save logs to a file for further review or debugging. The logger will automatically strip ANSI color codes from messages saved to the log file for readability. Log files are appended with each new logging session.

```python
log = Logger(log_file="logs/app.log")
log.success("This message will also be saved to app.log")
```

#### Using `start()` and `stop()` methods:
To view logs saved to the file, open the specified path and review the recorded entries, which include timestamped log messages for tracking system state over time.

## 🔄 Loading Animation

The Loader class now supports custom prefixes and can be used in two ways:

```python
loader = Loader(desc="Loading with object...", end="That was fast!", timeout=0.05).start()
for i in range(10):
sleep(0.25)
from logmagix import Loader
import time

# Method 1: Context Manager
with Loader(
prefix="MyApp",
desc="Processing...",
end="Completed!",
timeout=0.1
):
time.sleep(2) # Your task here

# Method 2: Manual Control
loader = Loader(
prefix="MyApp",
desc="Loading...",
end="Done!",
timeout=0.05
).start()
time.sleep(2) # Your task here
loader.stop()
```

### Custom Log and Loader Prefix
## Custom Log and Loader Prefix

Both the `Logger` and `Loader` classes allow for customizing the prefix shown before each message:

Expand Down Expand Up @@ -188,21 +224,46 @@ This will display the ASCII art version of "LogMagix" in the center of the termi
Here’s an example showing both logging, loader, and the new `Home` class functionality:

```python
from logmagix import Logger, Loader, Home
from logmagix import Logger, Home, Loader, LogLevel
import time
import uuid

log = Logger(prefix="custom/log/prefix")
start_time = time.time()
# Test ColorLogger (Style 1 - Default)
log1 = Logger(
prefix="ColorLogger",
github_repository="https://github.com/sexfrance/LogMagix",
level=LogLevel.DEBUG,
log_file="logs/color.log"
)

# Log messages
log.success("Everything is running smoothly!")
log.warning("Watch out, something might happen!")
log.failure("Critical error occurred!")
log.info("System is working properly")
log.debug(f"The system uuid is {uuid.getnode()}")
start_time = time.time()
log1.success("We are running style 1!")
log1.warning("Watch out, something might happen!")
log1.failure("Critical error occurred!")
log1.info("System is working properly")
log1.debug(f"The system uuid is {uuid.getnode()}")
log1.message("Dad", f"How are you? I'm gonna come soon!", start=start_time, end=time.time())
log1.question("How old are you? ")

# Test SimpleLogger (Style 2)
log2 = Logger(
style=2,
prefix="SimpleLogger",
level=LogLevel.INFO,
log_file="logs/simple.log"
)

# Use loader with custom prefix and context manager
start_time = time.time()
log2.success("We are running style 2 !")
log2.info("System is working properly")
log2.error("Critical error occurred!")
log2.warning("Watch out, something might happen!")
log2.message("System is working properly")
log2.debug(f"The system uuid is {uuid.getnode()}")
log2.question("How old are you? ")

# Test loader with custom prefix and context manager
print("\nTesting Loader:")
with Loader(prefix="custom/loader/prefix", desc="Processing data..."):
time.sleep(2) # Simulate task

Expand All @@ -211,17 +272,20 @@ loader = Loader(prefix="custom/loader/prefix", desc="Saving files...", end="Done
time.sleep(2) # Simulate task
loader.stop()


# Display home screen
home_screen = Home(
text="LogMagix",
align="center",
adinfo1="discord.cyberious.xyz",
adinfo2="v1.0",
credits="Developed by sexfrance"
adinfo1="Test Suite",
adinfo2="v1.0.0",
credits="Testing Framework",
clear=True
)

home_screen.display()

log.success("Processing completed!")
# Test critical error (commented out as it exits the program)
log1.critical("Critical error occurred!")
```

### Customization in `Home` Class
Expand All @@ -231,6 +295,10 @@ log.success("Processing completed!")
- **adinfo1** and **adinfo2**: Additional information displayed below the ASCII art.
- **credits**: Optional credits or user information.

### 📹 Preview

![Preview](https://i.imgur.com/fsgZuv1.png)

## ❗ Requirements

LogMagix requires:
Expand Down Expand Up @@ -263,4 +331,3 @@ LogMagix is developed and maintained by **sexfrance**.
<img alt="PyPI - Downloads" src="https://img.shields.io/pypi/dm/logmagix?style=for-the-badge&labelColor=black&color=f429ff&logo=IOTA">

</p>

23 changes: 15 additions & 8 deletions logmagix/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,6 @@ def __init__(self, prefix: str | None = "discord.cyberious.xyz", github_reposito
if log_file:
os.makedirs(os.path.dirname(log_file), exist_ok=True)
self._write_to_log(f"=== Logging started at {datetime.datetime.now()} ===\n")

if self.repo_url:
username = self._extract_github_username(self.repo_url)
if username:
self.info(f"Developed by {username} - {self.repo_url}")
else:
self.info(f"GitHub Repository: {self.repo_url}")

def _extract_github_username(self, url: str) -> str | None:
url = url.replace('https://', '').replace('http://', '').replace('www.', '')
Expand Down Expand Up @@ -82,6 +75,13 @@ def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.prefix = f"{self.PINK}[{self.MAGENTA}{self.prefix}{self.PINK}] " if self.prefix else f"{self.PINK}"

if self.repo_url:
username = self._extract_github_username(self.repo_url)
if username:
self.info(f"Developed by {username} - {self.repo_url}")
else:
self.info(f"GitHub Repository: {self.repo_url}")

def message3(self, level: str, message: str, start: int = None, end: int = None) -> str:
current_time = self.get_time()
return f"{self.prefix}[{self.BRIGHT_MAGENTA}{current_time}{self.PINK}] {self.PINK}[{self.CYAN}{level}{self.PINK}] -> {self.CYAN}{message}{Fore.RESET}"
Expand Down Expand Up @@ -164,6 +164,13 @@ def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.prefix = f"{Fore.BLACK}{self.get_time()} » {Fore.RESET}"

if self.repo_url:
username = self._extract_github_username(self.repo_url)
if username:
self.info(f"Developed by {username} - {self.repo_url}")
else:
self.info(f"GitHub Repository: {self.repo_url}")

def success(self, message: str, start: int = None, end: int = None, level: str = "SUCCESS") -> None:
if self._should_log(LogLevel.SUCCESS):
timer = f" (In {str(end - start)[:5]}s)" if start and end else ""
Expand All @@ -174,7 +181,7 @@ def success(self, message: str, start: int = None, end: int = None, level: str =
def error(self, message: str, start: int = None, end: int = None, level: str = "ERROR") -> None:
if self._should_log(LogLevel.FAILURE):
timer = f" (In {str(end - start)[:5]}s)" if start and end else ""
log_message = f"{self.prefix}{Fore.LIGHTRED_EX}{level} {Fore.BLACK}{Fore.RESET} {message}{timer}"
log_message = f"{self.prefix}{Fore.LIGHTRED_EX}{level} {Fore.BLACK} {Fore.RESET} {message}{timer}"
print(log_message)
self._write_to_log(log_message)

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

setup(
name="logmagix",
version="2.1.0",
version="2.1.0.1",
packages=find_packages(),
install_requires=["colorama", "pystyle"],
author="Sexfrance",
Expand Down
12 changes: 5 additions & 7 deletions test.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,13 @@

# Test ColorLogger (Style 1 - Default)
log1 = Logger(
prefix="ColorLogger",
github_repository="https://github.com/sexfrance/LogMagix",
level=LogLevel.DEBUG,
log_file="logs/color.log"
)
print("\nTesting ColorLogger (Style 1):")

start_time = time.time()
log1.success("Everything is running smoothly!")
log1.success("We are running style 1!")
log1.warning("Watch out, something might happen!")
log1.failure("Critical error occurred!")
log1.info("System is working properly")
Expand All @@ -23,13 +22,12 @@
log2 = Logger(
style=2,
prefix="SimpleLogger",
github_repository="https://github.com/sexfrance/LogMagix",
level=LogLevel.DEBUG,
level=LogLevel.INFO,
log_file="logs/simple.log"
)
print("\nTesting SimpleLogger (Style 2):")

start_time = time.time()
log2.success("Everything is running smoothly!")
log2.success("We are running style 2 !")
log2.info("System is working properly")
log2.error("Critical error occurred!")
log2.warning("Watch out, something might happen!")
Expand Down

0 comments on commit b0df6d2

Please sign in to comment.