syslog-rs 7.0.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
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
/*-
 * 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::{borrow::Cow, env::{self, VarError}, str::FromStr, sync::OnceLock};

#[cfg(feature = "build_sync")]
use crate::{LogFacility, LogStat, Priority, };
#[cfg(feature = "build_ext_file")]
use crate::SyslogFile;
#[cfg(feature = "build_ext_tls")]
use crate::SyslogTls;
#[cfg(feature = "build_ext_net")]
use crate::{SyslogNetTcp, SyslogNetUdp};
#[cfg(feature = "build_with_queue")]
use crate::{SyQueued, sy_sync_queue::SyslogQueueChannel};

use crate::{
    DynSyslog, SyShared, Syslog, SyslogDestination, SyslogLocal, error::{SyRes}, 
    formatters::
    {
        DEFAULT_SYSLOG_FORMATTER_TYPE, FormatFile, FormatRfc3146, FormatRfc5424, SyslogFormatter, 
        SyslogFormatters
    },  
    map_error, throw_error
};


/// * `local#` - for default
/// * `local#/var/run/syslogcustom` - for custom path 
pub const LOGGER_TYPE_LOCAL: &'static str = "local";

/// * `udp#127.0.0.1:80` - for IPv4 + port
/// * `udp#[fe00:::0]:80` - for IPv6 + port
/// * `udp#www.mydomain.tdl:80` - for hostname + port
pub const LOGGER_TYPE_UDP: &'static str = "udp";

/// * `tcp#127.0.0.1:80` - for IPv4 + port
/// * `tcp#[fe00:::0]:80` - for IPv6 + port
/// * `tcp#www.mydomain.tdl:80` - for hostname + port
pub const LOGGER_TYPE_TCP: &'static str = "tcp";

/// * `tls#127.0.0.1:80#servername#root_cert_path` - for IPv4 + port
/// * `tls#[fe00:::0]:80#servername#root_cert_path` - for IPv6 + port
/// * `tls#www.mydomain.tdl:80#servername#root_cert_path` - for hostname + port
pub const LOGGER_TYPE_TLS: &'static str = "tls";

/// * `file#/tmp/file1.txt` - for file append mode
pub const LOGGER_TYPE_FILE: &'static str = "file";

/// A syslog server destinatio: type and location. If not set, then logging is disabled.
pub const SYSLOG_LOGGER_DST_URI: &'static str = "SYSLOG_LOGGER_DST_URI";

/// A log facility. Starts with "LOG_*" see [LogFacility]. If not set, then default.
pub const SYSLOG_LOGGER_LOG_FACILITY: &'static str = "SYSLOG_LOGGER_LOG_FACILITY";

/// A formatter. See `formatters` for available. It is defined as `FORMATTER_NAME`.
/// 
/// If not defined, then a default formatter will be used.
/// 
/// Available: RFC3146, RFC5424, FILE.
pub const SYSLOG_LOGGER_LOG_FORMATTER: &'static str = "SYSLOG_LOGGER_LOG_FORMATTER";

/// An identification of the program. If not set, will be determined automatically.
/// 
/// If used in crate, then don't set this.
pub const SYSLOG_LOGGER_LOG_IDENTITY: &'static str = "SYSLOG_LOGGER_LOG_IDENTITY";

/// A logger instances. todo: if one instance fails, use backup.
pub(crate) static LOGGER: OnceLock<Box<dyn DynSyslog>> = OnceLock::new();

fn derive_suffix(suffix: Option<&str>, env_name: &'static str) -> Cow<'static, str>
{
    if let Some(su) = suffix
    {
        Cow::Owned([env_name, "_", su].concat())
    }
    else
    {
        Cow::Borrowed(env_name)
    }
}

/// Attaches to the already existing instance of type [SyShared].
/// 
/// This is usefull when a executable software whant to receive messages from the
/// crate which uses `logger`.
/// 
/// Cannot be called twice! An error will be returned.
pub 
fn attach_event_log_shared<F, D>(sy: &Syslog<F, D, SyShared>) -> SyRes<()>
where 
    F: SyslogFormatter,
    D: SyslogDestination,
{
    let clonned_sy = sy.clone().make_dyn();

    LOGGER
        .set(clonned_sy)
        .map_err(|_e|
            map_error!("syslog instance has been already initialized!")
        )
}

/// Attaches to the already existing instance of type [SyQueued].
/// 
/// This is usefull when a executable software whant to receive messages from the
/// crate which uses `logger`.
/// 
/// Cannot be called twice! An error will be returned.
#[cfg(feature = "build_with_queue")]
pub 
fn attach_event_log_queued<F, D, S>(sy: &Syslog<F, D, SyQueued<S, F, D>>) -> SyRes<()>
where 
    F: SyslogFormatter,
    D: SyslogDestination,
    S: SyslogQueueChannel<F, D>
{
    let clonned_sy = sy.clone().make_dyn();

    LOGGER
        .set(clonned_sy)
        .map_err(|_e|
            map_error!("syslog instance has been already initialized!")
        )
}

fn set_logger(syslog_inst: Box<dyn DynSyslog>) -> SyRes<()>
{
    LOGGER
        .set(syslog_inst)
        .map_err(|_e|
            map_error!("syslog instance has been already initialized!")
        )
}

fn openlog_with<F, D>(ident: Option<String>, logstat: LogStat, facility: LogFacility, net_tap_prov: D) -> SyRes<Box<dyn DynSyslog>>
where
    // Bounds from impl:
    F: SyslogFormatter,
    D: SyslogDestination,
{
    Syslog
        ::<F, D, SyShared>
        ::openlog_with(ident.as_ref().map(|d| d.as_str()), 
            logstat, facility, net_tap_prov)
                .map(|sy| sy.make_dyn())
}

#[derive(Debug)]
struct EnvVars
{
    logger_type_res: String,
    logger_facility: LogFacility,
    logger_formatter: SyslogFormatters,
    logger_identity: Option<String>,
}

impl EnvVars
{
    fn read_env(env_sufix: Option<&str>) -> SyRes<Option<Self>>
    {
        let logger_type_res = 
            match env::var(derive_suffix(env_sufix, SYSLOG_LOGGER_DST_URI).as_ref())
            {
                Ok(val) => 
                    val,
                Err(VarError::NotPresent) => 
                    return Ok(None),
                Err(VarError::NotUnicode(_e)) =>
                    throw_error!("{} is not unicode", SYSLOG_LOGGER_DST_URI)
            };

        let logger_facility= 
            match env::var(derive_suffix(env_sufix, SYSLOG_LOGGER_LOG_FACILITY).as_ref())
            {
                Ok(val) => 
                    LogFacility::from_str(&val)?,
                Err(VarError::NotPresent) => 
                    LogFacility::LOG_DAEMON,
                Err(VarError::NotUnicode(_e)) =>
                    throw_error!("{} is not unicode", SYSLOG_LOGGER_LOG_FACILITY)
            };

        let logger_formatter = 
            match env::var(derive_suffix(env_sufix, SYSLOG_LOGGER_LOG_FORMATTER).as_ref())
            {
                Ok(val) => 
                    SyslogFormatters::from_str(&val)?,
                Err(VarError::NotPresent) => 
                    DEFAULT_SYSLOG_FORMATTER_TYPE,
                Err(VarError::NotUnicode(_e)) =>
                    throw_error!("{} is not unicode", SYSLOG_LOGGER_LOG_FORMATTER)
            };

        let logger_identity = 
            match env::var(derive_suffix(env_sufix, SYSLOG_LOGGER_LOG_IDENTITY).as_ref())
            {
                Ok(val) => 
                    Some(val),
                Err(VarError::NotPresent) => 
                    None,
                Err(VarError::NotUnicode(_e)) =>
                    throw_error!("{} is not unicode", SYSLOG_LOGGER_LOG_IDENTITY)
            };

        return Ok(
            Some(
                Self
                {
                    logger_type_res, logger_facility, logger_formatter, logger_identity
                }
            )
        );
    }
}

#[derive(Debug, PartialEq, Eq)]
enum LoggerDst<'a>
{
    LoLocal{ dst_path: Option<&'a str> },
    
    #[cfg(feature = "build_ext_net")]
    LoUdp{ dst_host: &'a str },

    #[cfg(feature = "build_ext_net")]
    LoTcp{ dst_host: &'a str },

    #[cfg(feature = "build_ext_tls")]
    LoTls
    {
        dst_host: &'a str,
        serv_name: &'a str, 
        root_cert_path: &'a str,
    },

    #[cfg(feature = "build_ext_file")]
    LoFile{ dst_path: &'a str }
}

impl<'a> LoggerDst<'a>
{
    fn from_str(lo_sch: &'a str) -> SyRes<Self>
    {
        let (dst_type, payload) = 
            lo_sch
                .split_once("#")
                .ok_or_else(||
                    map_error!("{} incorrect format, expected type#dst:extras", SYSLOG_LOGGER_DST_URI)
                )?;

        let res = 
            match dst_type.to_lowercase().as_str()
            {
                LOGGER_TYPE_LOCAL =>
                {
                    let dst_path = payload.trim();

                    if dst_path.is_empty() == false
                    {
                        Self::LoLocal{ dst_path: Some(dst_path) }
                    }
                    else
                    {
                        Self::LoLocal{ dst_path: None }
                    }
                },

                #[cfg(feature = "build_ext_net")]
                LOGGER_TYPE_UDP => 
                {
                    let dst_host = payload.trim();
                    
                    Self::LoUdp{ dst_host }
                },

                #[cfg(not(feature = "build_ext_net"))]
                LOGGER_TYPE_UDP => 
                    throw_error!("cannot use UDP, crate compiled without `build_ext_net`!"),

                #[cfg(feature = "build_ext_net")]
                LOGGER_TYPE_TCP => //SyslogNetTcp
                {
                    let dst_host = payload.trim();

                    Self::LoTcp{ dst_host }
                },

                #[cfg(not(feature = "build_ext_net"))]
                LOGGER_TYPE_TCP => 
                    throw_error!("cannot use UDP, crate compiled without `build_ext_net`!"),
                
                #[cfg(feature = "build_ext_tls")]
                LOGGER_TYPE_TLS => 
                {
                    let (dst_host, payload) = 
                        payload
                            .split_once("#")
                            .map(|c| (c.0.trim(), c.1))
                            .ok_or_else(||
                                map_error!("SYSLOG_LOGGER_DST_URI incorrect format, expected type#dst:extras")
                            )?;

                    let (serv_name, root_cert_path) = 
                        payload
                            .split_once("#")
                            .map(|c| (c.0.trim(), c.1))
                            .ok_or_else(||
                                map_error!("SYSLOG_LOGGER_DST_URI incorrect format, expected type#dst:extras")
                            )?;

                    Self::LoTls{ dst_host, serv_name, root_cert_path }
                },

                #[cfg(not(feature = "build_ext_tls"))]
                LOGGER_TYPE_TLS => 
                    throw_error!("cannot use UDP, crate compiled without `build_ext_tls`!"),

                #[cfg(feature = "build_ext_file")]
                LOGGER_TYPE_FILE => 
                {
                    let dst_path = payload.trim();

                    Self::LoFile{ dst_path }
                },

                #[cfg(not(feature = "build_ext_file"))]
                LOGGER_TYPE_FILE =>
                    throw_error!("cannot use UDP, crate compiled without `build_ext_file`!"),

                n => 
                    throw_error!("SYSLOG_LOGGER_DST_URI unknown syslog dest type: {}", n)
            };

        return Ok(res);
    }
}

/// Initialzes the logger from the environment variables. If variables are not configured, 
/// exists without error. Should be called only once. 
/// 
/// The behaviour after `fork()` was not tested. So, it is advised to reconnect because the
/// FD will become invalid.
/// 
/// # Arguments
/// 
/// * `env_suffix` - specifies a specific suffix of environment variables. For example,
///     `SYSLOG_LOGGER_DST_URI` with suffix set to `XIO`, an `env` will be 
///     searched as `SYSLOG_LOGGER_DST_URI_XIO`.
/// 
/// # Returns
/// 
/// An error is returned if:
/// 
/// * called twice (re-initialization)
/// 
/// * if parsing of the env variables failes due to incorrect structure or whatever
/// 
/// * syslog client fails to establish connection (at the moment silencing this error is
///     not supported)
/// 
/// # Examples:
/// 
/// Setting the env to:
/// ```text
/// SYSLOG_LOGGER_DST_URI="local#"
/// SYSLOG_LOGGER_LOG_FACILITY="LOG_DAEMON"
/// SYSLOG_LOGGER_LOG_FORMATTER="RFC3146"
/// SYSLOG_LOGGER_LOG_IDENTITY="new_identity"
/// ```
/// 
/// should be initialized with:
/// 
/// ```ignore
/// init_event_log(None).unwrap();
/// ```
/// -- OR --
/// 
/// Setting the env to:
/// ```text
/// SYSLOG_LOGGER_DST_URI_XIO="local#"
/// SYSLOG_LOGGER_LOG_FACILITY_XIO="LOG_DAEMON"
/// SYSLOG_LOGGER_LOG_FORMATTER_XIO="RFC3146"
/// SYSLOG_LOGGER_LOG_IDENTITY_XIO="xio0"
/// ```
/// 
/// should be initialized with:
/// 
/// ```ignore
/// init_event_log(Some("XIO")).unwrap();
/// ```
pub 
fn init_event_log(env_suffix: Option<&str>) -> SyRes<()>
{
    let Some(envs) = EnvVars::read_env(env_suffix)?
        else { return Ok(()) };

    let dst = LoggerDst::from_str(&envs.logger_type_res)?;
    
    match dst
    {
        LoggerDst::LoLocal{ dst_path } =>
        {
            let tap = 
                if let Some(dst_path) = dst_path
                {
                    SyslogLocal::new_custom_path(dst_path, false)?
                }
                else
                {
                    SyslogLocal::new()
                };

            let syslog_inst = 
                match envs.logger_formatter
                {
                    SyslogFormatters::FormatRfc3146 => 
                    {
                        openlog_with
                            ::<FormatRfc3146, SyslogLocal>(envs.logger_identity, 
                                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, envs.logger_facility, tap)?
                    },
                    SyslogFormatters::FormatRfc5424 => 
                    {
                        openlog_with
                            ::<FormatRfc5424, SyslogLocal>(envs.logger_identity, 
                                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, envs.logger_facility, tap)?
                    },
                    SyslogFormatters::FormatFile => 
                    {
                        openlog_with
                            ::<FormatFile, SyslogLocal>(envs.logger_identity, 
                                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, envs.logger_facility, tap)?
                    },
                };

            set_logger(syslog_inst)?
        },
        #[cfg(feature = "build_ext_net")]
        LoggerDst::LoUdp{ dst_host } => 
        {
            let tap = SyslogNetUdp::new(dst_host, None)?;
            
            let syslog_inst = 
                match envs.logger_formatter
                {
                    SyslogFormatters::FormatRfc3146 => 
                    {
                        openlog_with
                            ::<FormatRfc3146, SyslogNetUdp>(envs.logger_identity, 
                                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, envs.logger_facility, tap)?
                    },
                    SyslogFormatters::FormatRfc5424 => 
                    {
                        openlog_with
                            ::<FormatRfc5424, SyslogNetUdp>(envs.logger_identity, 
                                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, envs.logger_facility, tap)?
                    },
                    SyslogFormatters::FormatFile => 
                    {
                        openlog_with
                            ::<FormatFile, SyslogNetUdp>(envs.logger_identity, 
                                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, envs.logger_facility, tap)?
                    }
                };
                
            LOGGER
                .set(syslog_inst)
                .map_err(|_e|
                    map_error!("syslog instance has been already initialized!")
                )?;
        },
        #[cfg(feature = "build_ext_net")]
        LoggerDst::LoTcp{ dst_host } => //SyslogNetTcp
        {
            let tap = SyslogNetTcp::new(dst_host, None, None)?;
            
            let syslog_inst = 
                match envs.logger_formatter
                {
                    SyslogFormatters::FormatRfc3146 => 
                    {
                        openlog_with
                            ::<FormatRfc3146, SyslogNetTcp>(envs.logger_identity, 
                                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, envs.logger_facility, tap)?
                    },
                    SyslogFormatters::FormatRfc5424 => 
                    {
                        openlog_with
                            ::<FormatRfc5424, SyslogNetTcp>(envs.logger_identity, 
                                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, envs.logger_facility, tap)?
                    },
                    SyslogFormatters::FormatFile => 
                    {
                        openlog_with
                            ::<FormatFile, SyslogNetTcp>(envs.logger_identity, 
                                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, envs.logger_facility, tap)?
                    }
                };
                
            LOGGER
                .set(syslog_inst)
                .map_err(|_e|
                    map_error!("syslog instance has been already initialized!")
                )?;
        },

        #[cfg(feature = "build_ext_tls")]
        LoggerDst::LoTls{ dst_host, serv_name, root_cert_path } => 
        {
            let tap = SyslogTls::new2(dst_host, None, serv_name, root_cert_path, None)?;

            let syslog_inst = 
                match envs.logger_formatter
                {
                    SyslogFormatters::FormatRfc3146 => 
                    {
                        openlog_with
                            ::<FormatRfc3146, SyslogTls>(envs.logger_identity, 
                                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, envs.logger_facility, tap)?
                    },
                    SyslogFormatters::FormatRfc5424 => 
                    {
                        openlog_with
                            ::<FormatRfc5424, SyslogTls>(envs.logger_identity, 
                                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID,envs. logger_facility, tap)?
                    },
                    SyslogFormatters::FormatFile => 
                    {
                        openlog_with
                            ::<FormatFile, SyslogTls>(envs.logger_identity, 
                                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, envs.logger_facility, tap)?
                    }
                };
                
            LOGGER
                .set(syslog_inst)
                .map_err(|_e|
                    map_error!("syslog instance has been already initialized!")
                )?;
        },

         #[cfg(feature = "build_ext_file")]
        LoggerDst::LoFile{ dst_path } => 
        {
            let tap = SyslogFile::new(dst_path);

            let syslog_inst = 
                match envs.logger_formatter
                {
                    SyslogFormatters::FormatRfc3146 => 
                    {
                        openlog_with
                            ::<FormatRfc3146, SyslogFile>(envs.logger_identity, 
                                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, envs.logger_facility, tap)?
                    },
                    SyslogFormatters::FormatRfc5424 => 
                    {
                        openlog_with
                            ::<FormatRfc5424, SyslogFile>(envs.logger_identity, 
                                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, envs.logger_facility, tap)?
                    },
                    SyslogFormatters::FormatFile => 
                    {
                        openlog_with
                            ::<FormatFile, SyslogFile>(envs.logger_identity, 
                                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, envs.logger_facility, tap)?
                    }
                };
                
            LOGGER
                .set(syslog_inst)
                .map_err(|_e|
                    map_error!("syslog instance has been already initialized!")
                )?;
        }
    }

    return Ok(());
}

/// Sends message via logger.
pub 
fn logger_log(pri: Priority, msg: String)
{
    let Some(logger) = LOGGER.get()
        else { return; };

    let _ = logger.syslog(pri, msg);
}

/// Sends a message with the [Priority::LOG_DEBUG].
#[macro_export]
macro_rules! logger_dbg
{
    ($($arg:tt)*) => (
        $crate::logger::logger_log($crate::Priority::LOG_DEBUG, format!($($arg)*))
    )
}

/// Sends a message with the [Priority::LOG_INFO].
#[macro_export]
macro_rules! logger_info
{
    ($($arg:tt)*) => (
        $crate::logger::logger_log($crate::Priority::LOG_INFO, format!($($arg)*))
    )
}

/// Sends a message with the [Priority::LOG_ERR].
#[macro_export]
macro_rules! logger_error
{
    ($($arg:tt)*) => (
        $crate::logger::logger_log($crate::Priority::LOG_ERR, format!($($arg)*))
    )
}

/// Sends a message with the [Priority::LOG_WARNING].
#[macro_export]
macro_rules! logger_warn
{
    ($($arg:tt)*) => (
        $crate::logger::logger_log($crate::Priority::LOG_WARNING, format!($($arg)*))
    )
}

/// Sends a message with the [Priority::LOG_EMERG].
#[macro_export]
macro_rules! logger_emerg
{
    ($($arg:tt)*) => (
        $crate::logger::logger_log($crate::Priority::LOG_EMERG, format!($($arg)*))
    )
}

/// Sends a message with the user defined priority.
#[macro_export]
macro_rules! logger_custom
{
    ($prio:expr, $($arg:tt)*) => (
        $crate::logger::logger_log($prio, format!($($arg)*))
    )
}


#[test]
fn test_parsing_logger()
{
    let res = LoggerDst::from_str("local#").unwrap();
    assert_eq!(res, LoggerDst::LoLocal { dst_path: None });

    let res = LoggerDst::from_str("local#/var/run/syslogcustom").unwrap();
    assert_eq!(res, LoggerDst::LoLocal { dst_path: Some("/var/run/syslogcustom") });

    #[cfg(feature = "build_ext_net")]
    {
        let res = LoggerDst::from_str("udp#127.0.0.1:80").unwrap();
        assert_eq!(res, LoggerDst::LoUdp { dst_host: "127.0.0.1:80" });

        let res = LoggerDst::from_str("udp#[fe00:::0]:80").unwrap();
        assert_eq!(res, LoggerDst::LoUdp { dst_host: "[fe00:::0]:80" });

        let res = LoggerDst::from_str("udp#www.mydomain.tdl:80").unwrap();
        assert_eq!(res, LoggerDst::LoUdp { dst_host: "www.mydomain.tdl:80" });


        let res = LoggerDst::from_str("tcp#127.0.0.1:80").unwrap();
        assert_eq!(res, LoggerDst::LoTcp { dst_host: "127.0.0.1:80" });

        let res = LoggerDst::from_str("tcp#[fe00:::0]:80").unwrap();
        assert_eq!(res, LoggerDst::LoTcp { dst_host: "[fe00:::0]:80" });

        let res = LoggerDst::from_str("tcp#www.mydomain.tdl:80").unwrap();
        assert_eq!(res, LoggerDst::LoTcp { dst_host: "www.mydomain.tdl:80" });
    }


    #[cfg(feature = "build_ext_tls")]
    {
        let res = LoggerDst::from_str("tls#127.0.0.1:80#servername#/tmp/a1.crt").unwrap();
        assert_eq!(res, LoggerDst::LoTls { dst_host: "127.0.0.1:80", serv_name: "servername", root_cert_path: "/tmp/a1.crt" });

        let res = LoggerDst::from_str("tls#[fe00:::0]:80#servername#/tmp/a1.crt").unwrap();
        assert_eq!(res, LoggerDst::LoTls { dst_host: "[fe00:::0]:80", serv_name: "servername", root_cert_path: "/tmp/a1.crt" });

        let res = LoggerDst::from_str("tls#www.mydomain.tdl#servername#/tmp/a1.crt").unwrap();
        assert_eq!(res, LoggerDst::LoTls { dst_host: "www.mydomain.tdl", serv_name: "servername", root_cert_path: "/tmp/a1.crt" });
    }

    #[cfg(feature = "build_ext_file")]
    {
        let res = LoggerDst::from_str("file#/tmp/file1.txt").unwrap();
        assert_eq!(res, LoggerDst::LoFile { dst_path: "/tmp/file1.txt" });
    }
}

#[test]
fn test_env_set()
{
    unsafe { env::set_var(SYSLOG_LOGGER_DST_URI, "file#/tmp/test_log1.txt") };
    unsafe { env::set_var(SYSLOG_LOGGER_LOG_FACILITY, "LOG_DAEMON") };
    unsafe { env::set_var(SYSLOG_LOGGER_LOG_FORMATTER, "FILE") };
    unsafe { env::set_var(SYSLOG_LOGGER_LOG_IDENTITY, "test_logger_file") };

    let re = EnvVars::read_env(None).unwrap().unwrap();

    assert_eq!(re.logger_type_res.as_str(), "file#/tmp/test_log1.txt");
    assert_eq!(re.logger_facility, LogFacility::LOG_DAEMON);
    assert_eq!(re.logger_formatter, SyslogFormatters::FormatFile);
    assert_eq!(re.logger_identity.as_ref().map(|v| v.as_str()), Some("test_logger_file"));
}

#[test]
fn test_env_set_suffix()
{
    let suf_xio = Some("XIO");
    unsafe { env::set_var(derive_suffix(suf_xio, SYSLOG_LOGGER_DST_URI).as_ref(), "file#/tmp/xio_out.txt") };
    unsafe { env::set_var(derive_suffix(suf_xio, SYSLOG_LOGGER_LOG_FACILITY).as_ref(), "LOG_DAEMON") };
    unsafe { env::set_var(derive_suffix(suf_xio, SYSLOG_LOGGER_LOG_FORMATTER).as_ref(), "FILE") };
    unsafe { env::set_var(derive_suffix(suf_xio, SYSLOG_LOGGER_LOG_IDENTITY).as_ref(), "xio_rs") };

    let suf_so9 = Some("SOCKET9");
    unsafe { env::set_var(derive_suffix(suf_so9, SYSLOG_LOGGER_DST_URI).as_ref(), "file#/tmp/socket9_out.txt") };
    unsafe { env::set_var(derive_suffix(suf_so9, SYSLOG_LOGGER_LOG_FACILITY).as_ref(), "LOG_DAEMON") };
    unsafe { env::set_var(derive_suffix(suf_so9, SYSLOG_LOGGER_LOG_FORMATTER).as_ref(), "FILE") };
    unsafe { env::set_var(derive_suffix(suf_so9, SYSLOG_LOGGER_LOG_IDENTITY).as_ref(), "socket9") };

    let re = EnvVars::read_env(suf_so9).unwrap().unwrap();

    assert_eq!(re.logger_type_res.as_str(), "file#/tmp/socket9_out.txt");
    assert_eq!(re.logger_facility, LogFacility::LOG_DAEMON);
    assert_eq!(re.logger_formatter, SyslogFormatters::FormatFile);
    assert_eq!(re.logger_identity.as_ref().map(|v| v.as_str()), Some("socket9"));
}

#[test]
fn test_env_set2()
{
    unsafe { env::remove_var(SYSLOG_LOGGER_DST_URI) };
    unsafe { env::set_var(SYSLOG_LOGGER_LOG_FACILITY, "LOG_DAEMON") };
    unsafe { env::set_var(SYSLOG_LOGGER_LOG_FORMATTER, "FILE") };
    unsafe { env::set_var(SYSLOG_LOGGER_LOG_IDENTITY, "test_logger_file") };

    let re = EnvVars::read_env(None).unwrap();
    assert_eq!(re.is_none(), true);
}