log4rs-mqtt

Crates.iolog4rs-mqtt
lib.rslog4rs-mqtt
version1.0.1
sourcesrc
created_at2023-09-20 14:49:07.780769
updated_at2023-09-26 16:58:21.706538
descriptionMQTT appender for log4rs based on paho MQTT
homepage
repositoryhttps://github.com/tclarke/log4rs-mqtt
max_upload_size
id978208
size25,013
Trevor R.H. Clarke (tclarke)

documentation

https://docs.rs/crate/log4rs-mqtt

README

crates.io MIT/Apache 2.0

log4rs-mqtt

log4rs-mqtt - MQTT appender for the log4rs based on PAHO MQTT.

Documentation on docs.rs

Features:

  • Specify the MQTT server to use.
  • Specify the MQTT topic used for logging.

Usage

Add this to your Cargo.toml:

[dependencies]
log4rs-mqtt = "1.0"

Initialization based on configuration file

Example configuration file:

appenders:
  mqtt:
    kind: mqtt
    mqtt_server: mqtt://mosquito.cluster.local:1883
    mqtt_client_id: log_client
    topic: logs
    qos: 1
    encoder:
      pattern: "{M} - {m}"
root:
  level: info
  appenders:
    - mqtt

Example code:

#[macro_use]
extern crate log;
extern crate log4rs;
extern crate log4rs_mqtt;

fn main() {
    let mut deserializers = log4rs::file::Deserializers::new();
    log4rs_mqtt::register(&mut deserializers);

    // Note that configuration file should have right extension, otherwise log4rs will fail to
    // recognize format.
    log4rs::init_file("test.yaml", deserializers).unwrap();

    info!("Example information message");
    warn!("Example warning message");
    error!("Example error message");
}

Manual initialization

Example code:

#[macro_use]
extern crate log;
extern crate log4rs;
extern crate log4rs_mqtt;

fn main() {
    // Use custom PatternEncoder to avoid duplicate timestamps in logs.
    let encoder = Box::new(log4rs::encode::pattern::PatternEncoder::new("{M} - {m}"));

    let appender = Box::new(
        log4rs_mqtt::MqttAppender::builder()
            .encoder(encoder)
            .mqtt_server("mqtt://mosquitto.cluster.local:1883")
            .mqtt_client_id("log_client")
            .qos(1)
            .topic("logs")
            .build(),
    );

    let config = log4rs::config::Config::builder()
        .appender(log4rs::config::Appender::builder().build(
            "mqtt",
            appender,
        ))
        .build(log4rs::config::Root::builder().appender("mqtt").build(
            log::LevelFilter::Info,
        ))
        .unwrap();
    log4rs::init_config(config).unwrap();

    info!("Example information message");
    warn!("Example warning message");
    error!("Example error message");
}
Commit count: 4

cargo fmt