opentelemetry/logs/logger.rs
1use std::borrow::Cow;
2
3use crate::{logs::LogRecord, InstrumentationScope};
4
5#[cfg(feature = "spec_unstable_logs_enabled")]
6use super::Severity;
7
8/// The interface for emitting [`LogRecord`]s.
9pub trait Logger {
10 /// Specifies the `LogRecord` type associated with this logger.
11 type LogRecord: LogRecord;
12
13 /// Creates a new log record builder.
14 fn create_log_record(&self) -> Self::LogRecord;
15
16 /// Emit a [`LogRecord`]. If there is active current thread's [`Context`],
17 /// the logger will set the record's `TraceContext` to the active trace context,
18 ///
19 /// [`Context`]: crate::Context
20 fn emit(&self, record: Self::LogRecord);
21
22 #[cfg(feature = "spec_unstable_logs_enabled")]
23 /// Check if the given log level is enabled.
24 fn event_enabled(&self, level: Severity, target: &str) -> bool;
25}
26
27/// Interfaces that can create [`Logger`] instances.
28pub trait LoggerProvider {
29 /// The [`Logger`] type that this provider will return.
30 type Logger: Logger;
31
32 /// Returns a new logger with the given instrumentation scope.
33 ///
34 /// # Examples
35 ///
36 /// ```
37 /// use opentelemetry::InstrumentationScope;
38 /// use opentelemetry::logs::LoggerProvider;
39 /// use opentelemetry_sdk::logs::LoggerProvider as SdkLoggerProvider;
40 ///
41 /// let provider = SdkLoggerProvider::builder().build();
42 ///
43 /// // logger used in applications/binaries
44 /// let logger = provider.logger("my_app");
45 ///
46 /// // logger used in libraries/crates that optionally includes version and schema url
47 /// let scope = InstrumentationScope::builder(env!("CARGO_PKG_NAME"))
48 /// .with_version(env!("CARGO_PKG_VERSION"))
49 /// .with_schema_url("https://opentelemetry.io/schema/1.0.0")
50 /// .build();
51 ///
52 /// let logger = provider.logger_with_scope(scope);
53 /// ```
54 fn logger_with_scope(&self, scope: InstrumentationScope) -> Self::Logger;
55
56 /// Returns a new logger with the given name.
57 ///
58 /// The `name` should be the application name or the name of the library
59 /// providing instrumentation.
60 fn logger(&self, name: impl Into<Cow<'static, str>>) -> Self::Logger {
61 let scope = InstrumentationScope::builder(name).build();
62 self.logger_with_scope(scope)
63 }
64}