1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- use os;
- use io;
- use fmt;
- use ascii;
- use bufio;
- export type Level = enum u8 {
- NONE,
- CRITICAL,
- ERROR,
- WARNING,
- INFO,
- DEBUG,
- };
- export fn level2str(l: Level) str =
- switch (l) {
- case Level::NONE => yield "NONE";
- case Level::CRITICAL => yield "CRITICAL";
- case Level::ERROR => yield "ERROR";
- case Level::WARNING => yield "WARNING";
- case Level::INFO => yield "INFO";
- case Level::DEBUG => yield "DEBUG";
- };
- export type InvalidLevel = !str;
- export type LevelStringTooLong = !size;
- export type LevelError = !(InvalidLevel | LevelStringTooLong);
- export fn str2level(l: str) (Level | !LevelError) = {
- static let buf: [64]u8 = [0...];
- static const max_level_len: size = 16;
- const actual_len = len(l);
- if (actual_len > max_level_len) return actual_len: !LevelStringTooLong;
- return switch (ascii::strupper_buf(l, buf[..0])) {
- case "NONE" => yield Level::NONE;
- case "CRITICAL" => yield Level::CRITICAL;
- case "ERROR" => yield Level::ERROR;
- case "WARNING" => yield Level::WARNING;
- case "INFO" => yield Level::INFO;
- case "DEBUG" => yield Level::DEBUG;
- case => return l: !InvalidLevel;
- };
- };
- export type Logger = struct {
- name: str,
- level: Level,
- handle: io::handle,
- };
- export fn new(name: str, level: Level, handle: io::handle) Logger =
- Logger {
- name = name,
- level = level,
- handle = handle,
- };
- export fn log(level: Level, l: Logger, fmt: str, args: fmt::field...) void =
- if (level <= l.level && level > Level::NONE) {
- static let buf: [os::BUFSZ]u8 = [0...];
- const handle: io::handle = &bufio::init(l.handle, [], buf);
- defer io::close(handle)!;
- fmt::fprintf(handle, "{}: {}: ", l.name, level2str(level))!;
- fmt::fprintf(handle, fmt, args...)!;
- fmt::fprintln(handle)!;
- };
- export fn critical(l: Logger, fmt: str, args: fmt::field...) void =
- log(Level::CRITICAL, l, fmt, args...);
- export fn error(l: Logger, fmt: str, args: fmt::field...) void =
- log(Level::ERROR, l, fmt, args...);
- export fn warning(l: Logger, fmt: str, args: fmt::field...) void =
- log(Level::WARNING, l, fmt, args...);
- export fn warn(l: Logger, fmt: str, args: fmt::field...) void =
- warning(l, fmt, args...);
- export fn info(l: Logger, fmt: str, args: fmt::field...) void =
- log(Level::INFO, l, fmt, args...);
- export fn debug(l: Logger, fmt: str, args: fmt::field...) void =
- log(Level::DEBUG, l, fmt, args...);
|