logger
import std::log::logger; · source
Types
Logger
type struct Logger {
private area: Str;
}
A named area of a program, Logger::new(Str::new("http")), that logs records at a level. A logger is a name and nothing else: copy it, or keep one in a global. It keeps the Str it was given, not a copy, so the text must outlive it, as a literal does.
import std::collections::str::{ Str };
import std::log::logger::{ Logger };
const log: Logger = Logger::new(Str::new("http"));
const path: Str = Str::new("/favicon.ico");
log.warning(f"no route for {path}");
error, warning, information, debug and trace log at their level, and log(level, message) at the level given. Each takes the message as an f-string written in the call, which is formatted only when a sink writes it, so a record the settings refuse costs one atomic load. The record carries the location of the logging call. is_enabled(level) answers whether a record at level would get through, for work worth skipping when it would not.
Constructors
static new(area: Str) -> Logger;
static new(area: Str) -> Logger;A logger for area, a name like http or http::server; an area below another (http::server below http) takes the level set for it when it has none of its own. The logger keeps the Str, not a copy, so the text must outlive it, as a literal does.
Methods
area(&this) -> Str;
area(&this) -> Str;The area this logger was made for, as given to new.
is_enabled(&this, level: LogLevel) -> boolean;
is_enabled(&this, level: LogLevel) -> boolean;True when the settings let a record at level from this logger's area through.
![caller_location]log(&this, level: LogLevel, message: Arguments) -> void;
![caller_location]log(&this, level: LogLevel, message: Arguments) -> void;Hand a record to the sink when the settings let it through. The record's location is where this call is written.
![caller_location]error(&this, message: Arguments) -> void;
![caller_location]error(&this, message: Arguments) -> void;log at LogLevel::Error, the least verbose level: something failed. Let through by the default settings.
![caller_location]warning(&this, message: Arguments) -> void;
![caller_location]warning(&this, message: Arguments) -> void;log at LogLevel::Warning: something is wrong but the program carries on. Let through by the default settings.
![caller_location]information(&this, message: Arguments) -> void;
![caller_location]information(&this, message: Arguments) -> void;log at LogLevel::Information: what the program is doing. Refused until the settings allow Information for this area.
![caller_location]debug(&this, message: Arguments) -> void;
![caller_location]debug(&this, message: Arguments) -> void;log at LogLevel::Debug: detail for finding a fault. Refused until the settings allow Debug for this area.
![caller_location]trace(&this, message: Arguments) -> void;
![caller_location]trace(&this, message: Arguments) -> void;log at LogLevel::Trace, the most verbose level: step-by-step detail. Refused until the settings allow Trace for this area.
Logging
type struct Logging {}
The process-wide logging settings. Until a program changes them, records at Warning and above go to standard error, through a StandardErrorSink.
set_level(level)lets records atleveland above through from every area no area setting names.set_area_level(area, level)sets the level forareaand every area below it:httpcovershttp::server, but nothttps. When several settings name areas a record's area is below, the longest wins.configure(specification)applies comma-separated entries, each a level name (the default level) orarea=level:"information,http=debug". Spaces around an entry and its parts are ignored, and so is an empty entry. Nothing is applied when an entry cannot be read; the error names the first such entry.configure_from_environment(variable)isconfigurewith the value of an environment variable, and changes nothing when it is unset.set_sink(&sink)sends every record from then on to aLogSinkof the program's own, andreset_sink()sends them to standard error again. The sink is borrowed, not kept: it must live until the program stops logging, as a global or a valuemainholds does. Any thread may log, so the sink's type must beSync.
import std::log::record::{ LogLevel };
import std::log::logger::{ Logger, Logging };
Logging::configure(Str::new("warning,http::server=debug")).unwrap();
const log: Logger = Logger::new(Str::new("http"));
const server: Logger = Logger::new(Str::new("http::server"));
server.is_enabled(LogLevel::Debug); // true
log.is_enabled(LogLevel::Debug); // false: `http` has the default, `warning`
Static functions
static set_level(level: LogLevel) -> void;
static set_level(level: LogLevel) -> void;Let records at level and above through, from every area no area setting names.
static set_area_level(area: Str, level: LogLevel) -> void;
static set_area_level(area: Str, level: LogLevel) -> void;Let records at level and above through from area and every area below it, replacing an earlier setting for the same area.
static configure(specification: Str) -> Result<(), LogSpecificationError>;
static configure(specification: Str) -> Result<(), LogSpecificationError>;Apply a specification of comma-separated entries, each a level name (the default level) or area=level: "information,http=debug". Spaces around an entry and its parts are ignored, and so is an empty entry. Nothing is applied when an entry cannot be read; the error names the first such entry.
static configure_from_environment(variable: Str) -> Result<(), LogSpecificationError>;
static configure_from_environment(variable: Str) -> Result<(), LogSpecificationError>;configure with the value of the environment variable variable; nothing changes when it is unset.
static set_sink<S>(sink: &S) -> void where S: LogSink, S: Sync;
static set_sink<S>(sink: &S) -> void where S: LogSink, S: Sync;Send every record from now on to sink, in place of standard error. The sink is borrowed, not kept: it must live until the program stops logging, as a global or a value main holds does. Any thread may log, so the sink's type must be Sync.
static reset_sink() -> void;
static reset_sink() -> void;Send records to standard error again, as before any set_sink.
LogSpecificationError
type struct LogSpecificationError with [Eq, Clone, Debug] {
entry: String;
}
A logging specification entry Logging::configure could not read, as written between commas. It prints as unrecognized logging entry 'http=loud'.
Properties
| Property | Type | Notes |
|---|---|---|
entry | String | The entry, as written between commas. |
Trait implementations
implement trait Error for struct LogSpecificationError
implement trait Display for struct LogSpecificationError
type struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type struct Name {
field: Type;
method(&this) -> Ret { ... }
}A value type with named fields and optional methods. Structs live on the stack and are passed by value. Fields are public by default and may carry = default values; methods take their receiver as &this, mut &this, or this.
type struct Logger {}A named area of a program, Logger::new("http"), that logs records at a level: log.warning(f"no route for {path}"). An f-string message is formatted only when a sink writes it, so a record the settings refuse costs one atomic load. A logger is a name and nothing else: copy it, or keep one in a global.
private type struct Name { ... }
private:Confined to the module that declares it - for items and members alike. A private field or function reached from another module is E0353, and a private type named there is E0503. private: opens a block of such members.
Logger.area: Strtype struct Str {}A read-only view of UTF-8 text owned elsewhere: a string literal, a String, a file's bytes. Copying a Str copies the view, not the text, and it is valid only while what it views is. Str::new("text") views a literal; String.as_str() views a String.
import a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
namespace std::log;log: records a program writes about what it is doing, by area and level, sent to one process-wide sink.
module pagenamespace std::log::logger;Logger, a named area a program logs through, and Logging, the process-wide settings every logger reads: the level for each area and the sink records go to.
type struct Logger {}A named area of a program, Logger::new("http"), that logs records at a level: log.warning(f"no route for {path}"). An f-string message is formatted only when a sink writes it, so a record the settings refuse costs one atomic load. A logger is a name and nothing else: copy it, or keep one in a global.
const NAME: Type = value;At module level, a true compile-time constant, conventionally SCREAMING_SNAKE_CASE. (mut at module level declares mutable global state instead.)
const log: Loggerstatic Logger::new(area: Str) -> LoggerA logger for area, a name like http or http::server; an area below another (http::server below http) takes the level set for it when it has none of its own. The logger keeps the Str, not a copy, so the text must outlive it, as a literal does.
static Str::new(text: string) -> StrConstruct from a NUL-terminated C-style string literal. The caller certifies that text is valid UTF-8 and outlives this view. The NUL terminator is not included in the view.
const path: Strconst log: LoggerLogger::warning(&this, message: Arguments) -> voidlog at LogLevel::Warning: something is wrong but the program carries on. Let through by the default settings.
const path: Strtype struct Logging {}The process-wide logging settings. Records at Warning and above go to standard error until a program says otherwise.
type enum LogLevel with [Eq, Clone, Debug] {
Error;
Warning;
Information;
Debug;
Trace;
}How much a record matters, from Error, the most, to Trace, the least. A level setting lets through records at that level and every level above it: Warning passes errors and warnings.
type struct Logging {}The process-wide logging settings. Records at Warning and above go to standard error until a program says otherwise.
static Logging::configure(specification: Str) -> Result<(), LogSpecificationError>Apply a specification of comma-separated entries, each a level name (the default level) or area=level: "information,http=debug". Spaces around an entry and its parts are ignored, and so is an empty entry. Nothing is applied when an entry cannot be read; the error names the first such entry.
Result::unwrap(this) -> TThe Ok value, aborting on Err. Consumes the result: the value moves out to the caller and the error, if any, is released.
const server: Loggerconst server: LoggerLogger::is_enabled(&this, level: LogLevel) -> booleanTrue when the settings let a record at level from this logger's area through.
LogLevel::Debugconst log: Loggertype struct LogSpecificationError with [Eq, Clone, Debug] {
entry: String;
}A logging specification entry Logging::configure could not read.
type struct Point with [Eq, Clone, Debug] { .. }Asks the compiler to generate implementations of the listed traits for the type, each working through its fields or variants in declaration order. The derivable traits are Eq, Ord, Hash, Clone, Debug, Default, ToValue and FromValue, and the text formats' FromJson, ToJson, FromYaml, ToYaml, FromToml and ToToml. The clause comes after the name and its parameters, before where.
type trait Eq<Rhs = This> {
equals(&this, other: &Rhs) -> boolean;
}Types that support value equality with a value of Rhs, which is the type itself unless an implementation names another: implement trait Eq for Str compares two Strs, and implement trait Eq<string> for Str a Str with a string.
type trait Clone {
clone(&this) -> This;
}A type whose values can be duplicated into independent copies. A type takes it with with [Clone] on its declaration, or by implementing clone by hand.
type trait Debug {
fmt(&this, f: mut &Formatter) -> Result<(), FormatError>;
}How a value reads to a programmer: what {x:?} writes, and {x:#?} over several lines. with [Debug] on a declaration writes it field by field.
LogSpecificationError.entry: StringThe entry, as written between commas.
type struct String<A = GlobalAllocator> {}Owned, growable UTF-8 text. It dereferences to Str, the read-only view most text functions take, so every Str method reads a String too (s.contains(...), s.split(...)); as_str hands the view out.
Logger::error(&this, message: Arguments) -> voidlog at LogLevel::Error, the least verbose level: something failed. Let through by the default settings.
Logger::information(&this, message: Arguments) -> voidlog at LogLevel::Information: what the program is doing. Refused until the settings allow Information for this area.
Logger::debug(&this, message: Arguments) -> voidlog at LogLevel::Debug: detail for finding a fault. Refused until the settings allow Debug for this area.
Logger::trace(&this, message: Arguments) -> voidlog at LogLevel::Trace, the most verbose level: step-by-step detail. Refused until the settings allow Trace for this area.
const log: Loggerstatic name(param: Type) -> Ret { ... }A method that belongs to the type rather than an instance, called as Type::name(..). For structs, static new(..) returning a struct literal is the idiomatic constructor.
(parameter) area: Str&this
mut &this
thisThe receiver of a method. Its first parameter declares how the method takes it: &this borrows read-only, mut &this borrows exclusively, and this / mut this move the value in and consume it. In the body, this.field reaches the members.
new T { field: value }
new Path(args)
new E::Variant
new T[n]Heap allocation. new T { .. } places a struct literal on the heap and yields a T*, and new E::V does the same for a unit variant. new Path(args) places the value a call returns, whatever its type: new Table::new(8), new Option<i64>::Some(41), new make_pair(3, 4). new T[n] reserves n uninitialised T - the typed malloc. The storage comes from the value type's Allocate implementation, or else the global allocator. A type is not a function, so new Point(1, 2) is refused (E0231).
(parameter) level: LogLevel(parameter) message: Argumentstype struct Arguments {}Text formatted where it is written. An f-string written directly as an argument whose parameter has this type is not built into a String: it becomes the f-string's pieces - its literal text, and a borrow of each hole's value - and the callee writes them through a Formatter (FormatWrite.write), each hole…
LogLevel::ErrorLogLevel::WarningLogLevel::InformationLogLevel::Tracestatic Logging::set_level(level: LogLevel) -> voidLet records at level and above through, from every area no area setting names.
static Logging::set_area_level(area: Str, level: LogLevel) -> voidLet records at level and above through from area and every area below it, replacing an earlier setting for the same area.
static Logging::configure_from_environment(variable: Str) -> Result<(), LogSpecificationError>configure with the value of the environment variable variable; nothing changes when it is unset.
static Logging::set_sink<S>(sink: &S) -> void
where S: LogSink, S: SyncSend every record from now on to sink, in place of standard error. The sink is borrowed, not kept: it must live until the program stops logging, as a global or a value main holds does. Any thread may log, so the sink's type must be Sync.
static Logging::reset_sink() -> voidSend records to standard error again, as before any set_sink.
type trait Sync {}Types that are safe to share between threads by shared reference. T: Sync if &T: Send.
(parameter) specification: Strtype enum Result<T, E> with [Eq, Clone, Debug] {
Ok(T);
Err(E);
}The outcome of an operation that can fail: Ok(value) on success, Err(error) on failure.
primitive ()The unit type: a value that carries no information, and the empty tuple. Distinct from void, which is the absence of a value - Result<(), E> succeeds with nothing to return. 0 bytes.
type struct LogSpecificationError with [Eq, Clone, Debug] {
entry: String;
}A logging specification entry Logging::configure could not read.
(parameter) variable: Str(parameter) sink: &Swhere T: Ord + Clone, U: HashConstrains generic parameters to types that implement the listed traits, which is what makes those traits' methods callable on T. Bounds on one parameter join with +; parameters separate with ,. A where on a single method narrows the type's parameter for that method only.
type trait LogSink {
write(&this, record: &LogRecord) -> void;
}A destination for log records. Logging calls write for every record that passes the level settings, one call at a time: no two writes to a sink overlap, so a sink needs no lock of its own for its output to come out whole.
implement struct Name { ... }
implement trait Trait for Type { ... }
implement u64 { ... }Adds methods to a type outside its declaration. implement struct T (or enum, or a bare primitive) opens an inherent block; implement trait Tr for T supplies a trait's methods for one type. Resolution is at compile time - no dynamic dispatch.
implement trait Trait for Type { ... }Introduces a trait implementation: the block supplies, for one concrete type, the method bodies the trait requires.
language referencetype trait Error : Display, Debug {
source(&this) -> Option<virtual &Error>;
}An error: a message for a person through Display, a fuller form through Debug, and the error it was caused by, if it keeps one.
implement trait Trait for Type { ... }Names the type a trait implementation is for. The block that follows supplies the bodies the trait requires.
language referencetype trait Display {
fmt(&this, f: mut &Formatter) -> Result<(), FormatError>;
to_string(&this) -> String;
}How a value reads to a person: what {x} in an f-string and println write. Implement it for a type a user sees.