xlog

    Native structured logging with levels and category-based filtering.

    log
    logging
    structured-logging
    Download zip
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    5 months ago
    Downloads
    63K

    #xlog

    tonyfettes/xlog is a native-only structured logger with top-level helpers, logger instances, categories, structured fields, stdout/file/multi outputs, and MOON_XLOG filtering.

    Logger calls are best-effort: output errors are ignored by Logger, while handlers can still report errors when called directly or wrapped.

    #Quick Start

    Use top-level helpers when passing a logger around would be noisy:

    @xlog.info("server started", category="app", fields={ "port": 8080 })
    @xlog.debug("query plan", category="app.db")

    Use a Logger when you want explicit category context or a specific output:

    let logger = @xlog.Logger(@xlog.Stdout(), category="app")
    let db = logger.child(category="db")

    logger.info("server started")
    db.debug("query plan")

    #Levels And Categories

    The default level is Info. Level order, from least to most verbose:

    Fatal Error Warn Info Debug Trace

    A record is emitted when its level is less than or equal to the effective level. Category overrides are hierarchical, so app.db.query falls back to app.db, then app, then the logger's level.

    Child loggers append category segments:

    let app = @xlog.Logger(@xlog.Stdout(), category="app")
    let db = app.child(category="db") // app.db

    Logger methods do not take per-call categories. Use child(category=...) for logger instances, and category="..." for top-level helpers.

    #Configuration

    Config::from_env() reads MOON_XLOG by default:

    MOON_XLOG=debug MOON_XLOG='warn,app.db=debug,app.db.query=trace'

    You can also build config directly:

    let config = @xlog.Config(level=@xlog.Warn)
    config.set_category_level("app.db", @xlog.Debug)

    let logger = @xlog.Logger(@xlog.Stdout(), category="app", config~)

    Invalid levels, invalid directives, and invalid categories raise ConfigError. The package global logger catches invalid MOON_XLOG and falls back to Info.

    #Outputs

    Stdout defaults to text output. Use Jsonl for one JSON object per line:

    @xlog.global().set_handler(@xlog.Stdout())
    @xlog.global().set_handler(@xlog.Stdout(format=@xlog.Jsonl))

    File opens an append-mode file and defaults to Jsonl:

    let file = @xlog.File("_build/app.log")
    @xlog.global().set_handler(file)
    @xlog.info("written to file", category="app")

    File is native-only and uses a small ISO C FILE * stub. The native handle closes automatically when the handler is no longer reachable; call close() only after removing it from long-lived loggers. It does not provide multi-process atomic logging guarantees.

    Multi fans out to several handlers:

    let file = @xlog.File("_build/app.log")
    let handlers : Array[&@xlog.Handler] = [@xlog.Stdout(), file]
    @xlog.global().set_handler(@xlog.Multi(handlers))

    Multi attempts every child handler. Direct Multi.handle(entry) calls can raise MultiError(Array[Error]); ordinary logger calls swallow that error.

    #Global Logger

    Top-level helpers use @xlog.global(), a process-wide root logger:

    let config = @xlog.Config::from_env() catch { _ => @xlog.Config() }

    @xlog.global().set_config(config)
    @xlog.global().set_level(@xlog.Debug)
    @xlog.info("top-level record", category="app")

    global() is a root logger, not a replaceable default logger. Configure it with set_handler, set_config, and set_level.

    #Example

    The examples/lorem package demonstrates category filtering:

    moon run examples/lorem MOON_XLOG=debug moon run examples/lorem MOON_XLOG='warn,lorem.db=trace,lorem.worker=debug,lorem.parser.lexer=trace' moon run examples/lorem

    Handler

    pub(open) trait Handler {
    fn handle(Self, Entry) -> Unit raise
    }

    A sink that receives structured log entries.

    Direct handler calls may raise errors. Logger methods catch and ignore those errors so logging failures do not interrupt application code.

    ConfigError

    pub(all) suberror ConfigError {
    InvalidCategory(String)
    InvalidDirective(String)
    InvalidLevel(String)
    }

    Errors raised when parsing or updating logger configuration.

    MultiError

    pub(all) suberror MultiError {
    MultiError(Array[Error])
    }

    Error raised by Multi when one or more child handlers fail.

    Config

    pub struct Config {
    // private fields
    }
    fn Config::Config(level? : Level) -> Config

    Logging configuration with a root level and category-specific overrides.

    Category overrides are hierarchical: app.db.query falls back to app.db, then app, then the logger's root level.

    Config::from_env

    fn Config::from_env(env? : String, level? : Level) -> Config raise ConfigError

    Read configuration from an environment variable.

    env defaults to MOON_XLOG. The value is a comma-separated list of directives: either a root level such as debug, or a category override such as app.db=trace.

    Config::set_category_level

    fn Config::set_category_level(self : Config, category : String, level : Level) -> Unit raise ConfigError

    Set a level override for a category.

    Category names must be non-empty dot-separated segments, with no leading dot, trailing dot, or empty segment.

    Entry

    pub struct Entry {
    level : Level
    category : String?
    timestamp :
    ZonedDateTime

    source : SourceLoc?
    message : String
    fields : Map[String, Json]
    }

    A structured log record passed to handlers.
    impl Show for Entry
    impl ToJson for Entry

    File

    pub struct File {
    // private fields
    }
    fn File::File(path : String, format? : Format) -> File raise
    IOError

    A handler that appends log entries to a file.

    File is native-only. It keeps the file open until close is called or the handler becomes unreachable.
    impl Handler for File

    File::close

    fn File::close(self : File) -> Unit

    Close the file handle.

    Calling close more than once is safe.

    Format

    pub(all) enum Format {
    Text
    Jsonl
    }

    Output format used by built-in handlers.

    Level

    pub(all) enum Level {
    Fatal
    Error
    Warn
    Info
    Debug
    Trace
    } derive(Compare, Eq)

    Log levels ordered from most severe to most verbose.

    A record is emitted when its level is less than or equal to the effective logger level.
    impl Show for Level

    Logger

    pub struct Logger {
    // private fields
    }
    fn Logger::Logger(handler : H, level? : Level, category? : String, config? : Config) -> Logger

    A structured logger that emits entries through a Handler.

    Logger calls are best-effort: errors raised by the handler are ignored.

    Logger::category

    fn Logger::category(self : Logger) -> String?

    Return this logger's category, if it has one.

    Logger::child

    fn Logger::child(self : Logger, category? : String, level? : Level) -> Logger

    Create a child logger with an optional appended category segment.

    Parent and child categories are joined with .. The child keeps the level it is created with, so later set_level calls on the parent do not affect existing children.

    Logger::debug

    #callsite(autofill(loc))
    fn Logger::debug(self : Logger, message : String, fields? : Map[String, Json], loc~ : SourceLoc) -> Unit

    Emit a Debug entry.

    Logger::error

    #callsite(autofill(loc))
    fn Logger::error(self : Logger, message : String, fields? : Map[String, Json], loc~ : SourceLoc) -> Unit

    Emit an Error entry.

    Logger::fatal

    #callsite(autofill(loc))
    fn Logger::fatal(self : Logger, message : String, fields? : Map[String, Json], loc~ : SourceLoc) -> Unit

    Emit a Fatal entry.

    Logger::info

    #callsite(autofill(loc))
    fn Logger::info(self : Logger, message : String, fields? : Map[String, Json], loc~ : SourceLoc) -> Unit

    Emit an Info entry.

    Logger::set_config

    fn Logger::set_config(self : Logger, config : Config) -> Unit

    Install a configuration object and reset the logger's root level from it.

    Logger::set_handler

    fn[H : Handler] Logger::set_handler(self : Logger, handler : H) -> Unit

    Replace the handler used by this logger.

    Logger::set_level

    fn Logger::set_level(self : Logger, level : Level) -> Unit

    Set the logger's root level.

    Category-specific overrides from an installed Config still take precedence for matching categories.

    Logger::trace

    #callsite(autofill(loc))
    fn Logger::trace(self : Logger, message : String, fields? : Map[String, Json], loc~ : SourceLoc) -> Unit

    Emit a Trace entry.

    Logger::warn

    #callsite(autofill(loc))
    fn Logger::warn(self : Logger, message : String, fields? : Map[String, Json], loc~ : SourceLoc) -> Unit

    Emit a Warn entry.

    Multi

    pub(all) struct Multi(Array[&Handler])

    A handler that fans out each entry to multiple child handlers.

    Every child handler is attempted. If any fail, MultiError is raised after all handlers have been called.
    impl Handler for Multi

    Stdout

    pub struct Stdout {
    // private fields
    }
    fn Stdout::Stdout(format? : Format) -> Stdout

    A handler that writes log entries to standard output.
    impl Handler for Stdout

    debug

    #callsite(autofill(loc))
    fn debug(message : String, fields? : Map[String, Json], category? : String, loc~ : SourceLoc) -> Unit

    Emit a Debug entry with the global logger.

    error

    #callsite(autofill(loc))
    fn error(message : String, fields? : Map[String, Json], category? : String, loc~ : SourceLoc) -> Unit

    Emit an Error entry with the global logger.

    fatal

    #callsite(autofill(loc))
    fn fatal(message : String, fields? : Map[String, Json], category? : String, loc~ : SourceLoc) -> Unit

    Emit a Fatal entry with the global logger.

    global

    fn global() -> Logger

    Return the process-wide root logger used by top-level logging helpers.

    The returned logger can be configured with set_handler, set_config, and set_level.

    info

    #callsite(autofill(loc))
    fn info(message : String, fields? : Map[String, Json], category? : String, loc~ : SourceLoc) -> Unit

    Emit an Info entry with the global logger.

    trace

    #callsite(autofill(loc))
    fn trace(message : String, fields? : Map[String, Json], category? : String, loc~ : SourceLoc) -> Unit

    Emit a Trace entry with the global logger.

    warn

    #callsite(autofill(loc))
    fn warn(message : String, fields? : Map[String, Json], category? : String, loc~ : SourceLoc) -> Unit

    Emit a Warn entry with the global logger.