syslog_rs/formatters/
syslog_file.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, SecondsFormat};
19
20use crate::{truncate, truncate_n, Priority, NEXTLINE, WSPACE};
21
22use super::{SyslogFormatted, SyslogFormatter};
23
24#[derive(Debug, Clone)]
25#[repr(transparent)]
26pub struct FormatFile(Cow<'static, str>);
27
28unsafe impl Send for FormatFile {}
29
30impl From<String> for FormatFile
31{
32    fn from(value: String) -> FormatFile 
33    {
34        return Self(Cow::Owned(value));
35    }
36}
37
38impl From<&'static str> for FormatFile
39{
40    fn from(value: &'static str) -> FormatFile
41    {
42        return Self(Cow::Borrowed(value));
43    }
44}
45
46impl SyslogFormatter for FormatFile
47{
48    fn vsyslog1_format(&self, max_msg_size: usize, pri: Priority, progname: &str, pid: &str) -> SyslogFormatted
49    {
50        let timedate = Local::now().to_rfc3339_opts(SecondsFormat::Secs, false);
51
52        let msg_payload = truncate_n(&self.0, max_msg_size);
53
54        let msg_payload_final = 
55            if msg_payload.ends_with("\n") == true
56            {
57                truncate(msg_payload)
58            }
59            else
60            {
61                msg_payload
62            };
63           
64        let msg_pkt = 
65            [
66                pri.to_string().as_str(),
67                WSPACE, timedate.as_str(), 
68                WSPACE, progname,
69                WSPACE, pid,
70                WSPACE, msg_payload_final, NEXTLINE
71            ]
72            .concat();
73
74        return 
75            SyslogFormatted
76            { 
77                msg_header: None, 
78                msg_payload: msg_pkt, 
79                full_msg: None
80            };
81    }
82}
83