From 99c7a3714c3111863f38ed037996f0f42ff7fbae Mon Sep 17 00:00:00 2001 From: Lalit Kumar Bhasin Date: Mon, 24 Jun 2024 17:34:28 -0700 Subject: [PATCH 1/8] initial commit --- opentelemetry-journald-logs/CHANGELOG.md | 3 + opentelemetry-journald-logs/CODEOWNERS | 5 + opentelemetry-journald-logs/Cargo.toml | 28 ++ opentelemetry-journald-logs/LICENSE | 201 ++++++++++++ opentelemetry-journald-logs/README.md | 14 + opentelemetry-journald-logs/build.rs | 3 + .../examples/basic-logs.rs | 29 ++ opentelemetry-journald-logs/src/lib.rs | 288 ++++++++++++++++++ 8 files changed, 571 insertions(+) create mode 100644 opentelemetry-journald-logs/CHANGELOG.md create mode 100644 opentelemetry-journald-logs/CODEOWNERS create mode 100644 opentelemetry-journald-logs/Cargo.toml create mode 100644 opentelemetry-journald-logs/LICENSE create mode 100644 opentelemetry-journald-logs/README.md create mode 100644 opentelemetry-journald-logs/build.rs create mode 100644 opentelemetry-journald-logs/examples/basic-logs.rs create mode 100644 opentelemetry-journald-logs/src/lib.rs 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..0b679676 --- /dev/null +++ b/opentelemetry-journald-logs/README.md @@ -0,0 +1,14 @@ +# Journald Log Exporter for OpenTelemetry + +This project provides a journald log exporter for OpenTelemetry, allowing logs to be sent to journald. Note that this exporter is experimental, and breaking changes are expected. The performance and stability improvements are required, and contributions are welcome. + +## 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/basic-logs.rs b/opentelemetry-journald-logs/examples/basic-logs.rs new file mode 100644 index 00000000..d25e8860 --- /dev/null +++ b/opentelemetry-journald-logs/examples/basic-logs.rs @@ -0,0 +1,29 @@ +// 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() + .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() +} + +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..aa04d467 --- /dev/null +++ b/opentelemetry-journald-logs/src/lib.rs @@ -0,0 +1,288 @@ +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 identifier(mut self, identifier: &str) -> Self { + self.identifier = Some(identifier.to_string()); + self + } + + pub fn message_size_limit(mut self, message_size_limit: usize) -> Self { + self.message_size_limit = Some(message_size_limit); + self + } + + pub fn attribute_prefix(mut self, attribute_prefix: Option) -> Self { + if let Some(prefix) = attribute_prefix { + self.attribute_prefix = Some(prefix.to_uppercase()); + } else { + self.attribute_prefix = None; + } + self + } + + pub fn json_format(mut self, json_format: bool) -> Self { + self.json_format = json_format; + self + } + + pub fn build(self) -> Result { + let identifier = self.identifier.ok_or("Identifier is required")?; + let message_size_limit = self + .message_size_limit + .ok_or("Message size limit is required")?; + Ok(JournaldLogExporter { + identifier: CString::new(identifier).map_err(|_| "Invalid identifier")?, + message_size_limit, + 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(); + let mut cstrings: 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(), + }); + cstrings.push(identifier_field); + 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()); + let message = CString::new(message_str).unwrap(); + iovecs.push(libc::iovec { + iov_base: message.as_ptr() as *mut c_void, + iov_len: message.as_bytes().len(), + }); + cstrings.push(message); + } + #[cfg(not(feature = "json"))] + { + return Err(std::io::Error::new( + std::io::ErrorKind::Unsupported, + "JSON format is not supported without the `json` feature", + )); + } + } else { + // Add the MESSAGE field + if let Some(body) = &log_data.record.body { + let formatted_body = format_any_value(body); + let message_str = format!("MESSAGE={}", formatted_body); + let message = CString::new(message_str).unwrap(); + iovecs.push(libc::iovec { + iov_base: message.as_ptr() as *mut c_void, + iov_len: message.as_bytes().len(), + }); + cstrings.push(message); + } + + // 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); + let attribute_str = if let Some(ref prefix) = self.attribute_prefix { + format!("{}{}={}", prefix, key_str, value_str) + } else { + format!("{}={}", key_str, value_str) + }; + let attribute = CString::new(attribute_str).unwrap(); + iovecs.push(libc::iovec { + iov_base: attribute.as_ptr() as *mut c_void, + iov_len: attribute.as_bytes().len(), + }); + cstrings.push(attribute); + } + } + } + + // 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(), + }); + cstrings.push(priority); + + 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(), |body| format_any_value(body)); + + 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() +} From abb1d99e4bf151717bd15f53d4cc1f2b0c68f178 Mon Sep 17 00:00:00 2001 From: Lalit Date: Mon, 24 Jun 2024 22:38:28 -0700 Subject: [PATCH 2/8] fix CI, docs enrich --- .github/workflows/ci.yml | 2 ++ opentelemetry-journald-logs/README.md | 6 ++++++ .../examples/basic-logs.rs | 2 +- opentelemetry-journald-logs/src/lib.rs | 2 +- opentelemetry-user-events-logs/README.md | 18 +++++++++--------- 5 files changed, 19 insertions(+), 11 deletions(-) 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/README.md b/opentelemetry-journald-logs/README.md index 0b679676..9c4ca6f9 100644 --- a/opentelemetry-journald-logs/README.md +++ b/opentelemetry-journald-logs/README.md @@ -1,5 +1,11 @@ # 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 project provides a journald log exporter for OpenTelemetry, allowing logs to be sent to journald. Note that this exporter is experimental, and breaking changes are expected. The performance and stability improvements are required, and contributions are welcome. ## Features diff --git a/opentelemetry-journald-logs/examples/basic-logs.rs b/opentelemetry-journald-logs/examples/basic-logs.rs index d25e8860..dc4c8b0b 100644 --- a/opentelemetry-journald-logs/examples/basic-logs.rs +++ b/opentelemetry-journald-logs/examples/basic-logs.rs @@ -11,7 +11,7 @@ fn init_logger() -> LoggerProvider { .identifier("opentelemetry-journal-exporter") .message_size_limit(4 * 1024) .attribute_prefix(Some("OTEL_".to_string())) - .json_format(true) //uncomment to log in json format + //.json_format(true) //uncomment to log in json format .build() .expect("Failed to build JournaldLogExporter"); diff --git a/opentelemetry-journald-logs/src/lib.rs b/opentelemetry-journald-logs/src/lib.rs index aa04d467..a94853ae 100644 --- a/opentelemetry-journald-logs/src/lib.rs +++ b/opentelemetry-journald-logs/src/lib.rs @@ -212,7 +212,7 @@ impl LogEntry { .record .body .as_ref() - .map_or_else(|| "".to_string(), |body| format_any_value(body)); + .map_or_else(|| "".to_string(), format_any_value); LogEntry { message, diff --git a/opentelemetry-user-events-logs/README.md b/opentelemetry-user-events-logs/README.md index d169dda9..dc8ca393 100644 --- a/opentelemetry-user-events-logs/README.md +++ b/opentelemetry-user-events-logs/README.md @@ -4,12 +4,12 @@ [splash]: https://raw.githubusercontent.com/open-telemetry/opentelemetry-rust/main/assets/logo-text.png -This crate contains a Log Exporter to export logs to Linux -[user_events](https://docs.kernel.org/trace/user_events.html), which is a -solution for user process tracing, similar to ETW (Event Tracing for Windows) on -Windows. It builds on top of the Linux Tracepoints, and so allows user processes -to create events and trace data that can be viewed via existing tools like -ftrace and perf. +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. + This kernel feature is supported started in Linux kernel 5.18 onwards. The feature enables - A faster path for tracing from user mode application utilizing kernel mode memory address space. @@ -19,9 +19,9 @@ This kernel feature is supported started in Linux kernel 5.18 onwards. The featu - Captured by the agents running locally, and listening for specific events withing user_events subsystem. - Or real-time monitoring using local Linux tool like [perf](https://perf.wiki.kernel.org/index.php/Main_Page) or ftrace. -[![Crates.io: opentelemetry-user-events-logs](https://img.shields.io/crates/v/opentelemetry-user-events-logs.svg)](https://crates.io/crates/opentelemetry-user-events-logs) -[![Documentation](https://docs.rs/opentelemetry-user-events-logs/badge.svg)](https://docs.rs/opentelemetry-user-events-logs) -[![LICENSE](https://img.shields.io/crates/l/opentelemetry-user-events-logs)](./LICENSE) +[![Crates.io: opentelemetry-journald-logs](https://img.shields.io/crates/v/opentelemetry-journald-logs.svg)](https://crates.io/crates/opentelemetry-journald-logs) +[![Documentation](https://docs.rs/opentelemetry-journald-logs/badge.svg)](https://docs.rs/opentelemetry-journald-logs) +[![LICENSE](https://img.shields.io/crates/l/opentelemetry-journald-logs)](./LICENSE) [![GitHub Actions CI](https://github.com/open-telemetry/opentelemetry-rust/workflows/CI/badge.svg)](https://github.com/open-telemetry/opentelemetry-rust/actions?query=workflow%3ACI+branch%3Amain) [![Slack](https://img.shields.io/badge/slack-@cncf/otel/rust-brightgreen.svg?logo=slack)](https://cloud-native.slack.com/archives/C03GDP0H023) From ddf0bc4c05696e20416a893bad19bd85d26f70b4 Mon Sep 17 00:00:00 2001 From: Lalit Date: Mon, 24 Jun 2024 23:15:33 -0700 Subject: [PATCH 3/8] add example README.md --- opentelemetry-journald-logs/README.md | 9 +- .../examples/README.md | 93 +++++++++++++++++++ .../examples/basic-logs.rs | 2 +- opentelemetry-user-events-logs/README.md | 18 ++-- 4 files changed, 111 insertions(+), 11 deletions(-) create mode 100644 opentelemetry-journald-logs/examples/README.md diff --git a/opentelemetry-journald-logs/README.md b/opentelemetry-journald-logs/README.md index 9c4ca6f9..4c4bfd9b 100644 --- a/opentelemetry-journald-logs/README.md +++ b/opentelemetry-journald-logs/README.md @@ -6,7 +6,14 @@ [splash]: https://raw.githubusercontent.com/open-telemetry/opentelemetry-rust/main/assets/logo-text.png -This project provides a journald log exporter for OpenTelemetry, allowing logs to be sent to journald. Note that this exporter is experimental, and breaking changes are expected. The performance and stability improvements are required, and contributions are welcome. +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 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 index dc4c8b0b..d25e8860 100644 --- a/opentelemetry-journald-logs/examples/basic-logs.rs +++ b/opentelemetry-journald-logs/examples/basic-logs.rs @@ -11,7 +11,7 @@ fn init_logger() -> LoggerProvider { .identifier("opentelemetry-journal-exporter") .message_size_limit(4 * 1024) .attribute_prefix(Some("OTEL_".to_string())) - //.json_format(true) //uncomment to log in json format + .json_format(true) //uncomment to log in json format .build() .expect("Failed to build JournaldLogExporter"); diff --git a/opentelemetry-user-events-logs/README.md b/opentelemetry-user-events-logs/README.md index dc8ca393..d169dda9 100644 --- a/opentelemetry-user-events-logs/README.md +++ b/opentelemetry-user-events-logs/README.md @@ -4,12 +4,12 @@ [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. - +This crate contains a Log Exporter to export logs to Linux +[user_events](https://docs.kernel.org/trace/user_events.html), which is a +solution for user process tracing, similar to ETW (Event Tracing for Windows) on +Windows. It builds on top of the Linux Tracepoints, and so allows user processes +to create events and trace data that can be viewed via existing tools like +ftrace and perf. This kernel feature is supported started in Linux kernel 5.18 onwards. The feature enables - A faster path for tracing from user mode application utilizing kernel mode memory address space. @@ -19,9 +19,9 @@ This kernel feature is supported started in Linux kernel 5.18 onwards. The featu - Captured by the agents running locally, and listening for specific events withing user_events subsystem. - Or real-time monitoring using local Linux tool like [perf](https://perf.wiki.kernel.org/index.php/Main_Page) or ftrace. -[![Crates.io: opentelemetry-journald-logs](https://img.shields.io/crates/v/opentelemetry-journald-logs.svg)](https://crates.io/crates/opentelemetry-journald-logs) -[![Documentation](https://docs.rs/opentelemetry-journald-logs/badge.svg)](https://docs.rs/opentelemetry-journald-logs) -[![LICENSE](https://img.shields.io/crates/l/opentelemetry-journald-logs)](./LICENSE) +[![Crates.io: opentelemetry-user-events-logs](https://img.shields.io/crates/v/opentelemetry-user-events-logs.svg)](https://crates.io/crates/opentelemetry-user-events-logs) +[![Documentation](https://docs.rs/opentelemetry-user-events-logs/badge.svg)](https://docs.rs/opentelemetry-user-events-logs) +[![LICENSE](https://img.shields.io/crates/l/opentelemetry-user-events-logs)](./LICENSE) [![GitHub Actions CI](https://github.com/open-telemetry/opentelemetry-rust/workflows/CI/badge.svg)](https://github.com/open-telemetry/opentelemetry-rust/actions?query=workflow%3ACI+branch%3Amain) [![Slack](https://img.shields.io/badge/slack-@cncf/otel/rust-brightgreen.svg?logo=slack)](https://cloud-native.slack.com/archives/C03GDP0H023) From d8b496c11da95b49ab1eed0a339c479440001494 Mon Sep 17 00:00:00 2001 From: Lalit Kumar Bhasin Date: Tue, 25 Jun 2024 12:08:53 -0700 Subject: [PATCH 4/8] Update basic-logs.rs comment the json_format option. --- opentelemetry-journald-logs/examples/basic-logs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/opentelemetry-journald-logs/examples/basic-logs.rs b/opentelemetry-journald-logs/examples/basic-logs.rs index d25e8860..dc4c8b0b 100644 --- a/opentelemetry-journald-logs/examples/basic-logs.rs +++ b/opentelemetry-journald-logs/examples/basic-logs.rs @@ -11,7 +11,7 @@ fn init_logger() -> LoggerProvider { .identifier("opentelemetry-journal-exporter") .message_size_limit(4 * 1024) .attribute_prefix(Some("OTEL_".to_string())) - .json_format(true) //uncomment to log in json format + //.json_format(true) //uncomment to log in json format .build() .expect("Failed to build JournaldLogExporter"); From 958e1af6920e934f5c6ed964e8f1ead9a9120d74 Mon Sep 17 00:00:00 2001 From: Lalit Date: Tue, 25 Jun 2024 17:52:34 -0700 Subject: [PATCH 5/8] remove the cstring vector, and make CString to upper scope --- opentelemetry-journald-logs/src/lib.rs | 45 ++++++++++++++------------ 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/opentelemetry-journald-logs/src/lib.rs b/opentelemetry-journald-logs/src/lib.rs index a94853ae..dbc6c134 100644 --- a/opentelemetry-journald-logs/src/lib.rs +++ b/opentelemetry-journald-logs/src/lib.rs @@ -87,7 +87,6 @@ impl JournaldLogExporter { fn send_log_to_journald(&self, log_data: &LogData) -> Result<(), std::io::Error> { let mut iovecs: Vec = Vec::new(); - let mut cstrings: Vec = Vec::new(); // Add the SYSLOG_IDENTIFIER field let identifier_str = format!("SYSLOG_IDENTIFIER={}", self.identifier.to_str().unwrap()); @@ -96,19 +95,18 @@ impl JournaldLogExporter { iov_base: identifier_field.as_ptr() as *mut c_void, iov_len: identifier_field.as_bytes().len(), }); - cstrings.push(identifier_field); + + // 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()); - let message = CString::new(message_str).unwrap(); - iovecs.push(libc::iovec { - iov_base: message.as_ptr() as *mut c_void, - iov_len: message.as_bytes().len(), - }); - cstrings.push(message); + message = Some(CString::new(message_str).unwrap()); } #[cfg(not(feature = "json"))] { @@ -122,12 +120,7 @@ impl JournaldLogExporter { if let Some(body) = &log_data.record.body { let formatted_body = format_any_value(body); let message_str = format!("MESSAGE={}", formatted_body); - let message = CString::new(message_str).unwrap(); - iovecs.push(libc::iovec { - iov_base: message.as_ptr() as *mut c_void, - iov_len: message.as_bytes().len(), - }); - cstrings.push(message); + message = Some(CString::new(message_str).unwrap()); } // Add other attributes @@ -140,16 +133,27 @@ impl JournaldLogExporter { } else { format!("{}={}", key_str, value_str) }; - let attribute = CString::new(attribute_str).unwrap(); - iovecs.push(libc::iovec { - iov_base: attribute.as_ptr() as *mut c_void, - iov_len: attribute.as_bytes().len(), - }); - cstrings.push(attribute); + attributes.push(CString::new(attribute_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={}", @@ -160,7 +164,6 @@ impl JournaldLogExporter { iov_base: priority.as_ptr() as *mut c_void, iov_len: priority.as_bytes().len(), }); - cstrings.push(priority); let total_size: usize = iovecs.iter().map(|iov| iov.iov_len).sum(); let size_exceeded = total_size > self.message_size_limit; From b2485160978cc490fdea7cc5d053c1388e4ccdd0 Mon Sep 17 00:00:00 2001 From: Lalit Date: Tue, 25 Jun 2024 18:24:52 -0700 Subject: [PATCH 6/8] perf improvement in message copy --- .../examples/basic-logs.rs | 2 +- opentelemetry-journald-logs/src/lib.rs | 19 ++++++++++--------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/opentelemetry-journald-logs/examples/basic-logs.rs b/opentelemetry-journald-logs/examples/basic-logs.rs index dc4c8b0b..d25e8860 100644 --- a/opentelemetry-journald-logs/examples/basic-logs.rs +++ b/opentelemetry-journald-logs/examples/basic-logs.rs @@ -11,7 +11,7 @@ fn init_logger() -> LoggerProvider { .identifier("opentelemetry-journal-exporter") .message_size_limit(4 * 1024) .attribute_prefix(Some("OTEL_".to_string())) - //.json_format(true) //uncomment to log in json format + .json_format(true) //uncomment to log in json format .build() .expect("Failed to build JournaldLogExporter"); diff --git a/opentelemetry-journald-logs/src/lib.rs b/opentelemetry-journald-logs/src/lib.rs index dbc6c134..4538b0d5 100644 --- a/opentelemetry-journald-logs/src/lib.rs +++ b/opentelemetry-journald-logs/src/lib.rs @@ -118,9 +118,8 @@ impl JournaldLogExporter { } else { // Add the MESSAGE field if let Some(body) = &log_data.record.body { - let formatted_body = format_any_value(body); - let message_str = format!("MESSAGE={}", formatted_body); - message = Some(CString::new(message_str).unwrap()); + message = + Some(CString::new(format!("MESSAGE={}", format_any_value(body))).unwrap()); } // Add other attributes @@ -128,12 +127,14 @@ impl JournaldLogExporter { 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_str = if let Some(ref prefix) = self.attribute_prefix { - format!("{}{}={}", prefix, key_str, value_str) - } else { - format!("{}={}", key_str, value_str) - }; - attributes.push(CString::new(attribute_str).unwrap()); + 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(), + ); } } } From 1f50bcbceb0a0cec5a5d9fbc1844453041b6640e Mon Sep 17 00:00:00 2001 From: Lalit Kumar Bhasin Date: Thu, 5 Sep 2024 02:36:53 -0700 Subject: [PATCH 7/8] review comments --- .../examples/basic-logs.rs | 11 +++--- opentelemetry-journald-logs/src/lib.rs | 38 +++++++++---------- 2 files changed, 24 insertions(+), 25 deletions(-) diff --git a/opentelemetry-journald-logs/examples/basic-logs.rs b/opentelemetry-journald-logs/examples/basic-logs.rs index d25e8860..791856fc 100644 --- a/opentelemetry-journald-logs/examples/basic-logs.rs +++ b/opentelemetry-journald-logs/examples/basic-logs.rs @@ -8,12 +8,11 @@ use tracing_subscriber::prelude::*; 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"); + .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) diff --git a/opentelemetry-journald-logs/src/lib.rs b/opentelemetry-journald-logs/src/lib.rs index 4538b0d5..a77526e1 100644 --- a/opentelemetry-journald-logs/src/lib.rs +++ b/opentelemetry-journald-logs/src/lib.rs @@ -25,41 +25,41 @@ pub struct JournaldLogExporterBuilder { } impl JournaldLogExporterBuilder { - pub fn identifier(mut self, identifier: &str) -> Self { + pub fn with_identifier(mut self, identifier: &str) -> Self { self.identifier = Some(identifier.to_string()); self } - pub fn message_size_limit(mut self, message_size_limit: usize) -> Self { - self.message_size_limit = Some(message_size_limit); + 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 attribute_prefix(mut self, attribute_prefix: Option) -> Self { - if let Some(prefix) = attribute_prefix { - self.attribute_prefix = Some(prefix.to_uppercase()); - } else { - self.attribute_prefix = None; - } + pub fn with_attribute_prefix(mut self, attribute_prefix: &str) -> Self { + self.attribute_prefix = Some(attribute_prefix.to_string().to_uppercase()); self } - pub fn json_format(mut self, json_format: bool) -> Self { + pub fn with_json_format(mut self, json_format: bool) -> Self { self.json_format = json_format; self } - pub fn build(self) -> Result { - let identifier = self.identifier.ok_or("Identifier is required")?; - let message_size_limit = self - .message_size_limit - .ok_or("Message size limit is required")?; - Ok(JournaldLogExporter { - identifier: CString::new(identifier).map_err(|_| "Invalid identifier")?, - message_size_limit, + 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, - }) + } } } From 939a39f6a026b072c1feb179696af234cb3d7196 Mon Sep 17 00:00:00 2001 From: Lalit Kumar Bhasin Date: Thu, 5 Sep 2024 02:44:07 -0700 Subject: [PATCH 8/8] handle json config inside builder --- opentelemetry-journald-logs/src/lib.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/opentelemetry-journald-logs/src/lib.rs b/opentelemetry-journald-logs/src/lib.rs index a77526e1..85a65e59 100644 --- a/opentelemetry-journald-logs/src/lib.rs +++ b/opentelemetry-journald-logs/src/lib.rs @@ -43,7 +43,15 @@ impl JournaldLogExporterBuilder { } pub fn with_json_format(mut self, json_format: bool) -> Self { - self.json_format = json_format; + #[cfg(feature = "json")] + { + self.json_format = json_format; + } + #[cfg(not(feature = "json"))] + { + let _ = json_format; // Prevents unused variable warning + self.json_format = false; + } self } @@ -108,13 +116,6 @@ impl JournaldLogExporter { let message_str = format!("MESSAGE={}", serde_json::to_string(&log_entry).unwrap()); message = Some(CString::new(message_str).unwrap()); } - #[cfg(not(feature = "json"))] - { - return Err(std::io::Error::new( - std::io::ErrorKind::Unsupported, - "JSON format is not supported without the `json` feature", - )); - } } else { // Add the MESSAGE field if let Some(body) = &log_data.record.body {