pub struct Loki { /* private fields */ }Expand description
A persistent, asynchronous logger implementation for Grafana Loki.
LokiLogger manages a dedicated background worker thread that handles batching,
retries, and HTTP transmission. It is designed to be high-performance, ensuring
that the main application thread is never blocked by network latency.
§Important Design Notes
- Monotonic Dating: This logger uses an internal “highwater” marking system.
The original date of the
Messageis ignored in favor of a strictly increasing timestamp generated at the moment of dispatch. This prevents Loki from rejecting out-of-order logs during high-frequency bursts. - Worker Lifecycle: A background thread is spawned on creation. Logs are transmitted via an MPSC channel. Dropping the logger will signal the worker to finish pending tasks before shutting down.
- Performance: Internal operations (batching, grouping by level) are performed in-memory, assuming that network I/O is the primary bottleneck.
Implementations§
Source§impl Loki
impl Loki
Sourcepub fn new(config: LokiConfig) -> Box<Loki>
pub fn new(config: LokiConfig) -> Box<Loki>
Creates a new LokiLogger using the StandardLokiService.
This is a convenience wrapper around Self::with_service.
Sourcepub fn with_service(
config: LokiConfig,
service: Box<dyn LokiService + Send + Sync>,
) -> Box<Loki>
pub fn with_service( config: LokiConfig, service: Box<dyn LokiService + Send + Sync>, ) -> Box<Loki>
Primary constructor that initializes the logger with a custom LokiService.
This method:
- Computes the full Loki Push API endpoint.
- Wraps the provided service in an
Arcfor shared access between the logger and the worker. - Spawns a background worker thread to process the log queue.
§Dependency Injection
By providing a custom LokiService, you can override how batches are processed,
enabling features like compression, custom filtering, or specialized error handling.
§Threading
Spawns a dedicated OS thread. The worker handles all network I/O and will
gracefully shut down when the LokiLogger instance is dropped.
§Panics
Panics if the internal [Client][reqwest::blocking::Client] cannot be initialized.
Sourcepub fn build_client(config: &LokiConfig) -> Client
pub fn build_client(config: &LokiConfig) -> Client
Constructs a pre-configured HTTP client for the Loki service.
This client is built with the specific connection and request timeouts
defined in the LokiConfig. It is intended to be used within an Arc
to share a connection pool across the worker’s lifecycle.
§Panics
- Panics if the TLS backend cannot be initialized or if the system configuration prevents creating a secure socket.
Sourcepub fn request_post(
payload: String,
data: &Arc<LokiData>,
) -> Result<Response, ServiceError>
pub fn request_post( payload: String, data: &Arc<LokiData>, ) -> Result<Response, ServiceError>
Performs a synchronous POST request to the Loki push API.
This method handles the low-level HTTP transmission, including setting
the Content-Type header and attaching authentication credentials.
§Errors
Returns a ServiceError::Network if the server is unreachable,
DNS resolution fails, or the connection times out.
Sourcepub fn request_auth(
request: RequestBuilder,
data: &Arc<LokiData>,
) -> RequestBuilder
pub fn request_auth( request: RequestBuilder, data: &Arc<LokiData>, ) -> RequestBuilder
Decorates a [RequestBuilder] with the configured authentication method.
Supports both Basic Auth (username/password) and Bearer Token /// authentication. If both are configured, they will both be applied to the request (though Loki usually expects only one).
§Parameters
request: The initial request builder to decorate.data: The shared data containing authentication credentials.
Trait Implementations§
Source§impl Drop for Loki
Ensures a graceful shutdown of the logging pipeline.
impl Drop for Loki
Ensures a graceful shutdown of the logging pipeline.
When the LokiLogger goes out of scope, the following sequence occurs:
- Channel Closure: The
senderis dropped (None). This signals the background worker that no more messages will be sent. - Worker Drain: The worker’s
receiver.recv()will return an error once the channel is empty, allowing its loop to terminate naturally. - Thread Join: The main thread blocks until the worker thread has finished processing and sending the final batch of logs.
This mechanism prevents data loss during application shutdown or restarts.
Source§impl LoggerImpl for Loki
impl LoggerImpl for Loki
Source§fn status(&self) -> LoggerStatus
fn status(&self) -> LoggerStatus
Returns the current operational status of the Loki service.
This method performs a live health check by hitting the /loki/status endpoint.
It uses a functional pipeline to transform the network result into a LoggerStatus.
§Performance Note:
This call is blocking. If the network is slow or the Loki server is hanging, this method will block the calling thread until the default timeout is reached.
§Returns
LoggerStatus::Running- Server is reachable and returned a success code.LoggerStatus::Broken- Any failure occurred (DNS, Connection Refused, 404, 500, etc.).
Source§fn log(&self, message: Message)
fn log(&self, message: Message)
Enqueues a Message for asynchronous processing and delivery.
This is the primary entry point for recording logs. It performs two critical tasks:
- Monotonic Timestamping: Uses a “highwater” Mutex to ensure every message has a strictly increasing timestamp, preventing Loki out-of-order errors.
- Asynchronous Dispatch: Sends the message through an MPSC channel to the background worker.
§Thread Safety & Performance
This method is non-blocking (except for a very brief lock on the highwater
timestamp). If the background worker is overloaded or the channel is
disconnected, it triggers the Fallback immediately to avoid data loss.
§Parameters
message: The log entry containing level, target, and content.
Auto Trait Implementations§
impl !Freeze for Loki
impl !RefUnwindSafe for Loki
impl Send for Loki
impl Sync for Loki
impl Unpin for Loki
impl !UnwindSafe for Loki
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more