Skip to content

Commit

Permalink
add missing files
Browse files Browse the repository at this point in the history
  • Loading branch information
thatstoasty committed Jul 31, 2024
1 parent 12aa5fa commit 52a3f08
Show file tree
Hide file tree
Showing 10 changed files with 79 additions and 122 deletions.
120 changes: 44 additions & 76 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,41 +1,22 @@
# stump

![Mojo 24.3](https://img.shields.io/badge/Mojo%F0%9F%94%A5-24.3-purple)
![Mojo Nightly 2024.7.3108](https://img.shields.io/badge/Mojo%F0%9F%94%A5-2024.7.3108-purple)

WIP Logger! Inspired by charmbracelet's log package and the Python structlog package.

**THIS LIBRARY IS BROKEN FOR MOJO 24.4+ UNTIL Dict.popitem() is fixed: https://github.com/modularml/mojo/issues/2756**
WIP Logger! Inspired by charmbracelet's `log` package and the Python `structlog` package.

There are some things I'm ironing out around terminal color profile querying at compilation time. At the moment, the default styles assume a `TRUE_COLOR` enabled color profile. So, if your terminal only supports `ANSI` or `ANSI256`, try setting custom styles like in the `custom.mojo` example, or update the default profile in `stump/style.mojo` from `TRUE_COLOR` to `ANSI` or `ANSI256`.

See the examples directory for examples on setting up custom processors, styling, message only/json/logfmt logging, and logging with the styling turned off!

![Example logs](https://github.com/thatstoasty/stump/blob/main/logger.png)

Minimal default logger example:

```py
from stump import get_logger


alias logger = get_logger()


fn main():
logger.info("Information is good.")
logger.warn("Warnings can be good too.")
logger.error("An error!")
logger.debug("Debugging...")
logger.fatal("uh oh...")
```

There's support for arbitrary arg pairs and kwargs to be merged into the log statement!

Example:

```mojo
from stump import get_logger
alias logger = get_logger()
var logger = get_logger()
fn main():
Expand All @@ -46,116 +27,104 @@ fn main():
logger.debug("Debugging...")
```

Output (no color included)

```txt
2024-04-03 14:53:56 INFO Information is good. key=value
2024-04-03 14:53:56 WARN Warnings can be good too. no_value=
2024-04-03 14:53:56 ERROR An error! erroring=True
2024-04-03 14:53:56 FATAL uh oh... number=4 mojo=🔥
```
![Example](https://github.com/thatstoasty/stump/blob/nightly/demos/tapes/default.gif)

Minimal JSON logger example:
JSON logger example:

```mojo
from stump import (
DEBUG,
JSON_FORMAT,
BoundLogger,
PrintLogger
)
from stump import DEBUG, json_formatter, BoundLogger, PrintLogger
# The loggers are compiled at build time, so we can reuse it.
alias LOG_LEVEL = DEBUG
alias logger = BoundLogger(PrintLogger(LOG_LEVEL), formatter=JSON_FORMAT)
var logger = BoundLogger(PrintLogger(DEBUG), formatter=json_formatter, apply_styles=False)
fn main():
logger.info("Information is good.")
logger.info("Information is good.", "arbitrary", "pairs", key="value")
logger.warn("Warnings can be good too.")
logger.error("An error!")
logger.debug("Debugging...")
logger.fatal("uh oh...")
```

![JSON Example](https://github.com/thatstoasty/stump/blob/nightly/demos/tapes/json.gif)

Customized style and processor logger example:

```mojo
from stump import (
DEBUG,
DEFAULT_FORMAT,
Processor,
Context,
Styles,
Sections,
BoundLogger,
PrintLogger,
STDLogger,
add_log_level,
add_timestamp,
add_timestamp_with_format,
)
from external.mist import TerminalStyle, Profile, TRUE_COLOR
import external.mist
# Define a custom processor to add a name to the log output.
fn add_my_name(context: Context) -> Context:
var new_context = Context(context)
fn add_my_name(context: Context, level: String) -> Context:
var new_context = context
new_context["name"] = "Mikhail"
return new_context
# Define custom processors to add extra information to the log output.
fn my_processors() -> List[Processor]:
return List[Processor](
add_log_level, add_timestamp_with_format["YYYY"](), add_my_name
)
# Define custom styles to format and colorize the log output.
fn my_styles() -> Styles:
# Log level styles, by default just set colors
var levels = Sections()
levels["FATAL"] = TerminalStyle.new().background("#d4317d")
levels["ERROR"] = TerminalStyle.new().background("#d48244")
levels["INFO"] = TerminalStyle.new().background("#13ed84")
levels["WARN"] = TerminalStyle.new().background("#decf2f")
levels["DEBUG"] = TerminalStyle.new().background("#bd37db")
var base_style = mist.Style()
var faint_style = mist.Style().faint()
var levels = List[mist.Style](
base_style.background(0xD4317D),
base_style.background(0xD48244),
base_style.background(0x13ED84),
base_style.background(0xDECF2F),
base_style.background(0xBD37DB),
)
var keys = Sections()
keys["name"] = (
TerminalStyle.new().foreground("#c9a0dc").underline()
)
keys["name"] = mist.Style().foreground(0xC9A0DC).underline()
var values = Sections()
values["name"] = TerminalStyle.new().foreground("#d48244").bold()
values["name"] = mist.Style().foreground(0xD48244).bold()
return Styles(
timestamp=base_style,
message=base_style,
key=faint_style,
value=base_style,
separator=faint_style,
levels=levels,
key=TerminalStyle.new().faint(),
separator=TerminalStyle.new().faint(),
keys=keys,
values=values,
)
# The loggers are compiled at build time, so we can reuse it.
alias LOG_LEVEL = DEBUG
# Build a bound logger with custom processors and styling
alias logger = BoundLogger(
PrintLogger(LOG_LEVEL), formatter=DEFAULT_FORMAT, processors=my_processors, styles=my_styles
var logger = BoundLogger(
STDLogger(level=DEBUG),
processors=List[Processor](add_log_level, add_timestamp, add_my_name),
styles=my_styles(),
)
fn main():
logger.info("Information is good.")
logger.warn("Warnings can be good too.")
logger.error("An error!")
logger.error("An error!", erroring=True)
logger.debug("Debugging...")
logger.fatal("uh oh...")
```

![Custom Example](https://github.com/thatstoasty/stump/blob/nightly/demos/tapes/custom.gif)

Importing the logger into other files works!

```mojo
Expand All @@ -171,12 +140,11 @@ fn main():
### Features

- Add more processor functions.
- Add support for logging to files via `Logger` struct that uses a writer that implement `io.Writer`.
- Add global logger support once we have file scope support.
- Make formatter flexible and composable. Right now it's only a few predefined formats.
- Exiting on fatal log calls.
- logf functions to specify a specific format for that log message.
- Speed improvements once https://github.com/modularml/mojo/issues/2779 is resolved and enables `mist` to compile text styling at comp time instead of on each and every log call. Providing a STDOUT writer logger instead of print logger will speed it up measurably as well.
- Simple naive JSON formatter to be improved to handle escaped chars, brackets, etc correctly.

### Bugs

- There are probably tons of edge cases on JSON parsing that I haven't thought of yet. Please don't be surprised if the JSON formatter breaks on you.
Binary file added demos/tapes/custom.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 11 additions & 0 deletions demos/tapes/custom.tape
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Output demos/tapes/custom.gif

Set Shell "zsh"
Set FontSize 23
Set Width 1200
Set Height 400
Set WindowBar Colorful


Type "mojo run examples/custom.mojo" Sleep 500ms Enter
Sleep 5s
Binary file added demos/tapes/default.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 11 additions & 0 deletions demos/tapes/default.tape
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Output demos/tapes/default.gif

Set Shell "zsh"
Set FontSize 23
Set Width 1200
Set Height 400
Set WindowBar Colorful


Type "mojo run examples/default.mojo" Sleep 500ms Enter
Sleep 5s
Binary file added demos/tapes/json.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 11 additions & 0 deletions demos/tapes/json.tape
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Output demos/tapes/json.gif

Set Shell "zsh"
Set FontSize 23
Set Width 1200
Set Height 400
Set WindowBar Colorful


Type "mojo run examples/json.mojo" Sleep 500ms Enter
Sleep 5s
1 change: 1 addition & 0 deletions examples/data/log.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
2024-07-31T13:15:13.950927-05:00 INFO Testing print...
2 changes: 1 addition & 1 deletion stump/processor.mojo
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import time
from external.morrow import Morrow


alias Processor = fn (context: Context, level: String) -> Context
"""Functions to modify the context before logging a message."""


# Built in processor functions to modify the context before logging a message.
Expand Down
45 changes: 0 additions & 45 deletions test.mojo

This file was deleted.

0 comments on commit 52a3f08

Please sign in to comment.