timber_rust/service/aws/msgformatter.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Dante Doménech Martinez dante19031999@gmail.com
3
4#![cfg(feature = "awscout")]
5#![cfg_attr(docsrs, doc(cfg(feature = "awscout")))]
6
7use crate::Message;
8use serde_json::json;
9
10
11/// Defines a strategy for converting a log message into a string format
12/// compatible with CloudWatch Logs.
13///
14/// Implementations of this trait determine how the structured log data
15/// (metadata, levels, and content) is serialized before transmission.
16pub trait MessageFormatter: Send + Sync {
17 /// Formats a single [`Message`] into its string representation.
18 fn format(&self, message: &Message) -> String;
19}
20
21/// The default formatter for CloudWatch messages.
22///
23/// This formatter serializes messages into a **JSON** string. This is considered
24/// a best practice for CloudWatch, as it enables advanced querying and filtering
25/// using CloudWatch Logs Insights.
26///
27/// # Output Example
28/// ```json
29/// {
30/// "level": "INFO",
31/// "msg": "Application started"
32/// }
33/// ```
34pub struct StandardMessageFormatter {}
35
36impl StandardMessageFormatter {
37 /// Creates a new instance of the default formatter.
38 pub fn new() -> Self {
39 Self {}
40 }
41}
42
43impl MessageFormatter for StandardMessageFormatter {
44 /// Converts the message into a JSON string containing the log level and content.
45 ///
46 /// The resulting string is what will be displayed in the "Message" column
47 /// of the CloudWatch Logs console.
48 fn format(&self, message: &Message) -> String {
49 json!({
50 "level": message.level().to_string(),
51 "msg": message.content().to_string(),
52 })
53 .to_string()
54 }
55}
56
57impl Default for StandardMessageFormatter {
58 fn default() -> Self {
59 Self{}
60 }
61}