moonbit-log

结构化日志库 - MoonBit CCF开源创新大赛参赛作品

logging
structured-log
audit
stopwatch
moonbit
ccf
moon add leppard/moonbit-log@0.1.0
Download zip
Author
Version
0.1.0
License
Apache-2.0
Last updated
last month
Downloads
18
README

#moonbit-log

结构化日志库 — CCF OSC2026 MoonBit 赛道参赛作品

License MoonBit

#Project Status

  • CCF OSC2026 MoonBit 赛道参赛项目
  • moon check --deny-warn 通过
  • moon test 163/163 通过
  • 代码规模: 4,100+ 行 MoonBit 源码
  • 零外部依赖,仅使用 MoonBit 标准库

#Features

#日志级别 (6)

Debug, Info, Warn, Error, Fatal, Audit

#处理器 (21)

类型处理器说明
输出ConsoleHandler控制台输出(支持 stdout/stderr 切换)
输出FileHandler缓冲批量输出,自动 flush
输出JsonHandlerJSON 格式输出
输出TextHandler带前缀的文本输出
输出RotatingFileHandler按大小/文件数自动轮转
存储MemoryHandler内存存储,支持检索/统计
存储AuditHandler审计日志,支持过滤/搜索/导出
存储RingBufferHandler环形缓冲区,支持 drain
控制SamplingHandler采样(1/N 比例)
控制DedupHandler去重(基于消息哈希)
控制RateLimitedHandler速率限制(时间窗口)
控制ThrottledHandler节流(最小间隔)
控制LevelFilteredHandler级别过滤
条件ConditionHandler条件谓词过滤
统计CountingHandler按级别计数统计
空操作NullHandler丢弃所有日志
组合MultiHandler多处理器路由分发
函数式HandlerFn闭包包装器
异步AsyncLogger批量队列异步日志
转换EntryTransformer日志条目转换器
异步BatchingLogger超时+批量双触发 flush

#格式器 (14)

text, compact, json, audit(分隔符), logfmt, xml, pretty(ANSI彩色), kv(key=value), banner(横幅), csv, pattern(模式), stats(统计), multi_line(缩进), custom(自定义)

#性能工具

  • Stopwatch: 微秒/毫秒/秒计时
  • Benchmark: 重复执行基准测试,自动计算均值/标准差/吞吐量
  • ThroughputMeter: 滑动窗口吞吐量测量

#配置系统

  • LogConfig + Builder 模式 + 工厂方法
  • 代码/JSON 双模式配置
  • 按名称选择 handler(format)/output 组合

#全局 Logger

g_debug / g_info / g_warn / g_error / g_fatal / g_log / g_log_with init_default_console() / init_default_json()

#Build & Test

# 编译检查(零警告) moon check --target all --deny-warn # 运行全部 163 个测试 moon test --target all # 格式化代码 moon fmt # 构建 WASM-GC moon build --target wasm-gc --release # 构建 JS moon build --target js --release

#Quick Start

moon.pkg 中添加依赖:

import { "leppard/moonbit-log" @log }

moon.mod 中添加:

[deps] leppard/moonbit-log = { version = "1.0.0" }

#基本使用

fn main {
@log.init_default_console()
@log.g_info("Hello, moonbit-log!")
@log.g_info("User login", [("user_id", "42"), ("ip", "10.0.0.1")])
}

#JSON 日志

@log.init_default_json()
@log.g_info("Order created", [
("order_id", "ORD-001"),
("amount", "299.00"),
("currency", "CNY")
])

#审计日志

let fmt = @log.audit_formatter("|")
let audit = @log.AuditHandler::new(@log.Level::Info, fmt, 100)
let logger = @log.Logger::new()
logger.add_handler(@log.make_handler(fn(e) { audit.log(e) }, fn() {}, fn() {}))
logger.log_with(@log.Level::Info, "数据导出", [("user", "admin"), ("records", "1000")])
println(audit.entries().length())

#文件/缓冲输出

let handler = @log.FileHandler::new(
@log.Level::Info,
@log.json_formatter(),
100
)
let logger = @log.Logger::new()
logger.add_handler(@log.make_handler(fn(e) { handler.log(e) }, fn() { handler.flush() }, fn() { handler.close() }))
logger.info("写入缓冲")

#文件轮转

let handler = @log.RotatingFileHandler::new(
@log.Level::Info,
@log.text_formatter(),
10,
5
)
let logger = @log.Logger::new()
logger.add_handler(@log.make_handler(fn(e) { handler.log(e) }, fn() { handler.flush() }, fn() { handler.close() }))
// 超过 10 行自动轮转,保留 5 个历史文件

#异步批处理

let handler = @log.ConsoleHandler::new(@log.Level::Debug, @log.compact_formatter())
let batch = @log.AsyncLogger::new(
@log.make_handler(fn(e) { handler.log(e) }, fn() { handler.flush() }, fn() { handler.close() }),
64
)
batch.log(@log.LogEntryBuilder::new(@log.Level::Info, "异步消息").build())
batch.flush()

#性能基准

let r = @log.benchmark("计算测试", 1000, fn() {
let mut x = 0
x = x + 1
@log.ignore(x)
})
println(@log.benchmark_report(r))

#配置系统

@log.configure(
level: @log.Level::Debug,
format: "compact",
output: "console"
)
@log.g_debug("配置已生效")

#API Reference

#Logger

方法签名说明
new()Logger创建 Logger
add_handler(HandlerFn)Unit添加处理器
debug/info/warn/error/fatal(msg, fields?)Unit按级别记录
log_with(Level, msg, fields?)Unit指定级别记录
set_level(Level)Unit设置最低级别

#Handler 通用接口

每个 Handler 实现三个方法:
  • log(self, LogEntry) -> Unit — 记录日志条目
  • flush(self) -> Unit — 刷新缓冲
  • close(self) -> Unit — 关闭并释放资源

#Stopwatch

方法返回说明
new()Stopwatch创建并启动计时
elapsed_ms()Int64已过毫秒数
elapsed_us()Int64已过微秒数
elapsed_s()Double已过秒数
lap(msg)Int64记录分段并返回耗时(ms)
reset()Unit重置计时
laps()Array[(String, Int64)]返回全部分段记录
report()String生成可读报告

#LogEntry

字段类型说明
levelLevel日志级别
messageString日志消息
fieldsArray[(String, String)]键值对字段
timestampInt64Unix 时间戳(ms)
moduleString模块名
fileString源文件名
lineInt行号

#Project Structure

moonbit-log/ ├── logger.mbt # Logger 核心 ├── log_entry.mbt # LogEntry / LogEntryBuilder ├── level.mbt # Level 枚举 / enabled / from_string ├── handler.mbt # HandlerFn 函数式 Handler ├── formatter.mbt # text / compact / json / audit / custom ├── console_handler.mbt # ConsoleHandler ├── file_handler.mbt # FileHandler (缓冲批量输出) ├── json_handler.mbt # JsonHandler ├── text_handler.mbt # TextHandler (带前缀) ├── memory_handler.mbt # MemoryHandler (内存存储+检索) ├── audit_handler.mbt # AuditHandler (审计日志) ├── multi_handler.mbt # MultiHandler (多路分发) ├── advanced_handlers.mbt # RotatingFile / LevelFilter / Sampling / Dedup / RingBuffer / RateLimited ├── extra_handler_utils.mbt # Null / Condition / Throttled / Counting / kv / banner / csv ├── extra_formatters.mbt # logfmt / xml / pretty(ANSI) ├── template_formatter.mbt # pattern / stats / multi_line ├── async_logger.mbt # AsyncLogger / BatchingLogger / EntryTransformer ├── config.mbt # LogConfig + 工厂方法 + JSON 配置 ├── global_logger.mbt # 全局 Logger 单例 ├── stopwatch.mbt # Stopwatch / Benchmark / ThroughputMeter ├── entry_utils.mbt # 条目工具函数 ├── log_test.mbt # 基础测试 (~50 用例) ├── extended_test.mbt # 扩展测试 (~50 用例) ├── edge_case_test.mbt # 边界情况测试 (~63 用例) ├── cmd/example/main.mbt # CLI 示例 ├── moon.mod # 模块元数据 └── moon.pkg # 包配置

#竞品对比

维度xlogMoonLogTraceBitLoggermoonbit-log
发布日期2025202520252026
构建状态失败成功成功成功
零依赖-+-+
测试数???163
审计日志---+
文件轮转---+
去重/限速---+
性能基准---+
Span 追踪-+--
代码规模~500~3k~1.5k4.1k

#License

Apache-2.0

#参赛信息

  • 赛事: CCF 开源创新大赛 (OSC 2026) · MoonBit 赛道
  • 命名空间: leppard/moonbit-log
  • 仓库: https://gitlink.org.cn/leppard/moonbit-log
  • 代码行数: 4,127
  • 源文件: 24
  • 测试用例: 163

#
AsyncLogger

pub(all) struct AsyncLogger {
inner : HandlerFn
queue : Array[LogEntry]
batch_size : Int
dropped_count : Int
}

Async logger that batches log entries and flushes them in bulk to the inner handler.

#
AsyncLogger::close

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

Flushes the queue and closes the inner handler.

#
AsyncLogger::dropped_count

fn AsyncLogger::dropped_count(self : AsyncLogger) -> Int

Returns the count of dropped entries (entries that were skipped).

#
AsyncLogger::flush

fn AsyncLogger::flush(self : AsyncLogger) -> Unit

Flushes all queued entries to the inner handler.

#
AsyncLogger::log

fn AsyncLogger::log(self : AsyncLogger, entry : LogEntry) -> Unit

Queues an entry; automatically flushes when the queue reaches batch size.

#
AsyncLogger::new

fn AsyncLogger::new(inner : HandlerFn, batch_size : Int) -> AsyncLogger

Creates an AsyncLogger with the given inner handler and batch size.

#
AsyncLogger::queue_size

fn AsyncLogger::queue_size(self : AsyncLogger) -> Int

Returns the current number of queued entries.

#
AsyncLogger::set_batch_size

fn AsyncLogger::set_batch_size(self : AsyncLogger, size : Int) -> Unit

Sets the batch size threshold for automatic flushing.

#
AuditHandler

pub(all) struct AuditHandler {
level : Level
fmt : (LogEntry) -> String
entries : Array[LogEntry]
max_entries : Int
}

Audit handler that stores entries and auto-flushes when the buffer is full.

#
AuditHandler::close

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

Flushes buffered entries and closes the handler.

#
AuditHandler::entries

fn AuditHandler::entries(self : AuditHandler) -> Array[LogEntry]

Returns all buffered entries.

#
AuditHandler::filter_by_level

fn AuditHandler::filter_by_level(self : AuditHandler, target : Level) -> Array[LogEntry]

Filters stored entries to those matching the given log level.

#
AuditHandler::flush

fn AuditHandler::flush(self : AuditHandler) -> Unit

Flushes all buffered entries to stdout and clears the buffer.

#
AuditHandler::log

fn AuditHandler::log(self : AuditHandler, entry : LogEntry) -> Unit

Stores an entry and auto-flushes to stdout when the buffer reaches max_entries.

#
AuditHandler::new

fn AuditHandler::new(level : Level, fmt : (LogEntry) -> String, max_entries : Int) -> AuditHandler

Creates a new AuditHandler with the given level, formatter, and max buffer size.

#
AuditHandler::search_by_message

fn AuditHandler::search_by_message(self : AuditHandler, keyword : String) -> Array[LogEntry]

Searches stored entries whose message contains the given keyword.

#
AuditHandler::search_by_module

fn AuditHandler::search_by_module(self : AuditHandler, mod_name : String) -> Array[LogEntry]

Searches stored entries by module name.

#
BatchingLogger

pub(all) struct BatchingLogger {
inner : HandlerFn
entries : Array[LogEntry]
batch_size : Int
flush_interval : Int64
last_flush : Int64
}

Batching logger that flushes entries based on batch size or time interval.

#
BatchingLogger::close

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

Flushes the queue and closes the inner handler.

#
BatchingLogger::flush

fn BatchingLogger::flush(self : BatchingLogger) -> Unit

Flushes all queued entries to the inner handler and resets the flush timer.

#
BatchingLogger::log

fn BatchingLogger::log(self : BatchingLogger, entry : LogEntry) -> Unit

Queues an entry; flushes automatically when batch size is reached.

#
BatchingLogger::new

fn BatchingLogger::new(inner : HandlerFn, batch_size : Int, flush_interval_us : Int64) -> BatchingLogger

Creates a BatchingLogger with the given handler, batch size, and flush interval in microseconds.

#
BatchingLogger::queue_size

fn BatchingLogger::queue_size(self : BatchingLogger) -> Int

Returns the current number of queued entries.

#
BenchmarkResult

pub(all) struct BenchmarkResult {
name : String
iterations : Int
total_time_us : Double
min_time_us : Double
max_time_us : Double
}

Result of a benchmark run, containing timing statistics.

#
BenchmarkResult::avg_time_us

fn BenchmarkResult::avg_time_us(self : BenchmarkResult) -> Double

Returns the average time per iteration in microseconds.

#
BenchmarkResult::iterations

fn BenchmarkResult::iterations(self : BenchmarkResult) -> Int

Returns the number of iterations executed.

#
BenchmarkResult::max_time_us

fn BenchmarkResult::max_time_us(self : BenchmarkResult) -> Double

Returns the maximum single-iteration time in microseconds.

#
BenchmarkResult::min_time_us

fn BenchmarkResult::min_time_us(self : BenchmarkResult) -> Double

Returns the minimum single-iteration time in microseconds.

#
BenchmarkResult::name

fn BenchmarkResult::name(self : BenchmarkResult) -> String

Returns the benchmark name.

#
BenchmarkResult::total_time_us

fn BenchmarkResult::total_time_us(self : BenchmarkResult) -> Double

Returns the total time across all iterations in microseconds.

#
ConditionHandler

pub(all) struct ConditionHandler {
inner : HandlerFn
condition : (LogEntry) -> Bool
}

Handler that only logs when a predicate condition is met.

#
ConditionHandler::close

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

Closes the inner handler.

#
ConditionHandler::flush

fn ConditionHandler::flush(self : ConditionHandler) -> Unit

Flushes the inner handler.

#
ConditionHandler::log

fn ConditionHandler::log(self : ConditionHandler, entry : LogEntry) -> Unit

Logs the entry only if the condition predicate returns true.

#
ConditionHandler::new

fn ConditionHandler::new(inner : HandlerFn, condition : (LogEntry) -> Bool) -> ConditionHandler

Creates a ConditionHandler that only passes entries matching the predicate.

#
ConsoleHandler

pub(all) struct ConsoleHandler {
level : Level
fmt : (LogEntry) -> String
use_stderr : Bool
}

Console handler that prints formatted log output to stdout.

#
ConsoleHandler::close

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

Closes the handler and releases resources. No-op for console handler.

#
ConsoleHandler::flush

fn ConsoleHandler::flush(self : ConsoleHandler) -> Unit

Flushes buffered output. No-op for console handler.

#
ConsoleHandler::log

fn ConsoleHandler::log(self : ConsoleHandler, entry : LogEntry) -> Unit

Logs an entry if its level meets the configured threshold.

#
ConsoleHandler::new

fn ConsoleHandler::new(level : Level, fmt : (LogEntry) -> String) -> ConsoleHandler

Creates a new ConsoleHandler with the given minimum level and formatter.

#
ConsoleHandler::with_stderr

fn ConsoleHandler::with_stderr(self : ConsoleHandler, v : Bool) -> ConsoleHandler

Sets whether output goes to stderr. Returns a new handler.

#
CountingHandler

pub(all) struct CountingHandler {
inner : HandlerFn
debug_count : Int
info_count : Int
warn_count : Int
error_count : Int
fatal_count : Int
}

Handler that counts entries by level, useful for monitoring.

#
CountingHandler::close

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

Closes the inner handler.

#
CountingHandler::debug_count

fn CountingHandler::debug_count(self : CountingHandler) -> Int

Returns the count of debug-level entries.

#
CountingHandler::error_count

fn CountingHandler::error_count(self : CountingHandler) -> Int

Returns the count of error-level entries.

#
CountingHandler::fatal_count

fn CountingHandler::fatal_count(self : CountingHandler) -> Int

Returns the count of fatal-level entries.

#
CountingHandler::flush

fn CountingHandler::flush(self : CountingHandler) -> Unit

Flushes the inner handler.

#
CountingHandler::info_count

fn CountingHandler::info_count(self : CountingHandler) -> Int

Returns the count of info-level entries.

#
CountingHandler::log

fn CountingHandler::log(self : CountingHandler, entry : LogEntry) -> Unit

Logs the entry and increments the level counter.

#
CountingHandler::new

Creates a CountingHandler that tracks log counts per level.

#
CountingHandler::reset

fn CountingHandler::reset(self : CountingHandler) -> Unit

Resets all level counters to zero.

#
CountingHandler::total_count

fn CountingHandler::total_count(self : CountingHandler) -> Int

Returns the total count across all levels.

#
CountingHandler::warn_count

fn CountingHandler::warn_count(self : CountingHandler) -> Int

Returns the count of warn-level entries.

#
DedupHandler

pub(all) struct DedupHandler {
inner : HandlerFn
last_message : String
repeat_count : Int
}

Handler that suppresses consecutive duplicate log messages.

#
DedupHandler::close

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

Flushes pending repeats and closes the inner handler.

#
DedupHandler::flush

fn DedupHandler::flush(self : DedupHandler) -> Unit

Flushes any pending repeat summary and delegates to the inner handler.

#
DedupHandler::log

fn DedupHandler::log(self : DedupHandler, entry : LogEntry) -> Unit

Logs the entry; if it repeats the previous message, increments a counter instead.

#
DedupHandler::new

fn DedupHandler::new(inner : HandlerFn) -> DedupHandler

Creates a DedupHandler that deduplicates repeated log messages.

#
EntryTransformer

pub(all) struct EntryTransformer {
inner : HandlerFn
transform : (LogEntry) -> LogEntry
}

Handler that transforms each log entry before forwarding to the inner handler.

#
EntryTransformer::close

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

Delegates close to the inner handler.

#
EntryTransformer::flush

fn EntryTransformer::flush(self : EntryTransformer) -> Unit

Delegates flush to the inner handler.

#
EntryTransformer::log

fn EntryTransformer::log(self : EntryTransformer, entry : LogEntry) -> Unit

Applies the transform function to the entry, then forwards it to the inner handler.

#
EntryTransformer::new

fn EntryTransformer::new(inner : HandlerFn, transform : (LogEntry) -> LogEntry) -> EntryTransformer

Creates an EntryTransformer with the given inner handler and transform function.

#
FileHandler

pub(all) struct FileHandler {
level : Level
fmt : (LogEntry) -> String
lines : Array[String]
capacity : Int
}

File handler that buffers log entries and flushes them to a debug output.

#
FileHandler::close

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

Flushes buffered output and closes the handler.

#
FileHandler::flush

fn FileHandler::flush(self : FileHandler) -> Unit

Flushes buffered lines to the debug output and clears the buffer.

#
FileHandler::lines

fn FileHandler::lines(self : FileHandler) -> Array[String]

Returns the buffered log lines.

#
FileHandler::log

fn FileHandler::log(self : FileHandler, entry : LogEntry) -> Unit

Logs an entry into the buffer and auto-flushes when capacity is reached.

#
FileHandler::new

fn FileHandler::new(level : Level, fmt : (LogEntry) -> String, capacity : Int) -> FileHandler

Creates a new FileHandler with the given level, formatter, and buffer capacity.

#
FileHandler::output_path

fn FileHandler::output_path() -> String

Returns the default output path for file handler logs.

#
HandlerFn

pub(all) struct HandlerFn {
log_fn : (LogEntry) -> Unit
flush_fn : () -> Unit
close_fn : () -> Unit
}

Function-based log handler dispatching to user-supplied callbacks.

#
HandlerFn::close

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

Closes the underlying handler callback.

#
HandlerFn::flush

fn HandlerFn::flush(self : HandlerFn) -> Unit

Flushes the underlying handler callback.

#
HandlerFn::log

fn HandlerFn::log(self : HandlerFn, entry : LogEntry) -> Unit

Dispatches a log entry to the underlying log callback.

#
JsonHandler

pub(all) struct JsonHandler {
level : Level
fmt : (LogEntry) -> String
}

JSON handler that outputs log entries as JSON-formatted strings.

#
JsonHandler::close

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

Closes the handler and releases resources. No-op for JSON handler.

#
JsonHandler::flush

fn JsonHandler::flush(self : JsonHandler) -> Unit

Flushes buffered output. No-op for JSON handler.

#
JsonHandler::log

fn JsonHandler::log(self : JsonHandler, entry : LogEntry) -> Unit

Logs an entry in JSON format if its level meets the threshold.

#
JsonHandler::new

fn JsonHandler::new(level : Level, fmt : (LogEntry) -> String) -> JsonHandler

Creates a new JsonHandler with the given minimum level and formatter.

#
Level

pub(all) enum Level {
Debug
Info
Warn
Error
Fatal
}

Log level enumeration indicating severity.
impl Eq for Level
impl Show for Level

#
Level::all

fn Level::all() -> Array[Level]

Returns all available log levels in ascending severity order.

#
Level::enabled

fn Level::enabled(self : Level, threshold : Level) -> Bool

Returns true if this level is at or above the given threshold.

#
Level::from_string

fn Level::from_string(s : String) -> Level

Parses a string into a Level. Falls back to Debug on unknown input.

#
Level::max

fn Level::max(a : Level, b : Level) -> Level

Returns the more severe of two levels.

#
Level::min

fn Level::min(a : Level, b : Level) -> Level

Returns the less severe of two levels.

#
Level::to_int

fn Level::to_int(self : Level) -> Int

Converts the level to its integer representation (0-4).

#
Level::to_string

fn Level::to_string(self : Level) -> String

Converts the level to its uppercase string representation.

#
LevelFilteredHandler

pub(all) struct LevelFilteredHandler {
inner : HandlerFn
min_level : Level
max_level : Level
}

Handler that filters log entries by a minimum and maximum level range.

#
LevelFilteredHandler::close

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

Delegates close to the inner handler.

#
LevelFilteredHandler::flush

fn LevelFilteredHandler::flush(self : LevelFilteredHandler) -> Unit

Delegates flush to the inner handler.

#
LevelFilteredHandler::log

fn LevelFilteredHandler::log(self : LevelFilteredHandler, entry : LogEntry) -> Unit

Forwards the entry to the inner handler only if its level falls within [min_level, max_level].

#
LevelFilteredHandler::new

fn LevelFilteredHandler::new(inner : HandlerFn, min_level : Level, max_level : Level) -> LevelFilteredHandler

Creates a LevelFilteredHandler with the given inner handler and level bounds.

#
LogConfig

pub(all) struct LogConfig {
level : Level
format_type : String
output_type : String
batch_size : Int
max_files : Int
max_lines : Int
ansi_color : Bool
audit_separator : String
}

Configuration struct for building loggers with preset options.

#
LogConfig::build_async

fn LogConfig::build_async(self : LogConfig) -> Logger

Builds an async Logger that batches log entries before writing.

#
LogConfig::build_logger

fn LogConfig::build_logger(self : LogConfig) -> Logger

Builds a synchronous Logger from this configuration.

#
LogConfig::build_multi

fn LogConfig::build_multi(self : LogConfig) -> MultiHandler

Builds a MultiHandler from this configuration, allowing multiple outputs.

#
LogConfig::default

fn LogConfig::default() -> LogConfig

Returns a LogConfig with default values (Debug level, text format, console output).

#
LogConfig::describe

fn LogConfig::describe(self : LogConfig) -> String

Returns a human-readable description of this configuration.

#
LogConfig::with_batch

fn LogConfig::with_batch(self : LogConfig, size : Int) -> LogConfig

Returns a copy with the batch size replaced.

#
LogConfig::with_color

fn LogConfig::with_color(self : LogConfig, color : Bool) -> LogConfig

Returns a copy with the ANSI color flag replaced.

#
LogConfig::with_format

fn LogConfig::with_format(self : LogConfig, fmt : String) -> LogConfig

Returns a copy with the format type replaced (e.g. "text", "json", "compact").

#
LogConfig::with_level

fn LogConfig::with_level(self : LogConfig, l : Level) -> LogConfig

Returns a copy with the log level replaced.

#
LogConfig::with_output

fn LogConfig::with_output(self : LogConfig, out : String) -> LogConfig

Returns a copy with the output type replaced (e.g. "console", "file", "audit").

#
LogEntry

pub(all) struct LogEntry {
timestamp : Int64
level : Level
message : String
mod_name : String
fields : Array[(String, String)]
file : String
line : Int
thread_id : Int
sequence : Int64
}

Structured log entry carrying metadata and message content.

#
LogEntry::fields

fn LogEntry::fields(self : LogEntry) -> Array[(String, String)]

Returns the key-value fields attached to the entry.

#
LogEntry::level

fn LogEntry::level(self : LogEntry) -> Level

Returns the log level of the entry.

#
LogEntry::location_file

fn LogEntry::location_file(self : LogEntry) -> String

Returns the source file path of the log call.

#
LogEntry::location_line

fn LogEntry::location_line(self : LogEntry) -> Int

Returns the source line number of the log call.

#
LogEntry::message

fn LogEntry::message(self : LogEntry) -> String

Returns the log message of the entry.

#
LogEntry::module_name

fn LogEntry::module_name(self : LogEntry) -> String

Returns the module name associated with the entry.

#
LogEntry::sequence

fn LogEntry::sequence(self : LogEntry) -> Int64

Returns the sequence number of the entry.

#
LogEntry::thread_id

fn LogEntry::thread_id(self : LogEntry) -> Int

Returns the thread ID of the log call.

#
LogEntry::timestamp

fn LogEntry::timestamp(self : LogEntry) -> Int64

Returns the timestamp of the entry.

#
LogEntryBuilder

pub(all) struct LogEntryBuilder {
entry : LogEntry
}

Builder for constructing a LogEntry with optional metadata.

#
LogEntryBuilder::build

Finalizes and returns the constructed LogEntry.

#
LogEntryBuilder::new

fn LogEntryBuilder::new(level : Level, message : String) -> LogEntryBuilder

Creates a new builder with the given level and message.

#
LogEntryBuilder::with_field

fn LogEntryBuilder::with_field(self : LogEntryBuilder, key : String, value : String) -> LogEntryBuilder

Adds a single key-value field to the entry.

#
LogEntryBuilder::with_fields

fn LogEntryBuilder::with_fields(self : LogEntryBuilder, extras : Array[(String, String)]) -> LogEntryBuilder

Appends multiple key-value fields to the entry.

#
LogEntryBuilder::with_location

fn LogEntryBuilder::with_location(self : LogEntryBuilder, file : String, line : Int) -> LogEntryBuilder

Sets the source file and line number on the entry.

#
LogEntryBuilder::with_module

fn LogEntryBuilder::with_module(self : LogEntryBuilder, name : String) -> LogEntryBuilder

Sets the module name on the entry.

#
LogEntryBuilder::with_sequence

fn LogEntryBuilder::with_sequence(self : LogEntryBuilder, seq : Int64) -> LogEntryBuilder

Sets the sequence number on the entry.

#
LogEntryBuilder::with_thread

fn LogEntryBuilder::with_thread(self : LogEntryBuilder, id : Int) -> LogEntryBuilder

Sets the thread ID on the entry.

#
LogEntryBuilder::with_timestamp

fn LogEntryBuilder::with_timestamp(self : LogEntryBuilder, ts : Int64) -> LogEntryBuilder

Sets the timestamp on the entry.

#
Logger

pub(all) struct Logger {
handlers : Array[HandlerFn]
level : Level
seq : Int64
}

Logger managing log level, handlers, and sequence numbering.

#
Logger::add_handler

fn Logger::add_handler(self : Logger, h : HandlerFn) -> Unit

Registers a handler to receive log entries.

#
Logger::clear_handlers

fn Logger::clear_handlers(self : Logger) -> Unit

Removes all registered handlers.

#
Logger::close

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

Closes all registered handlers.

#
Logger::debug

fn Logger::debug(self : Logger, msg : String) -> Unit

Logs a message at the Debug level.

#
Logger::error

fn Logger::error(self : Logger, msg : String) -> Unit

Logs a message at the Error level.

#
Logger::fatal

fn Logger::fatal(self : Logger, msg : String) -> Unit

Logs a message at the Fatal level.

#
Logger::flush

fn Logger::flush(self : Logger) -> Unit

Flushes all registered handlers.

#
Logger::info

fn Logger::info(self : Logger, msg : String) -> Unit

Logs a message at the Info level.

#
Logger::log

fn Logger::log(self : Logger, level : Level, message : String) -> Unit

Logs a message at the given level if it passes the threshold.

#
Logger::log_entry

fn Logger::log_entry(self : Logger, entry : LogEntry) -> Unit

Logs a pre-built entry if its level passes the threshold.

#
Logger::log_with

fn Logger::log_with(self : Logger, level : Level, msg : String, fields : Array[(String, String)]) -> Unit

Logs a message with additional key-value fields.

#
Logger::new

fn Logger::new() -> Logger

Creates a new Logger with no handlers and Debug level.

#
Logger::set_level

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

Sets the minimum log level for filtering.

#
Logger::warn

fn Logger::warn(self : Logger, msg : String) -> Unit

Logs a message at the Warn level.

#
Logger::with_level

fn Logger::with_level(self : Logger, l : Level) -> Logger

Sets the minimum log level, returning a new Logger instance.

#
MemoryHandler

pub(all) struct MemoryHandler {
level : Level
fmt : (LogEntry) -> String
entries : Array[LogEntry]
}

In-memory handler that stores log entries for later retrieval.

#
MemoryHandler::clear

fn MemoryHandler::clear(self : MemoryHandler) -> Unit

Clears all stored log entries.

#
MemoryHandler::close

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

Closes the handler and releases resources. No-op for memory handler.

#
MemoryHandler::count

fn MemoryHandler::count(self : MemoryHandler) -> Int

Returns the total number of stored entries.

#
MemoryHandler::count_by_level

fn MemoryHandler::count_by_level(self : MemoryHandler, target : Level) -> Int

Counts entries that match the given log level.

#
MemoryHandler::entries

fn MemoryHandler::entries(self : MemoryHandler) -> Array[LogEntry]

Returns all stored log entries.

#
MemoryHandler::first_entry

fn MemoryHandler::first_entry(self : MemoryHandler) -> LogEntry?

Returns the oldest entry, or None if no entries exist.

#
MemoryHandler::flush

fn MemoryHandler::flush(self : MemoryHandler) -> Unit

Flushes buffered output. No-op for memory handler.

#
MemoryHandler::formatted_lines

fn MemoryHandler::formatted_lines(self : MemoryHandler) -> Array[String]

Returns all stored entries formatted as strings using the handler's formatter.

#
MemoryHandler::last_entry

fn MemoryHandler::last_entry(self : MemoryHandler) -> LogEntry?

Returns the most recent entry, or None if no entries exist.

#
MemoryHandler::log

fn MemoryHandler::log(self : MemoryHandler, entry : LogEntry) -> Unit

Stores an entry in memory if its level meets the configured threshold.

#
MemoryHandler::new

fn MemoryHandler::new(level : Level, fmt : (LogEntry) -> String) -> MemoryHandler

Creates a new MemoryHandler with the given minimum level and formatter.

#
MultiHandler

pub(all) struct MultiHandler {
handlers : Array[HandlerFn]
}

Multi-handler that delegates log operations to a list of sub-handlers.

#
MultiHandler::add

fn MultiHandler::add(self : MultiHandler, h : HandlerFn) -> Unit

Adds a sub-handler to the multi-handler.

#
MultiHandler::close

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

Closes all registered sub-handlers.

#
MultiHandler::flush

fn MultiHandler::flush(self : MultiHandler) -> Unit

Flushes all registered sub-handlers.

#
MultiHandler::log

fn MultiHandler::log(self : MultiHandler, entry : LogEntry) -> Unit

Delegates logging to all registered sub-handlers.

#
MultiHandler::new

Creates an empty MultiHandler with no sub-handlers.

#
NullHandler

pub(all) struct NullHandler {
level : Level
}

Handler that discards all log entries (null pattern).

#
NullHandler::close

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

No-op close.

#
NullHandler::flush

fn NullHandler::flush(self : NullHandler) -> Unit

No-op flush.

#
NullHandler::log

fn NullHandler::log(self : NullHandler, _entry : LogEntry) -> Unit

Discards the entry (no-op).

#
NullHandler::new

fn NullHandler::new(level : Level) -> NullHandler

Creates a NullHandler that discards all entries below the given level.

#
RateLimitedHandler

pub(all) struct RateLimitedHandler {
inner : HandlerFn
max_per_second : Int
window_count : Int
window_start : Int64
window_duration : Int64
}

Handler that rate-limits log entries to a maximum per second.

#
RateLimitedHandler::close

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

Delegates close to the inner handler.

#
RateLimitedHandler::flush

fn RateLimitedHandler::flush(self : RateLimitedHandler) -> Unit

Delegates flush to the inner handler.

#
RateLimitedHandler::log

fn RateLimitedHandler::log(self : RateLimitedHandler, entry : LogEntry) -> Unit

Forwards the entry to the inner handler if the rate limit has not been exceeded.

#
RateLimitedHandler::new

fn RateLimitedHandler::new(inner : HandlerFn, max_per_second : Int) -> RateLimitedHandler

Creates a RateLimitedHandler that limits to max_per_second entries per second.

#
RingBufferHandler

pub(all) struct RingBufferHandler {
level : Level
fmt : (LogEntry) -> String
buffer : Array[LogEntry]
capacity : Int
head : Int
count : Int
}

Ring buffer handler that keeps a fixed-capacity sliding window of recent log entries.

#
RingBufferHandler::close

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

No-op for ring buffer; entries are managed in memory.

#
RingBufferHandler::drain

Returns and clears all entries from the ring buffer.

#
RingBufferHandler::entries

Returns all entries in the ring buffer in insertion order.

#
RingBufferHandler::fill_ratio

fn RingBufferHandler::fill_ratio(self : RingBufferHandler) -> Double

Returns the fraction of capacity currently used, as a value between 0.0 and 1.0.

#
RingBufferHandler::flush

fn RingBufferHandler::flush(self : RingBufferHandler) -> Unit

No-op for ring buffer; entries are managed in memory.

#
RingBufferHandler::is_full

fn RingBufferHandler::is_full(self : RingBufferHandler) -> Bool

Returns true if the ring buffer has reached its capacity.

#
RingBufferHandler::log

fn RingBufferHandler::log(self : RingBufferHandler, entry : LogEntry) -> Unit

Adds an entry to the ring buffer, overwriting the oldest entry if full.

#
RingBufferHandler::new

fn RingBufferHandler::new(level : Level, fmt : (LogEntry) -> String, capacity : Int) -> RingBufferHandler

Creates a RingBufferHandler with the given level, formatter, and capacity.

#
RotatingFileHandler

pub(all) struct RotatingFileHandler {
level : Level
fmt : (LogEntry) -> String
lines : Array[String]
max_lines : Int
max_files : Int
base_path : String
file_count : Int
}

Rotating file handler with size-based log rotation.

#
RotatingFileHandler::close

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

Flushes and closes the handler.

#
RotatingFileHandler::file_count

fn RotatingFileHandler::file_count(self : RotatingFileHandler) -> Int

Returns the current file rotation count.

#
RotatingFileHandler::flush

fn RotatingFileHandler::flush(self : RotatingFileHandler) -> Unit

Flushes buffered lines to disk and clears the buffer.

#
RotatingFileHandler::lines

fn RotatingFileHandler::lines(self : RotatingFileHandler) -> Array[String]

Returns the current buffered lines.

#
RotatingFileHandler::log

fn RotatingFileHandler::log(self : RotatingFileHandler, entry : LogEntry) -> Unit

Logs an entry if its level is enabled, buffering until rotation threshold is met.

#
RotatingFileHandler::new

fn RotatingFileHandler::new(level : Level, fmt : (LogEntry) -> String, base_path : String, max_lines : Int, max_files : Int) -> RotatingFileHandler

Creates a new RotatingFileHandler with the given level, formatter, base path, and rotation limits.

#
SamplingHandler

pub(all) struct SamplingHandler {
inner : HandlerFn
rate : Int
count : Int
}

Handler that only logs every N-th entry (sampling).

#
SamplingHandler::close

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

Delegates close to the inner handler.

#
SamplingHandler::flush

fn SamplingHandler::flush(self : SamplingHandler) -> Unit

Delegates flush to the inner handler.

#
SamplingHandler::log

fn SamplingHandler::log(self : SamplingHandler, entry : LogEntry) -> Unit

Logs the entry if the internal counter is divisible by the sampling rate.

#
SamplingHandler::new

fn SamplingHandler::new(inner : HandlerFn, rate : Int) -> SamplingHandler

Creates a SamplingHandler that logs one out of every rate entries.

#
SamplingHandler::reset

fn SamplingHandler::reset(self : SamplingHandler) -> Unit

Resets the sampling counter to zero.

#
Stopwatch

pub(all) struct Stopwatch {
elapsed : Double
running : Bool
start_time :
Timestamp

}

A simple stopwatch for measuring elapsed time in microseconds.

#
Stopwatch::elapsed_micros

fn Stopwatch::elapsed_micros(self : Stopwatch) -> Double

Returns the total elapsed time in microseconds (including current run if running).

#
Stopwatch::elapsed_millis

fn Stopwatch::elapsed_millis(self : Stopwatch) -> Double

Returns the total elapsed time in milliseconds.

#
Stopwatch::elapsed_secs

fn Stopwatch::elapsed_secs(self : Stopwatch) -> Double

Returns the total elapsed time in seconds.

#
Stopwatch::format_elapsed

fn Stopwatch::format_elapsed(self : Stopwatch) -> String

Formats the stopwatch's elapsed time as a human-readable string (us/ms/s).

#
Stopwatch::is_running

fn Stopwatch::is_running(self : Stopwatch) -> Bool

Returns true if the stopwatch is currently running.

#
Stopwatch::new

fn Stopwatch::new() -> Stopwatch

Creates a new stopped Stopwatch with zero elapsed time.

#
Stopwatch::reset

fn Stopwatch::reset(self : Stopwatch) -> Unit

Resets the stopwatch to zero and stops it.

#
Stopwatch::restart

fn Stopwatch::restart(self : Stopwatch) -> Unit

Resets and immediately starts the stopwatch.

#
Stopwatch::start

fn Stopwatch::start(self : Stopwatch) -> Unit

Starts the stopwatch; no-op if already running.

#
Stopwatch::stop

fn Stopwatch::stop(self : Stopwatch) -> Unit

Stops the stopwatch and accumulates the elapsed time; no-op if not running.

#
TextHandler

pub(all) struct TextHandler {
level : Level
fmt : (LogEntry) -> String
prefix : String
}

Text handler that outputs log entries with an optional prefix string.

#
TextHandler::close

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

Closes the handler and releases resources. No-op for text handler.

#
TextHandler::flush

fn TextHandler::flush(self : TextHandler) -> Unit

Flushes buffered output. No-op for text handler.

#
TextHandler::log

fn TextHandler::log(self : TextHandler, entry : LogEntry) -> Unit

Logs an entry with an optional prefix if its level meets the threshold.

#
TextHandler::new

fn TextHandler::new(level : Level, fmt : (LogEntry) -> String) -> TextHandler

Creates a new TextHandler with the given minimum level and formatter.

#
TextHandler::with_prefix

fn TextHandler::with_prefix(self : TextHandler, p : String) -> TextHandler

Sets a prefix string prepended to each log line. Returns a new handler.

#
ThrottledHandler

pub(all) struct ThrottledHandler {
inner : HandlerFn
seen : Array[String]
}

Handler that limits log output to at most one entry per unique message.

#
ThrottledHandler::close

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

Closes the inner handler and clears seen messages.

#
ThrottledHandler::flush

fn ThrottledHandler::flush(self : ThrottledHandler) -> Unit

Flushes the inner handler.

#
ThrottledHandler::log

fn ThrottledHandler::log(self : ThrottledHandler, entry : LogEntry) -> Unit

Logs the entry only if its message has not been seen before.

#
ThrottledHandler::new

Creates a ThrottledHandler that only logs each unique message once.

#
ThroughputMeter

pub(all) struct ThroughputMeter {
sw : Stopwatch
count : Int64
}

Meter that counts operations and measures throughput (ops per second).

#
ThroughputMeter::elapsed_str

fn ThroughputMeter::elapsed_str(self : ThroughputMeter) -> String

Returns the elapsed measurement time as a human-readable string.

#
ThroughputMeter::format_throughput

fn ThroughputMeter::format_throughput(self : ThroughputMeter) -> String

Returns a human-readable throughput string (e.g. "1.23 K ops/s").

#
ThroughputMeter::increment

fn ThroughputMeter::increment(self : ThroughputMeter) -> Unit

Increments the operation count by one; starts the timer on first call.

#
ThroughputMeter::new

Creates a new ThroughputMeter with zero count and a stopped stopwatch.

#
ThroughputMeter::ops_per_second

fn ThroughputMeter::ops_per_second(self : ThroughputMeter) -> Double

Returns the measured throughput in operations per second.

#
ThroughputMeter::record_batch

fn ThroughputMeter::record_batch(self : ThroughputMeter, n : Int64) -> Unit

Records a batch of operations (adds n to count); starts the timer on first call.

#
ThroughputMeter::stop

fn ThroughputMeter::stop(self : ThroughputMeter) -> Unit

Stops the throughput measurement timer.

#
add_thread_id

fn add_thread_id(entry : LogEntry, id : Int) -> LogEntry

Returns a copy of the entry with the thread_id field replaced.

#
add_timestamp

fn add_timestamp(entry : LogEntry) -> LogEntry

Returns a copy of the entry with timestamp set to sequence + 1.

#
ansi_blue

fn ansi_blue() -> String

ANSI blue foreground color code.

#
ansi_bold

fn ansi_bold() -> String

ANSI bold / increased intensity code.

#
ansi_cyan

fn ansi_cyan() -> String

ANSI cyan foreground color code.

#
ansi_dim

fn ansi_dim() -> String

ANSI dim / decreased intensity code.

#
ansi_gray

fn ansi_gray() -> String

ANSI gray foreground color code.

#
ansi_green

fn ansi_green() -> String

ANSI green foreground color code.

#
ansi_magenta

fn ansi_magenta() -> String

ANSI magenta foreground color code.

#
ansi_red

fn ansi_red() -> String

ANSI red foreground color code.

#
ansi_reset

fn ansi_reset() -> String

ANSI reset code to clear all attributes.

#
ansi_yellow

fn ansi_yellow() -> String

ANSI yellow foreground color code.

#
audit_formatter

fn audit_formatter(separator : String) -> ((LogEntry) -> String)

Separator-delimited formatter suitable for audit trails.

#
audit_logger

fn audit_logger(level : Level, sep : String) -> Logger

Creates an audit logger with the given level and separator.
fn banner_formatter(width : Int) -> ((LogEntry) -> String)

Formats a log entry as a full-width banner for emphasis.

#
benchmark

fn benchmark(name : String, iterations : Int, f : () -> Unit) -> BenchmarkResult

Runs a function iterations times and returns timing statistics.

#
benchmark_compare

fn benchmark_compare(name_a : String, name_b : String, iterations : Int, f_a : () -> Unit, f_b : () -> Unit) -> String

Runs two benchmarks and returns a side-by-side comparison report.

#
benchmark_report

fn benchmark_report(result : BenchmarkResult) -> String

Returns a human-readable benchmark report string.

#
benchmark_warmup

fn benchmark_warmup(name : String, iterations : Int, warmup : Int, f : () -> Unit) -> BenchmarkResult

Runs warmup iterations, then benchmarks and returns timing statistics.

#
compact_formatter

fn compact_formatter() -> ((LogEntry) -> String)

Minimal formatter producing only level and message.

#
configure

fn configure(level : Level, fmt : (LogEntry) -> String) -> Unit

Reconfigures the global logger with the given level and formatter, replacing all handlers.

#
csv_formatter

fn csv_formatter(separator : String, _include_header : Bool) -> ((LogEntry) -> String)

Formats a log entry in CSV-like format.

#
custom_formatter

fn custom_formatter(f : (LogEntry) -> String) -> ((LogEntry) -> String)

Wraps a user-provided formatting function as a LogEntry formatter.

#
default_setup

fn default_setup() -> Logger

Creates a logger with default Debug level and compact console format.

#
entries_by_level

fn entries_by_level(entries : Array[LogEntry], target : Level) -> Array[LogEntry]

Returns only entries of the specified level.

#
entries_count

fn entries_count(entries : Array[LogEntry]) -> Int

Returns the number of entries in the array.

#
entries_earliest

fn entries_earliest(entries : Array[LogEntry]) -> LogEntry?

Returns the entry with the earliest timestamp, or None if empty.

#
entries_filter

fn entries_filter(entries : Array[LogEntry], predicate : (LogEntry) -> Bool) -> Array[LogEntry]

Filters entries using a predicate function, returning matching entries.

#
entries_latest

fn entries_latest(entries : Array[LogEntry]) -> LogEntry?

Returns the entry with the latest timestamp, or None if empty.

#
entries_reject

fn entries_reject(entries : Array[LogEntry], predicate : (LogEntry) -> Bool) -> Array[LogEntry]

Returns a new array without entries that match the predicate.

#
entries_sort_by_timestamp

fn entries_sort_by_timestamp(entries : Array[LogEntry]) -> Array[LogEntry]

Sorts an array of LogEntries by timestamp in ascending order.

#
entries_summary

fn entries_summary(entries : Array[LogEntry]) -> String

Returns a summary string of all entries in an array.

#
entries_to_json_array

fn entries_to_json_array(entries : Array[LogEntry]) -> String

Serializes an array of LogEntries to a JSON array string.

#
entry_from_json

fn entry_from_json(json : String) -> LogEntry?

Deserializes a JSON string into a LogEntry, returning None on failure.

#
entry_get_field

fn entry_get_field(entry : LogEntry, key : String) -> String?

Returns the value of a field by key, or None if not found.

#
entry_has_field

fn entry_has_field(entry : LogEntry, key : String) -> Bool

Returns true if the entry contains a field with the given key.

#
entry_merge

fn entry_merge(base : LogEntry, other : LogEntry) -> LogEntry

Merges two log entries, combining their fields (base fields first, then other).

#
entry_to_json_string

fn entry_to_json_string(entry : LogEntry) -> String

Serializes a LogEntry to a JSON string.

#
entry_with_fields

fn entry_with_fields(entry : LogEntry, extras : Array[(String, String)]) -> LogEntry

Returns a copy of the entry with additional fields appended.

#
from_config_json

fn from_config_json(json : String) -> Logger

Creates a logger from a JSON config string describing level and output format.

#
g_close

fn g_close() -> Unit

Closes all handlers on the global logger.

#
g_debug

fn g_debug(msg : String) -> Unit

Logs a debug message via the global logger.

#
g_error

fn g_error(msg : String) -> Unit

Logs an error message via the global logger.

#
g_fatal

fn g_fatal(msg : String) -> Unit

Logs a fatal message via the global logger.

#
g_flush

fn g_flush() -> Unit

Flushes all handlers on the global logger.

#
g_info

fn g_info(msg : String) -> Unit

Logs an info message via the global logger.

#
g_log

fn g_log(level : Level, msg : String) -> Unit

Logs a message at the specified level via the global logger.

#
g_log_with

fn g_log_with(level : Level, msg : String, fields : Array[(String, String)]) -> Unit

Logs a message with structured fields at the specified level via the global logger.

#
g_warn

fn g_warn(msg : String) -> Unit

Logs a warning message via the global logger.

#
get_global_logger

fn get_global_logger() -> Logger

Returns the global singleton logger instance.

#
init_default_console

fn init_default_console() -> Unit

Initializes the global logger with a default console handler using compact format.

#
init_default_json

fn init_default_json() -> Unit

Initializes the global logger with a default JSON console handler at Info level.

#
json_formatter

fn json_formatter() -> ((LogEntry) -> String)

JSON formatter producing structured log output.

#
json_logger

fn json_logger(level : Level) -> Logger

Creates a JSON-format logger at the given level.

#
kv_formatter

fn kv_formatter() -> ((LogEntry) -> String)

Formats a log entry in key=value format with a timestamp prefix.

#
lazy_format

fn lazy_format(template : String, entry : LogEntry) -> String

Replace {placeholder} tokens in a template string with log entry fields.

#
logfmt_formatter

fn logfmt_formatter() -> ((LogEntry) -> String)

Logfmt-style formatter producing key=value pairs.

#
make_handler

fn make_handler(log_fn : (LogEntry) -> Unit, flush_fn : () -> Unit, close_fn : () -> Unit) -> HandlerFn

Creates a HandlerFn from individual log, flush, and close callbacks.

#
mask_field

fn mask_field(entry : LogEntry, field_key : String) -> LogEntry

Returns a copy of the entry with the specified field value masked as "****".

#
measure_time

fn measure_time(f : () -> Unit) -> Double

Measures and returns the execution time of a function in microseconds.

#
measure_time_ms

fn measure_time_ms(f : () -> Unit) -> Double

Measures and returns the execution time of a function in milliseconds.

#
multi_line_formatter

fn multi_line_formatter(indent : Int) -> ((LogEntry) -> String)

Multi-line formatter that prints each field on its own line with indentation.

#
pattern_formatter

fn pattern_formatter(pattern : String) -> ((LogEntry) -> String)

Create a formatter that applies the given template pattern to every entry.

#
prefix_message

fn prefix_message(entry : LogEntry, prefix : String) -> LogEntry

Returns a copy of the entry with a prefix prepended to the message.

#
pretty_formatter

fn pretty_formatter(use_color : Bool) -> ((LogEntry) -> String)

Colorized formatter with optional ANSI color codes by log level.

#
quick_logger

fn quick_logger(level : Level) -> Logger

Creates a logger with default config at the given level.

#
redirect_level

fn redirect_level(entry : LogEntry, from : Level, to : Level) -> LogEntry

Returns a copy of the entry with the level changed from from to to.

#
set_global_logger

fn set_global_logger(logger : Logger) -> Unit

Replaces the global logger's level and handlers with those from the given logger.

#
stats_formatter

fn stats_formatter(show_fields : Bool, show_location : Bool) -> ((LogEntry) -> String)

Compact formatter with optional fields and source location display.

#
strip_fields

fn strip_fields(entry : LogEntry) -> LogEntry

Returns a copy of the entry with all fields removed.

#
suffix_message

fn suffix_message(entry : LogEntry, suffix : String) -> LogEntry

Returns a copy of the entry with a suffix appended to the message.

#
text_formatter

fn text_formatter() -> ((LogEntry) -> String)

Plain-text formatter with timestamp, level, module, message and fields.

#
xml_formatter

fn xml_formatter() -> ((LogEntry) -> String)

XML formatter producing element with structured children.