syslog_rs/formatters/
syslog_3146.rs

1/*-
2 * syslog-rs - a syslog client translated from libc to rust
3 * 
4 * Copyright 2025 Aleksandr Morozov
5 * 
6 * The syslog-rs crate can be redistributed and/or modified
7 * under the terms of either of the following licenses:
8 *
9 *   1. the Mozilla Public License Version 2.0 (the “MPL”) OR
10 *
11 *   2. The MIT License (MIT)
12 *                     
13 *   3. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016
14 */
15
16use std::borrow::Cow;
17
18use chrono::Local;
19
20use crate::{truncate, truncate_n, Priority, CBRACE_SEM, OBRACE, RFC3164_MAX_PAYLOAD_LEN, WSPACE};
21
22use super::{SyslogFormatted, SyslogFormatter};
23
24
25
26#[derive(Debug, Clone)]
27#[repr(transparent)]
28pub struct FormatRfc3146(Cow<'static, str>);
29
30unsafe impl Send for FormatRfc3146 {}
31
32impl From<String> for FormatRfc3146
33{
34    fn from(value: String) -> FormatRfc3146 
35    {
36        return Self(Cow::Owned(value));
37    }
38}
39
40impl From<&'static str> for FormatRfc3146
41{
42    fn from(value: &'static str) -> FormatRfc3146
43    {
44        return FormatRfc3146(Cow::Borrowed(value));
45    }
46}
47
48
49
50impl SyslogFormatter for FormatRfc3146
51{
52    fn vsyslog1_format(&self, _max_msg_size: usize, pri: Priority, progname: &str, pid: &str) -> SyslogFormatted
53    {
54        // get timedate
55        let timedate = Local::now().format("%h %e %T").to_string();
56
57        let msg_payload = truncate_n(&self.0, RFC3164_MAX_PAYLOAD_LEN);
58
59        let msg_payload_final = 
60            if msg_payload.ends_with("\n") == true
61            {
62                truncate(&msg_payload)
63            }
64            else
65            {
66                &msg_payload
67            };
68            
69        // message based on RFC 3164
70        let msg_pri = 
71            [
72                "<", pri.bits().to_string().as_str(), ">"
73            ]
74            .concat();
75
76        let msg_pkt = 
77            [
78                //pri <>
79                //Cow::Owned(msg_pri), 
80                // timedate
81                timedate.as_str(),
82                // hostname
83                // " ".as_bytes(), hostname.as_bytes(), 
84                // appname
85                WSPACE, progname,
86                // PID
87                OBRACE, pid, CBRACE_SEM,
88                // msg
89                WSPACE, /*b"\xEF\xBB\xBF",*/ msg_payload_final
90            ]
91            .concat();
92
93
94        return 
95            SyslogFormatted
96            { 
97                msg_header: Some(msg_pri), 
98                msg_payload: msg_pkt, 
99                full_msg: None
100            };
101    }
102}
103