About
Logging facilities in the Mys programming language.
A basic example
Create a logger and call it’s warning and error methods to print messages to standard output.
from log import get_logger
func main():
logger = get_logger(__name__)
logger.WARNING(f"Is 1 + 1 = {1 + 2} really correct?")
logger.ERROR(f"Something is wrong!")
The output:
❯ mys run
✔ Reading package configuration (0 seconds)
✔ Building (1.43 seconds)
basic.main WARNING Is 1 + 1 = 3 really correct?
basic.main ERROR Something is wrong!
Setting logging level example
Set a logger’s level by just knowing the logger name.
from log import get_logger
from log import LOGGERS
from log import Level
func set_log_level_to_debug(name: string):
logger = LOGGERS.get(name, None)
if logger is None:
print(f"Logger '{name}' does not exist.")
else:
logger.level = Level.Debug
func main():
logger = get_logger("foo")
logger.DEBUG("First try.")
set_log_level_to_debug("bar")
logger.DEBUG("Second try.")
set_log_level_to_debug("foo")
logger.DEBUG("Third try.")
The output:
❯ mys run
✔ Reading package configuration (0 seconds)
✔ Building (2.13 seconds)
Logger 'bar' does not exist.
Setting log level to debug for logger 'foo'.
foo DEBUG Third try.
API
enum Level(i64):
Logging levels.
Debug
Info
Warning
Error
trait Handler:
Log entry output handler trait.
func write(self, message: string):
Write given message to desired location.
trait Formatter:
Log entry formatter trait.
func format(self, logger_name: string, level: Level, message: string) -> string:
Returns a formatted log message.
class Logger:
A logger.
This class is normally not instantiated directly by the
user. Instead, use `get_logger()` to create instances.
level: Level
func __init__(self, name: string, level: Level = Level.Warning):
Initialize the logger object with given name and level.
func is_enabled_for(self, level: Level) -> bool:
Returns True is given level is enabled, otherwise False.
macro ERROR(self, message: string):
Log given error message.
macro WARNING(self, message: string):
Log given warning message.
macro INFO(self, message: string):
Log given info message.
macro DEBUG(self, message: string):
Log given debug message.
class StdoutHandler(Handler):
Writes log messages to standard output.
func write(self, message: string):
Writes given log message to standard output.
class DefaultFormatter(Formatter):
Default log entry formatter.
func format(self, logger_name: string, level: Level, message: string) -> string:
Formats a log message on the format <logger name> <level> <message>
and returns it.
func get_logger(name: string) -> Logger:
Get the logger with given name. Creates a new logger if it does not
already exist. The global variable LOGGERS contains all loggers
created by this function.
LOGGERS: {string: Logger}
A dictionary of all known loggers.
HANDLER: Handler
The handler which all log messages are written to.
FORMATTER: Formatter
The formatter that formats all messages.