Loki

Struct Loki 

Source
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 Message is 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

Source

pub fn new(config: LokiConfig) -> Box<Loki>

Creates a new LokiLogger using the StandardLokiService.

This is a convenience wrapper around Self::with_service.

Source

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:

  1. Computes the full Loki Push API endpoint.
  2. Wraps the provided service in an Arc for shared access between the logger and the worker.
  3. 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.

Source

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.
Source

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.

Source

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.

When the LokiLogger goes out of scope, the following sequence occurs:

  1. Channel Closure: The sender is dropped (None). This signals the background worker that no more messages will be sent.
  2. Worker Drain: The worker’s receiver.recv() will return an error once the channel is empty, allowing its loop to terminate naturally.
  3. 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§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl LoggerImpl for Loki

Source§

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
Source§

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:

  1. Monotonic Timestamping: Uses a “highwater” Mutex to ensure every message has a strictly increasing timestamp, preventing Loki out-of-order errors.
  2. 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.
Source§

fn as_any(&self) -> &dyn Any

Returns a reference to the underlying type as Any for downcasting.

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> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more