syslog-rs 1.0.1

A native Rust implementation of the glibc/libc syslog.
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
# syslog-rs

### This is NOT an Open Source software! This is Source Available or Sources Disclosed software or Fairuse software!!! If this is a concern, please don't use this crate.  

### This crate does not include/use AI generated code! The AI generated code is prohibited.   

### Issues tracker: [A public crate's Issues Tracker]https://gitlab.com/4neko/syslog-rs

v 1.0.0

An implementation of the syslog from glibc/libc like it was designed in
in both system libraries. The API is almost compatible with what is in
libc/glibc.

Available features:
- feature = "use_async" for asynchronious code
- feature = "use_sync" for synchronious code
- feature = "use_sync_queue" for synchronious with async processing
- feature = "build_with_net" enables the TCP/UDP and extended interface

The `use_sync` is acting like the libc's/glibc's functions syslog(), openlog()...

The `use_sync_queue` has the same API as libc/glibc but is different in some ways. Also, it spawns a worker thread which sends messages from the queue to syslog.

The `use_async` is async realization of the `use_sync`. Untested, probably requires further dev.

Features:
- `build_with_file` enables the functionality to open a log file directly on local FS. And a subset of the `use_sync_queue`. this feature enables the code 
    which allowes to log into file using sync_queue. It is possible to log from both sync and async code, see `example_logtofile.rs`.
- `build_with_net` enables the TCP, UDP, TLS (should be enabled separatly using `build_with_tls`)
- `build_with_tls` enables the TLS for TCP (a subset of `build_with_net`)

All 3 features can be used simpltaniously. 

Available tunables:
- feature = "udp_truncate_1024_bytes"
- feature = "udp_truncate_1440_bytes" DEFAULT

The above is for RFC5424 which controls the syslog message length for forwarding via UDP protocol.

- feature = "tcp_truncate_1024_bytes"
- feature = "tcp_truncate_2048_bytes" DEFAULT
- feature = "tcp_truncate_4096_bytes"
- feature = "tcp_truncate_max_bytes"

- feature = "truncate_default" - a shortcut for "udp_truncate_1440_bytes" and "tcp_truncate_2048_bytes"

The above is for RFC5424 which controls the syslog message length for forwarding via TCP protocol.

- feature = "dgram_sysctl_failure_panic"

The above is for *BSD systems only and controls the behaviour of the sysctl error handling. If this is
enabled, the crate will panic is access to sysctl fails. Not enabled by default.

!!! `use_async` is using tokio mutex to achieve the synchronization. On the large async queues, when many tasks are spawned, the syslog becomes a performace bottleneck because syslog server may be busy, and syslog() is slow, and calling syslog() will lock other tasks until the lock will be released. Maybe it is good idea to have for example for each tokio thread a sibgle instance of the syslog.


## Usage:

For default
syslog-rs = "1.0"

For customization:
syslog-rs = {version = "1.0", default-features = false, features = ["use_sync", "truncate_default"]}

## Supports

- GNU/Linux RFC3164 (UTF-8 by default)
- *BSD and OSX RFC5424 (BOM UTF-8 by default)

## Contributors

Ordered by Relkom s.r.o (c) 2021

Developed by:
Aleksandr Morozov 

## Examples

See ./examples/ in the repository.

### Sync syslog (Local)

```rust


use std::{sync::LazyLock, thread};
use std::time::Duration;

#[cfg(feature = "use_sync")]
use syslog_rs::sy_sync::Syslog;

use syslog_rs::{LogFacility, LogStat, Priority, SyslogLocal};

pub static SYSLOG: LazyLock<Syslog> = LazyLock::new(|| 
    {
        Syslog::openlog(
            Some("example"), 
            LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
            LogFacility::LOG_DAEMON, SyslogLocal::new()
        )
        .unwrap()
    }
);


macro_rules! logdebug 
{
    ($($arg:tt)*) => (
        SYSLOG.syslog(Priority::LOG_DEBUG, format!($($arg)*))
    )
}

pub fn main()
{
    logdebug!("test message1!");

    SYSLOG.change_identity("example2").unwrap();

    logdebug!("test message from new ident");

    thread::sleep(Duration::from_micros(10));

    return;
}

```

### Async syslog (Local)

```rust
use syslog_rs::sy_async::AsyncSyslog;
use tokio::sync::OnceCell;
use tokio::time::{Duration, sleep};

use syslog_rs::{LogFacility, LogStat, Priority, SyslogLocal};


pub static SYSLOG: OnceCell<AsyncSyslog> = OnceCell::const_new();


macro_rules! logdebug 
{
    ($($arg:tt)*) => (
        SYSLOG.get().unwrap().syslog(Priority::LOG_DEBUG, format!($($arg)*)).await
    )
}

#[tokio::main]
async fn main()
{
    let syslog =
    AsyncSyslog::openlog(
            Some("example"), 
            LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
            LogFacility::LOG_DAEMON,
            SyslogLocal::new()
        ).await.unwrap();


    SYSLOG.get_or_init(|| async { syslog }).await;


    logdebug!("test message async start!");
    
    SYSLOG.get().unwrap().vsyslog(Priority::LOG_DEBUG, "test 2").await;

    sleep(Duration::from_micros(10)).await;

    SYSLOG.get().unwrap().change_identity("new_identity").await.unwrap();

    logdebug!("test message new identity!");

    sleep(Duration::from_micros(10)).await;

    logdebug!("test 123!");
    logdebug!("test 123123! end ");
    return;
}

```

### Custom formatter.

```rust
use std::{borrow::Cow, sync::OnceLock};
use std::thread;
use std::time::Duration;

use chrono::{Local, SecondsFormat};
#[cfg(feature = "use_sync")]
use syslog_rs::sy_sync::Syslog;
use syslog_rs::{SyslogFile, NEXTLINE, WSPACE};
use syslog_rs::{common, formatters::{SyslogFormatted, SyslogFormatter}, SyslogShared, TapType};
#[cfg(feature = "use_sync")]
use syslog_rs::{LogStat, LogFacility, Priority};

pub static SYNC_SYSLOG: OnceLock<Syslog<SyslogFile, MyFormatter, SyslogShared<MyFormatter>>> = OnceLock::new();

macro_rules! logdebug 
{
    ($($arg:tt)*) => (
        SYNC_SYSLOG.get().unwrap().syslog(Priority::LOG_DEBUG, format!($($arg)*));
    )
}

#[derive(Debug, Clone)]
pub struct MyFormatter();

unsafe impl Send for MyFormatter {}

impl SyslogFormatter for MyFormatter
{
    fn vsyslog1_format<'f>(_tap_type: TapType, pri: Priority, progname: &'f str, pid: &'f str, fmt: &'f str) -> SyslogFormatted<'f>
    {
        let timedate = Local::now().to_rfc3339_opts(SecondsFormat::Secs, false);

        let msg_payload_final = 
            if fmt.ends_with("\n") == true
            {
                common::truncate(fmt)
            }
            else
            {
                fmt
            };
           
        let msg_pkt = 
            [
                Cow::Owned(pri.to_string()), Cow::Borrowed(WSPACE), Cow::Borrowed("MYFORMATTER"),
                Cow::Borrowed(WSPACE), Cow::Owned(timedate), 
                Cow::Borrowed(WSPACE), Cow::Borrowed(progname),
                Cow::Borrowed(WSPACE), Cow::Borrowed(pid),
                Cow::Borrowed(WSPACE), Cow::Borrowed(msg_payload_final), Cow::Borrowed(NEXTLINE)
            ]
            .to_vec();
       
        let msg_rng = msg_pkt.len();

        return SyslogFormatted::new( msg_pkt,  0..msg_rng );
    }
}

pub fn main()
{
    let syslog = 
        Syslog
            ::<SyslogFile, MyFormatter, SyslogShared<MyFormatter>>
            ::openlog_with(
            Some("example"), 
            LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
            LogFacility::LOG_DAEMON,
            SyslogFile::new("/tmp/myformatter.log")
        ).unwrap();

    SYNC_SYSLOG.get_or_init(|| syslog);

    logdebug!("test message!");

    SYNC_SYSLOG.get().unwrap().change_identity("another").unwrap();

    logdebug!("test message new!");

    thread::sleep(Duration::from_micros(10));

   
```

### Formatter select

```rust
use std::sync::OnceLock;
use std::thread;
use std::time::Duration;

#[cfg(feature = "use_sync")]
use syslog_rs::sy_sync::Syslog;
use syslog_rs::{formatters::{FormatRfc3146, FormatRfc5424}, SyslogLocal, SyslogShared};
#[cfg(feature = "use_sync")]
use syslog_rs::{LogStat, LogFacility, Priority};

#[cfg(target_os = "linux")]
pub static SYNC_SYSLOG: OnceLock<Syslog<SyslogLocal, FormatRfc3146, SyslogShared<FormatRfc3146>>> = OnceLock::new();
#[cfg(not(target_os = "linux"))]
pub static SYNC_SYSLOG: OnceLock<Syslog<SyslogLocal, FormatRfc5424, SyslogShared<FormatRfc5431>>> = OnceLock::new();

macro_rules! logdebug 
{
    ($($arg:tt)*) => (
        SYNC_SYSLOG.get().unwrap().syslog(Priority::LOG_DEBUG, format!($($arg)*));
    )
}

pub fn main()
{
    let syslog = 
        Syslog::<_>::openlog_with(
            Some("example"), 
            LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
            LogFacility::LOG_DAEMON,
            SyslogLocal::new()
        ).unwrap();

    SYNC_SYSLOG.get_or_init(|| syslog);

    logdebug!("test message!");

    thread::sleep(Duration::from_micros(10));

    return;
}
```

### SYNC and ASYNC to same "tap" i.e same connection

```rust



use std::sync::OnceLock;
use std::thread;
use std::time::Duration;


use syslog_rs::formatters::DefaultSyslogFormatterFile;
use syslog_rs::sy_async::AsyncSyslog;
use syslog_rs::sy_sync::Syslog;
use syslog_rs::{AsyncSyslogQueue, LogFacility, LogStat, Priority, SyslogFile, SyslogQueue};
use tokio::sync::{mpsc, OnceCell};
use tokio::{runtime, task};

pub static SYSLOG: OnceLock<Syslog<SyslogFile, DefaultSyslogFormatterFile, SyslogQueue<DefaultSyslogFormatterFile>>> = OnceLock::new();

pub static ASYSLOG: OnceCell<AsyncSyslog<SyslogFile, DefaultSyslogFormatterFile, AsyncSyslogQueue<DefaultSyslogFormatterFile>>> = OnceCell::const_new();

macro_rules! logdebug 
{
    ($($arg:tt)*) => (
        SYSLOG.get().as_ref().unwrap().syslog(Priority::LOG_DEBUG, format!($($arg)*))
    )
}

macro_rules! alogdebug 
{
    ($($arg:tt)*) => (
        ASYSLOG.get().as_ref().unwrap().syslog(Priority::LOG_DEBUG, format!($($arg)*)).await
    )
}


pub fn main()
{
    SYSLOG.get_or_init(move || {
        Syslog::<SyslogFile, DefaultSyslogFormatterFile, SyslogQueue<DefaultSyslogFormatterFile>>::openlog_with(
            Some("example"), 
            LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
            LogFacility::LOG_DAEMON,
            SyslogFile::new("/tmp/example_logtofile.txt")
        )
        .unwrap()
    });
    
    

    logdebug!("test message logtofile!");

    thread::sleep(Duration::from_micros(10));

    let runtime = 
        runtime::Builder::new_multi_thread()
            .enable_all()
            .build()
            .unwrap();

    runtime.block_on(async 
        {
            ASYSLOG.get_or_init(|| async {
                AsyncSyslog::<SyslogFile, DefaultSyslogFormatterFile, AsyncSyslogQueue<DefaultSyslogFormatterFile>>::attach_queue(SYSLOG.get().unwrap()).await.unwrap()
            }).await;

            let s =
            task::spawn_blocking(move || 
                {
                    for i in 0..10
                    {
                        logdebug!("blocking thread message no: '{}'", i);
                    
                        thread::sleep(Duration::from_micros(300));
                    }

                    return;
                }
            );

            for i in 0..10
            {
                alogdebug!("async thread message no: '{}'", i);

                tokio::time::sleep(Duration::from_micros(304)).await;
            }

            s.await.unwrap();

            let (tx, mut rx) = mpsc::channel::<u64>(1);

            task::spawn_blocking(move || 
                {
                    SYSLOG.get().unwrap().update_tap(SyslogFile::new("/tmp/example_logtofile2.txt")).unwrap();

                    tx.blocking_send(0).unwrap();

                    for i in 0..10
                    {
                        logdebug!("blocking NEW thread message no: '{}'", i);
                    
                        thread::sleep(Duration::from_micros(300));
                    }
                    return;
                }
            );

            rx.recv().await;

            for i in 0..10
            {
                alogdebug!("async NEW thread message no: '{}'", i);

                tokio::time::sleep(Duration::from_micros(304)).await;
            }
        }
    );

    logdebug!("test message logtofile!");

    return;
}
```

### Log to file
```rust


use std::{sync::LazyLock, thread};
use std::time::Duration;



use syslog_rs::formatters::DefaultSyslogFormatterFile;
use syslog_rs::sy_sync::Syslog;
use syslog_rs::{LogFacility, LogStat, Priority, SyslogFile, SyslogShared};

pub static SYSLOG: LazyLock<Syslog<SyslogFile, DefaultSyslogFormatterFile, SyslogShared<DefaultSyslogFormatterFile>>> = LazyLock::new(|| 
    {
        Syslog::<SyslogFile, DefaultSyslogFormatterFile, SyslogShared<DefaultSyslogFormatterFile>>::openlog_with(
            Some("example"), 
            LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
            LogFacility::LOG_DAEMON,
            SyslogFile::new("/tmp/sync_file.log")
        )
        .unwrap()
    }
);


macro_rules! logdebug 
{
    ($($arg:tt)*) => (
        SYSLOG.syslog(Priority::LOG_DEBUG, format!($($arg)*))
    )
}

pub fn main()
{
    logdebug!("test message1!");
    logdebug!("test message2!");
    logdebug!("test message3!");

    thread::sleep(Duration::from_micros(10));

    return;
}


```

### Exampe UDP
```rust

use std::{sync::LazyLock, thread};
use std::time::Duration;



use syslog_rs::formatters::DefaultSyslogFormatter;
use syslog_rs::sy_sync::Syslog;
use syslog_rs::{LogFacility, LogStat, Priority, SyslogNet, SyslogShared};

pub static SYSLOG: LazyLock<Syslog<SyslogNet, DefaultSyslogFormatter, SyslogShared<DefaultSyslogFormatter>>> = LazyLock::new(|| 
    {
        Syslog::<SyslogNet, DefaultSyslogFormatter, SyslogShared<DefaultSyslogFormatter>>::openlog_with(
            Some("example"), 
            LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
            LogFacility::LOG_DAEMON,
            SyslogNet::new_udp("127.0.0.1:514")            
        )
        .unwrap()
    }
);

macro_rules! logdebug 
{
    ($($arg:tt)*) => (
        SYSLOG.syslog(Priority::LOG_DEBUG, format!($($arg)*))
    )
}

pub fn main()
{
    logdebug!("test message!");

    thread::sleep(Duration::from_micros(10));

    return;
}

```

## Benchmarking

The test spawns 2 threads and one main thread. All 3 threads are sending messages to syslog. The time measurment in the tables are approximations.

Results of the tests in syslog_*.rs files in Debug mode (AMD Ryzen 5 7600X 6-Core Processor):

| use_sync (sys mutex) | use_sync_queue |   use_async  |
|----------            |----------------|--------------|
|main: 87.31µs       | main: 12.74µs   |main: 94.849µs|
|t1: 170.809µs          |t2: 1.77µs   |t2: 12.339µs   |
|t2: 69.529µs          |t1: 4.49µs      |t1: 7.2µs  |
|t1: 6.87µs          |t2: 630ns  |t1: 16.32µs  |
|t2: 5.8µs          |t1: 320ns    |t2: 6.26µs  |
|t1: 5.7µs         |t2: 1.13µs      |t2: 14.74µs   |
|t2: 5.46µs         |t1: 280ns      |t1: 6.7µs   |
|t1: 5.83µs          |t1: 950ns    |t1: 8.73µs   |
|t2: 7.239µs          |t2: 750ns      |t2: 5.37µs  |
|t1: 5.8µs          |t1: 720ns   |t2: 8.02µs   |
|t2: 5.38µs          |t2: 700ns    |t1: 5.34µs   |