[pbs-devel] [PATCH proxmox] router: Added `init_syslog_logger()` function

Gabriel Goller g.goller at proxmox.com
Mon Aug 21 13:19:38 CEST 2023


This function inits the `syslog` logger and sets the minimal level
to the value of the environment variable passed. The default level
is `info`. Added the `log` and `syslog` crates.

Signed-off-by: Gabriel Goller <g.goller at proxmox.com>
---
 Cargo.toml                   |  1 +
 proxmox-router/Cargo.toml    |  2 ++
 proxmox-router/src/router.rs | 25 +++++++++++++++++++++++--
 3 files changed, 26 insertions(+), 2 deletions(-)

diff --git a/Cargo.toml b/Cargo.toml
index e334ac1..980a9d8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -84,6 +84,7 @@ url = "2.2"
 walkdir = "2"
 webauthn-rs = "0.3"
 zstd = { version = "0.12", features = [ "bindgen" ] }
+syslog = "6"
 
 # workspace dependencies
 proxmox-api-macro = { version = "1.0.5", path = "proxmox-api-macro" }
diff --git a/proxmox-router/Cargo.toml b/proxmox-router/Cargo.toml
index 1c08ce2..81a8e8c 100644
--- a/proxmox-router/Cargo.toml
+++ b/proxmox-router/Cargo.toml
@@ -19,6 +19,8 @@ percent-encoding.workspace = true
 serde_json.workspace = true
 serde.workspace = true
 unicode-width ="0.1.8"
+syslog = "6"
+log = "0.4.17"
 
 # cli:
 tokio = { workspace = true, features = [], optional = true }
diff --git a/proxmox-router/src/router.rs b/proxmox-router/src/router.rs
index e9a669a..b0a75d7 100644
--- a/proxmox-router/src/router.rs
+++ b/proxmox-router/src/router.rs
@@ -1,9 +1,9 @@
 use std::collections::HashMap;
-use std::fmt;
 use std::future::Future;
 use std::pin::Pin;
+use std::{env, fmt};
 
-use anyhow::Error;
+use anyhow::{anyhow, bail, Error};
 #[cfg(feature = "server")]
 use http::request::Parts;
 #[cfg(feature = "server")]
@@ -580,3 +580,24 @@ impl ApiMethod {
         self
     }
 }
+
+pub fn init_syslog_logger(
+    application_name: &str,
+    env_var_name: &str,
+    default_log_level: log::LevelFilter,
+) -> Result<(), anyhow::Error> {
+    let mut log_level = default_log_level;
+    if let Ok(v) = env::var(env_var_name) {
+        if let Ok(l) = v.parse::<log::LevelFilter>() {
+            log_level = l;
+        }
+    }
+    if let Err(e) = syslog::init(
+        syslog::Facility::LOG_DAEMON,
+        log_level,
+        Some(application_name),
+    ) {
+        bail!(e.description().to_owned());
+    };
+    Ok(())
+}
-- 
2.39.2






More information about the pbs-devel mailing list