diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7a900643..0d31b013 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,6 +21,8 @@ jobs: sudo rm -rf /usr/local/lib/android sudo rm -rf /usr/share/dotnet df -h + - name: Install libsystemd (required by opentelemetry-journald-logs) + run: sudo apt-get install -y libsystemd-dev - uses: actions/checkout@v1 with: submodules: true diff --git a/opentelemetry-journald-logs/CHANGELOG.md b/opentelemetry-journald-logs/CHANGELOG.md new file mode 100644 index 00000000..4984a94f --- /dev/null +++ b/opentelemetry-journald-logs/CHANGELOG.md @@ -0,0 +1,3 @@ +# Changelog + +## vNext \ No newline at end of file diff --git a/opentelemetry-journald-logs/CODEOWNERS b/opentelemetry-journald-logs/CODEOWNERS new file mode 100644 index 00000000..633c7384 --- /dev/null +++ b/opentelemetry-journald-logs/CODEOWNERS @@ -0,0 +1,5 @@ +# Code owners file. +# This file controls who is tagged for review for any given pull request. + +# For anything not explicitly taken by someone else: +* @open-telemetry/rust-approvers \ No newline at end of file diff --git a/opentelemetry-journald-logs/Cargo.toml b/opentelemetry-journald-logs/Cargo.toml new file mode 100644 index 00000000..006183aa --- /dev/null +++ b/opentelemetry-journald-logs/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "opentelemetry-journald-logs" +version = "0.1.0" +edition = "2021" +keywords = ["opentelemetry", "journald", "logs", "tracing"] +description = "OpenTelemetry logs exporter for journald" +repository = "https://github.com/open-telemetry/opentelemetry-rust-contrib/tree/main/opentelemetry-journald-logs" +homepage = "https://github.com/open-telemetry/opentelemetry-rust-contrib/tree/main/opentelemetry-journald-logs" +license = "Apache-2.0" + +[dependencies] +opentelemetry = { workspace = true, features = ["logs"] } +opentelemetry_sdk = { workspace = true, features = ["logs"] } +libc = "0.2" +async-trait = "0.1" +serde = { version = "1.0", features = ["derive"], optional =true} +serde_json = {version = "1.0", optional = true} + +[dev-dependencies] +opentelemetry-appender-tracing = { workspace = true } +tracing = { version = "0.1", default-features = false, features = ["std"] } +tracing-core = "0.1.31" +tracing-subscriber = { version = "0.3.0", default-features = false, features = ["registry", "std"] } + +[features] +logs_level_enabled = ["opentelemetry/logs_level_enabled", "opentelemetry_sdk/logs_level_enabled"] +default = ["logs_level_enabled"] +json = ["serde", "serde_json"] \ No newline at end of file diff --git a/opentelemetry-journald-logs/LICENSE b/opentelemetry-journald-logs/LICENSE new file mode 100644 index 00000000..f49a4e16 --- /dev/null +++ b/opentelemetry-journald-logs/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/opentelemetry-journald-logs/README.md b/opentelemetry-journald-logs/README.md new file mode 100644 index 00000000..4c4bfd9b --- /dev/null +++ b/opentelemetry-journald-logs/README.md @@ -0,0 +1,27 @@ +# Journald Log Exporter for OpenTelemetry + + +![OpenTelemetry — An observability framework for cloud-native software.][splash] + +[splash]: https://raw.githubusercontent.com/open-telemetry/opentelemetry-rust/main/assets/logo-text.png + + +This crate provides a Log Exporter to export logs to the systemd journal (journald) using the OpenTelemetry framework. The exporter supports both plain text and JSON formats for log entries and includes options for setting message size limits, identifiers, and attribute prefixes. + +Journald is a system service for collecting and storing log data. It is a part of systemd, a suite of system management daemons, libraries, and utilities designed for Linux. This exporter allows OpenTelemetry to send log data directly to journald, enabling seamless integration with systemd's logging infrastructure. + +This exporter requires libsystemd for sending log entries to the journald daemon. + +[!CAUTION] +The exporter is in an experimental stage, and breaking changes may occur. Performance and stability improvements may be needed, and we welcome contributions. + +## Features + +- Export OpenTelemetry logs to journald. +- Optionally serialize logs and attributes as JSON. +- Configurable message size limit. +- Configurable attribute prefix. + +## Installation and Usage + + Refer to the example under examples directory. \ No newline at end of file diff --git a/opentelemetry-journald-logs/build.rs b/opentelemetry-journald-logs/build.rs new file mode 100644 index 00000000..e2f05ed3 --- /dev/null +++ b/opentelemetry-journald-logs/build.rs @@ -0,0 +1,3 @@ +fn main() { + println!("cargo:rustc-link-lib=systemd"); +} diff --git a/opentelemetry-journald-logs/examples/README.md b/opentelemetry-journald-logs/examples/README.md new file mode 100644 index 00000000..5e1b55b6 --- /dev/null +++ b/opentelemetry-journald-logs/examples/README.md @@ -0,0 +1,93 @@ +# Example: Basic Logs + +This example demonstrates how to use the `opentelemetry-journald-logs` crate to export logs to the systemd journal (journald). + +## Running the Example + +To run this example, use the following command: + +```sh +cargo run --example basic-logs +``` + +## Running with JSON Format + +To export all log properties and attributes as JSON instead of key-value pairs, uncomment the `.json_format(true)` line in the init_logger function and use the following command: + +```rust +fn init_logger() -> LoggerProvider { + let exporter = JournaldLogExporter::builder() + .identifier("opentelemetry-journal-exporter") + .message_size_limit(4 * 1024) + .attribute_prefix(Some("OTEL_".to_string())) + .json_format(true) // uncomment to log in JSON format + .build() + .expect("Failed to build JournaldLogExporter"); + + LoggerProvider::builder() + .with_simple_exporter(exporter) + .build() +} +``` +Then run: + +```sh +cargo run --example basic-logs --features="json" +``` + +## Viewing the Logs + +To see the logs in the systemd journal, use the following command: + +```sh +journalctl -o json-seq --follow +``` + +### Example Output (without JSON): + +```json +{ + "MESSAGE": "my test message", + "OTEL_USER_ID": "5678", + "_TRANSPORT": "journal", + "_COMM": "basic-logs", + "_UID": "1000", + "__CURSOR": "s=b6ec4d2d7b2f458e92a4935c7915a430;i=23f19;b=92f3c733ee9a41e6a48eb22e1b60d6b5;m=154ca4caa6;t=61bb0be5fd085;x=962d19517545c0b1", + "_PID": "251476", + "_MACHINE_ID": "38786fbba498f16c66a525b6642cf555", + "__REALTIME_TIMESTAMP": "1719295782408325", + "__MONOTONIC_TIMESTAMP": "91480181414", + "_SOURCE_REALTIME_TIMESTAMP": "1719295782408217", + "_BOOT_ID": "92f3c733ee9a41e6a48eb22e1b60d6b5", + "_CAP_EFFECTIVE": "0", + "_HOSTNAME": "DESKTOP-D0BLHPQ", + "SYSLOG_IDENTIFIER": "opentelemetry-journal-exporter", + "OTEL_NAME": "event opentelemetry-journald-logs/examples/basic-logs.rs:28", + "PRIORITY": "6", + "OTEL_EVENT_ID": "1234", + "_GID": "1001" +} +``` + +### Example Output (with JSON): + +```json +{ + "SYSLOG_IDENTIFIER": "opentelemetry-journal-exporter", + "_UID": "1000", + "_HOSTNAME": "DESKTOP-D0BLHPQ", + "_PID": "251979", + "MESSAGE": "{\"message\":\"my test message\",\"OTEL_NAME\":\"event opentelemetry-journald-logs/examples/basic-logs.rs:28\",\"OTEL_EVENT_ID\":\"1234\",\"OTEL_USER_ID\":\"5678\"}", + "_MACHINE_ID": "38786fbba498f16c66a525b6642cf555", + "__MONOTONIC_TIMESTAMP": "91646562711", + "_COMM": "basic-logs", + "_TRANSPORT": "journal", + "PRIORITY": "6", + "_GID": "1001", + "_SOURCE_REALTIME_TIMESTAMP": "1719295948789586", + "_CAP_EFFECTIVE": "0", + "_BOOT_ID": "92f3c733ee9a41e6a48eb22e1b60d6b5", + "__CURSOR": "s=b6ec4d2d7b2f458e92a4935c7915a430;i=23f1a;b=92f3c733ee9a41e6a48eb22e1b60d6b5;m=15568f9197;t=61bb0c84a9776;x=8ee7deaebbd340de", + "__REALTIME_TIMESTAMP": "1719295948789622" +} +``` diff --git a/opentelemetry-journald-logs/examples/basic-logs.rs b/opentelemetry-journald-logs/examples/basic-logs.rs new file mode 100644 index 00000000..791856fc --- /dev/null +++ b/opentelemetry-journald-logs/examples/basic-logs.rs @@ -0,0 +1,28 @@ +// cargo run --example basic-logs + +use opentelemetry_appender_tracing::layer; +use opentelemetry_journald_logs::JournaldLogExporter; +use opentelemetry_sdk::logs::LoggerProvider; +use tracing::info; +use tracing_subscriber::prelude::*; + +fn init_logger() -> LoggerProvider { + let exporter = JournaldLogExporter::builder() + .with_identifier("opentelemetry-journal-exporter") + .with_message_size_limit(4 * 1024) + .with_attribute_prefix("OTEL") + //.with_json_format(true) //uncomment to log in json format + .build(); + + LoggerProvider::builder() + .with_simple_exporter(exporter) + .build() +} + +fn main() { + let logger_provider = init_logger(); + let layer = layer::OpenTelemetryTracingBridge::new(&logger_provider); + tracing_subscriber::registry().with(layer).init(); + + info!(event_id = 1234, user_id = 5678, "my test message"); +} diff --git a/opentelemetry-journald-logs/src/lib.rs b/opentelemetry-journald-logs/src/lib.rs new file mode 100644 index 00000000..85a65e59 --- /dev/null +++ b/opentelemetry-journald-logs/src/lib.rs @@ -0,0 +1,293 @@ +use async_trait::async_trait; +use libc::{c_int, c_void}; +use opentelemetry::logs::AnyValue; +use std::ffi::CString; +use std::fmt::Debug; + +use opentelemetry::logs::LogError; +use opentelemetry_sdk::export::logs::{LogData, LogExporter}; + +use opentelemetry::logs::Severity; + +#[cfg(feature = "json")] +use serde::Serialize; + +extern "C" { + fn sd_journal_sendv(iov: *const libc::iovec, n: libc::c_int) -> libc::c_int; +} + +#[derive(Default)] +pub struct JournaldLogExporterBuilder { + identifier: Option, + message_size_limit: Option, + attribute_prefix: Option, + json_format: bool, +} + +impl JournaldLogExporterBuilder { + pub fn with_identifier(mut self, identifier: &str) -> Self { + self.identifier = Some(identifier.to_string()); + self + } + + pub fn with_message_size_limit(mut self, message_size_limit: usize) -> Self { + if message_size_limit > 0 { + self.message_size_limit = Some(message_size_limit); + } + self + } + + pub fn with_attribute_prefix(mut self, attribute_prefix: &str) -> Self { + self.attribute_prefix = Some(attribute_prefix.to_string().to_uppercase()); + self + } + + pub fn with_json_format(mut self, json_format: bool) -> Self { + #[cfg(feature = "json")] + { + self.json_format = json_format; + } + #[cfg(not(feature = "json"))] + { + let _ = json_format; // Prevents unused variable warning + self.json_format = false; + } + self + } + + pub fn build(self) -> JournaldLogExporter { + JournaldLogExporter { + identifier: CString::new( + self.identifier + .as_deref() + .filter(|s| !s.is_empty()) + .unwrap_or(""), + ) + .unwrap(), + message_size_limit: self.message_size_limit.unwrap_or(0), + attribute_prefix: self.attribute_prefix, + json_format: self.json_format, + } + } +} + +#[derive(Debug)] +pub struct JournaldLogExporter { + identifier: CString, + message_size_limit: usize, + attribute_prefix: Option, + json_format: bool, +} + +impl JournaldLogExporter { + pub fn builder() -> JournaldLogExporterBuilder { + JournaldLogExporterBuilder::default() + } + + fn send_to_journald(&self, iovecs: &[libc::iovec]) -> Result<(), std::io::Error> { + let ret = unsafe { sd_journal_sendv(iovecs.as_ptr(), iovecs.len() as c_int) }; + if ret < 0 { + Err(std::io::Error::last_os_error()) + } else { + Ok(()) + } + } + + fn send_log_to_journald(&self, log_data: &LogData) -> Result<(), std::io::Error> { + let mut iovecs: Vec = Vec::new(); + + // Add the SYSLOG_IDENTIFIER field + let identifier_str = format!("SYSLOG_IDENTIFIER={}", self.identifier.to_str().unwrap()); + let identifier_field = CString::new(identifier_str).unwrap(); + iovecs.push(libc::iovec { + iov_base: identifier_field.as_ptr() as *mut c_void, + iov_len: identifier_field.as_bytes().len(), + }); + + // Initialize potential message and attributes outside conditional blocks + let mut message: Option = None; + let mut attributes: Vec = Vec::new(); + + if self.json_format { + #[cfg(feature = "json")] + { + // Serialize message and attributes as JSON + let log_entry = LogEntry::from_log_data(log_data, self.attribute_prefix.clone()); + let message_str = format!("MESSAGE={}", serde_json::to_string(&log_entry).unwrap()); + message = Some(CString::new(message_str).unwrap()); + } + } else { + // Add the MESSAGE field + if let Some(body) = &log_data.record.body { + message = + Some(CString::new(format!("MESSAGE={}", format_any_value(body))).unwrap()); + } + + // Add other attributes + if let Some(attr_list) = &log_data.record.attributes { + for (key, value) in attr_list.iter() { + let key_str = sanitize_field_name(key.as_str()); + let value_str = format_any_value(value); + attributes.push( + CString::new(if let Some(ref prefix) = self.attribute_prefix { + format!("{}{}={}", prefix, key_str, value_str) + } else { + format!("{}={}", key_str, value_str) + }) + .unwrap(), + ); + } + } + } + + // Add the message to iovecs if it was set + if let Some(msg) = &message { + iovecs.push(libc::iovec { + iov_base: msg.as_ptr() as *mut c_void, + iov_len: msg.as_bytes().len(), + }); + } + + // Add attributes to iovecs + for attribute in &attributes { + iovecs.push(libc::iovec { + iov_base: attribute.as_ptr() as *mut c_void, + iov_len: attribute.as_bytes().len(), + }); + } + + // Add the PRIORITY field + let priority_str = format!( + "PRIORITY={}", + get_priority(&log_data.record.severity_number.unwrap_or(Severity::Info)) + ); + let priority = CString::new(priority_str).unwrap(); + iovecs.push(libc::iovec { + iov_base: priority.as_ptr() as *mut c_void, + iov_len: priority.as_bytes().len(), + }); + + let total_size: usize = iovecs.iter().map(|iov| iov.iov_len).sum(); + let size_exceeded = total_size > self.message_size_limit; + + // Try to send to journald regardless of the size + let send_result = self.send_to_journald(&iovecs); + + if size_exceeded { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!( + "Log message size {} exceeds the limit of {} bytes", + total_size, self.message_size_limit + ), + )); + } + + send_result + } +} + +#[cfg(feature = "json")] +#[derive(Serialize)] +struct LogEntry { + message: String, + #[serde(flatten)] + attributes: std::collections::HashMap, +} + +#[cfg(feature = "json")] +impl LogEntry { + fn from_log_data(log_data: &LogData, attribute_prefix: Option) -> Self { + let mut attributes = std::collections::HashMap::new(); + + if let Some(attr_list) = &log_data.record.attributes { + for (key, value) in attr_list.iter() { + let key_str = sanitize_field_name(key.as_str()); + let value_str = format_any_value(value); + let attribute_key = if let Some(ref prefix) = attribute_prefix { + format!("{}{}", prefix, key_str) + } else { + key_str + }; + attributes.insert(attribute_key, value_str); + } + } + + let message = log_data + .record + .body + .as_ref() + .map_or_else(|| "".to_string(), format_any_value); + + LogEntry { + message, + attributes, + } + } +} + +fn format_any_value(value: &AnyValue) -> String { + match value { + AnyValue::Int(v) => v.to_string(), + AnyValue::Double(v) => v.to_string(), + AnyValue::String(v) => v.to_string(), + AnyValue::Boolean(v) => v.to_string(), + AnyValue::Bytes(v) => format!("{:?}", v), + AnyValue::ListAny(values) => { + let elements: Vec = values.iter().map(format_any_value).collect(); + format!("[{}]", elements.join(", ")) + } + AnyValue::Map(map) => { + let entries: Vec = map + .iter() + .map(|(k, v)| format!("{}: {}", k, format_any_value(v))) + .collect(); + format!("{{{}}}", entries.join(", ")) + } + } +} + +fn get_priority(severity: &Severity) -> i32 { + match severity { + Severity::Debug | Severity::Debug2 | Severity::Debug3 | Severity::Debug4 => 7, // debug + Severity::Info | Severity::Info2 | Severity::Info3 | Severity::Info4 => 6, // info + Severity::Warn | Severity::Warn2 | Severity::Warn3 | Severity::Warn4 => 4, // warning + Severity::Error | Severity::Error2 | Severity::Error3 | Severity::Error4 => 3, // error + Severity::Fatal | Severity::Fatal2 | Severity::Fatal3 | Severity::Fatal4 => 2, // critical + _ => 5, // notice (default) + } +} + +#[async_trait] +impl LogExporter for JournaldLogExporter { + async fn export(&mut self, batch: Vec) -> Result<(), LogError> { + let mut partial_failure = false; + for log in batch { + match self.send_log_to_journald(&log) { + Ok(_) => (), + Err(e) => { + if e.kind() == std::io::ErrorKind::InvalidData { + partial_failure = true; + } else { + return Err(LogError::Other(Box::new(e))); + } + } + } + } + if partial_failure { + return Err(LogError::from( + "Some log messages exceeded the size limit and were not exported", + )); + } + Ok(()) + } +} + +fn sanitize_field_name(name: &str) -> String { + name.chars() + .map(|c| if c == '.' { '_' } else { c }) + .skip_while(|&c| c == '_') + .filter(|&c| c == '_' || c.is_ascii_alphanumeric()) + .collect::() + .to_uppercase() +}