syslog-rs 6.6.0

A native Rust implementation of the glibc/libc/windows syslog client and windows native log for logging.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/*-
 * syslog-rs - a syslog client translated from libc to rust
 * 
 * Copyright 2025 Aleksandr Morozov
 * 
 * The syslog-rs crate can be redistributed and/or modified
 * under the terms of either of the following licenses:
 *
 *   1. the Mozilla Public License Version 2.0 (the “MPL”) OR
 *
 *   2. The MIT License (MIT)
 *                     
 *   3. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016
 */

use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
use std::{str};

use crate::formatters::DefaultSyslogFormatter;
use crate::sync::{LogItems, SyStream, SyStreamPri, SyStreamSyslogApi};
use crate::{formatters::SyslogFormatter};
use crate::{common::*, SyslogDestination};
use crate::error::SyRes;


use crate::sync::syslog_sync_internal::{SyslogSocketLockless};

#[cfg(target_family = "unix")]
use crate::SyslogLocal;

#[cfg(target_family = "windows")]
use crate::WindowsEvent;


#[cfg(target_family = "unix")]
pub type DefaultLocalSyslogDestination = SyslogLocal;
#[cfg(target_family = "windows")]
pub type DefaultLocalSyslogDestination = WindowsEvent;

/// A `sync`, shared instance of the syslog client which is shared between many
/// threads. Previously a mutex was used, but since the v5.0.0 a CoW experimental
/// approach is used. The `CoW` creates clones of the instance without holding
/// a long mutex locks. When writing, the instance does not hold a long lock on
/// updated item. Only exclusive lock locks the readers, because the instance is
/// updated and not usable anyway.
/// 
/// If the program has fixed amount of threads, probably the `syslog_threadlocal`
/// will be better alternative. It has the same functionality, but avoids 
/// any sync locks by working in current thread.
/// 
/// # Traits
/// 
/// For this isntance a [SyslogApi] and [SyStreamApi] are implemented.
/// 
/// # Examples
/// 
/// ```ignore
/// let log = 
///     SyncSyslog::openlog(
///         Some("test1"), 
///         LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
///         LogFacility::LOG_DAEMON,
///         SyslogLocal::new()
///     );
/// ```
/// 
/// ```ignore
/// let log = 
///     SyncSyslog
///         ::<DefaultSyslogFormatter, SyslogLocal>
///         ::openlog_with(
///             Some("test1"), 
///             LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
///             LogFacility::LOG_DAEMON,
///             SyslogLocal::new()
///         );
/// ```
/// 
/// ```ignore
/// pub static SYSLOG3: LazyLock<SyncSyslog<DefaultSyslogFormatter, SyslogLocal,>> = 
///     LazyLock::new(|| 
///         {
///             SyncSyslog
///                 ::<DefaultSyslogFormatter, SyslogLocal>
///                 ::openlog_with(
///                     Some("test1"), 
///                     LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
///                     LogFacility::LOG_DAEMON,
///                     SyslogLocal::new()
///                 )
///                 .unwrap()
///         }
///     );
/// ```
/// # Streaming
/// 
/// A stream is availble via [SyStreamApi].
/// 
/// ```ignore
/// let _ = write!(SYSLOG.stream(Priority::LOG_DEBUG), "test {} 123 stream test ", d);
/// ```
/// 
/// # Generics
/// 
/// * `F` - a [SyslogFormatter] which sets the instance which would 
///     format the message.
/// 
/// * `D` - a [SyslogDestination] instance which is either:
///     [SyslogLocal], [SyslogFile], [SyslogNet], [SyslogTls]. By
///     default a `SyslogLocal` is selected.
#[derive(Debug, Clone)]
pub struct SyncSyslog<F = DefaultSyslogFormatter, D = DefaultLocalSyslogDestination>
where 
    F: SyslogFormatter, 
    D: SyslogDestination, 
{   
    /// An identification i.e program name, thread name
    log_items: Arc<Mutex<LogItems>>,

    /// A stream (unixdatagram, udp, tcp)
    stream: Arc<Mutex<SyslogSocketLockless<D>>>,

     _p: PhantomData<F>,
}

unsafe impl<F: SyslogFormatter, D: SyslogDestination> Send for SyncSyslog<F, D>
{}

impl SyncSyslog
{
    /// Opens a default connection to the local syslog server with default formatter.
    /// 
    /// In order to access the syslog API, use the [SyslogApi].
    /// 
    /// # Arguments
    /// 
    /// * `ident` - A program name which will appear on the logs. If none, will be determined
    ///     automatically.
    /// 
    /// * `logstat` - [LogStat] an instance config.
    /// 
    /// * `facility` - [LogFacility] a syslog facility.
    /// 
    /// * `net_tap_prov` - a [SyslogLocal] instance with configuration.
    /// 
    /// # Returns
    /// 
    /// A [SyRes] is returned ([Result]) with: 
    /// 
    /// * [Result::Ok] - with instance
    /// 
    /// * [Result::Err] - with error description.
    pub 
    fn openlog(ident: Option<&str>, logstat: LogStat, facility: LogFacility, 
        net_tap_prov: DefaultLocalSyslogDestination) -> SyRes<Self> 
    {
        return Ok( 
            Self
            {
                log_items: 
                    Arc::new(
                        Mutex::new(
                            LogItems::new(ident, 0xff, logstat, facility)
                        )
                    ),
                stream: 
                    Arc::new(
                        Mutex::new(
                            SyslogSocketLockless::<DefaultLocalSyslogDestination>::new(logstat, net_tap_prov)?
                        )
                    ),
                _p: 
                    PhantomData,
            }
        );
    }
}


impl<F: SyslogFormatter, D: SyslogDestination> SyncSyslog<F, D>
{
    /// Opens a special connection to the destination syslog server with specific formatter.
    /// 
    /// All struct generic should be specified before calling this function.
    /// 
    /// In order to access the syslog API, use the [SyslogApi].
    /// 
    /// # Arguments
    /// 
    /// * `ident` - A program name which will appear on the logs. If none, will be determined
    ///     automatically.
    /// 
    /// * `logstat` - [LogStat] an instance config.
    /// 
    /// * `facility` - [LogFacility] a syslog facility.
    /// 
    /// * `net_tap_prov` - a destination server. A specific `D` instance which contains infomation 
    ///     about the destination server. See `syslog_provider.rs`.
    /// 
    /// # Returns
    /// 
    /// A [SyRes] is returned ([Result]) with: 
    /// 
    /// * [Result::Ok] - with instance
    /// 
    /// * [Result::Err] - with error description.
    pub 
    fn openlog_with(ident: Option<&str>, logstat: LogStat, facility: LogFacility, net_tap_prov: D) -> SyRes<Self> 
    {
        return Ok( 
            Self
            {
                log_items: 
                    Arc::new(
                        Mutex::new(
                            LogItems::new(ident, 0xff, logstat, facility)
                        )
                    ),
                stream: 
                    Arc::new(
                        Mutex::new(
                            SyslogSocketLockless::<D>::new(logstat, net_tap_prov)?
                        )
                    ),
                _p: 
                    PhantomData,
            }
        );
    }
}


impl<F: SyslogFormatter, D: SyslogDestination> SyncSyslog<F, D>
{
    /// Connects the current instance to the syslog server (destination).
    pub 
    fn connectlog(&self) -> SyRes<()>
    {
        return 
            self
                .stream
                .lock()
                .unwrap()
                .connectlog();
    }

    /// Sets the logmask to filter out the syslog calls.
    /// 
    /// See macroses [LOG_MASK] and [LOG_UPTO] to generate mask
    ///
    /// # Example
    ///
    /// LOG_MASK!(Priority::LOG_EMERG) | LOG_MASK!(Priority::LOG_ERROR)
    ///
    /// or
    ///
    /// ~(LOG_MASK!(Priority::LOG_INFO))
    /// LOG_UPTO!(Priority::LOG_ERROR)
    pub 
    fn setlogmask(&self, logmask: i32) -> SyRes<i32> 
    {
        let pri = 
            self
                .log_items
                .lock()
                .unwrap()
                .set_logmask(logmask);

        return Ok(pri);
    }

    /// Closes connection to the syslog server (destination).
    pub 
    fn closelog(&self) -> SyRes<()> 
    {
        return 
            self
                .stream
                .lock()
                .unwrap()
                .disconnectlog();
    }

    /// Similar to libc, syslog() sends data to syslog server.
    /// 
    /// # Arguments
    ///
    /// * `pri` - a priority [Priority]
    ///
    /// * `fmt` - a formatter [SyslogFormatter] message. In C exists a functions with
    ///     variable argumets amount. In Rust you should create your
    ///     own macros like format!() or use format!()]. The [String] and ref `'static` 
    ///     [str] can be passed directly.
    /// 
    /// # Returns 
    /// 
    /// A [SyRes] is returned which may describe an error.
    #[inline]
    pub 
    fn syslog(&self, pri: Priority, fmt: F) -> SyRes<()>
    {
        let Some((formatted_msg, logstat)) = 
            self.log_items.lock().unwrap().vsyslog1_msg::<F, D>(pri, &fmt)
        else { return Ok(()) };

        self.stream.lock().unwrap().vsyslog1(logstat, formatted_msg)
    }

    /// This function can be used to update the facility name, for example
    /// after fork().
    /// 
    /// # Arguments
    /// 
    /// * `ident` - an [Option] optional new identity (up to 48 UTF8 chars)
    ///     If set to [Option::None] would request the program name from OS.
    pub 
    fn change_identity(&self, ident: Option<&str>) -> SyRes<()>
    {
        self
            .log_items
            .lock()
            .unwrap()
            .set_identity(ident);

        return Ok(());
    }

    /// Re-opens the connection to the syslog server. Can be used to 
    /// rotate logs(handle SIGHUP).
    /// 
    /// # Returns
    /// 
    /// A [Result] is retured as [SyRes].
    /// 
    /// * [Result::Ok] - with empty inner type.
    /// 
    /// * [Result::Err] - an error code and description 
    pub 
    fn reconnect(&self) -> SyRes<()>
    {
        return
            self
                .stream
                .lock()
                .unwrap()
                .reconnectlog();
    }

    /// Updates the instance's socket. `tap_data` [TapTypeData] should be of
    /// the same variant (type) as current.
    pub 
    fn update_tap_data(&self, tap_data: D) -> SyRes<()>
    {
        return
            self
                .stream
                .lock()
                .unwrap()
                .update_tap_data(tap_data);
    }

}

impl<F, D> SyncSyslog<F, D>
where F: SyslogFormatter, D: SyslogDestination
{
    /// Returns the streamable [SyStream] instance which can be used with [write!].
    /// 
    /// It implements both [std::fmt::Write] and [std::io::Write].
    /// 
    /// # Example
    /// 
    /// ```ignore
    /// let log = 
    ///     SingleSyslog::openlog(
    ///         Some("test1"), 
    ///         LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
    ///         LogFacility::LOG_DAEMON,
    ///         SyslogLocal::new()
    ///     ).unwrap();
    /// 
    /// write!(log.get_stream::<SyStreamPriDebug>(), "test stream singlesyslog {}", i).unwrap();
    /// ```
    pub 
    fn get_stream<'t, PRI>(&'t self) -> SyStream<'t, PRI, D, F, &'t Self>
    where PRI: SyStreamPri
    {
        SyStream
        {
            s: Some(self),
            _p: PhantomData,
            _p1: PhantomData,
            _p2: PhantomData
        }
    }
}


impl<F: SyslogFormatter, D: SyslogDestination> SyStreamSyslogApi<F, D>  
for &SyncSyslog<F, D>
{
    type SYSLOG<'t> = &'t SyncSyslog<F, D>;

    fn syslog<'t>(syslog: Self::SYSLOG<'t>, pri: Priority, fmt: F) -> SyRes<()>
    {
        syslog.syslog(pri, fmt)
    }
}