syslog-rs 6.6.1

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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
/*-
 * 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::{fmt, thread};
use std::sync::{Arc, Mutex, Weak};
use std::sync::atomic::{AtomicBool, Ordering};

use crate::formatters::{DefaultSyslogFormatter, SyslogFormatter};
use crate::sync::syslog_sync_internal::SyslogSocketLockless;
use crate::sync::{SyStreamSyslogApi, LogItems, SyStream, SyStreamPri, DefaultLocalSyslogDestination};
use crate::sync::DefaultQueueAdapter;

use crate::{map_error, SyslogDestination};


use crate::common::*;
use crate::error::SyRes;


/// A wrapper for the data commands in the queue
pub enum SyCmd<F: SyslogFormatter, D: SyslogDestination, S: SyslogQueueChannel<F, D>>
{
    /// A message to syslog server
    Syslog
    {
        pri: Priority,
        msg: F
    },

    /// A reuest to change logmask
    Logmask
    {
        logmask: i32, 
        loopback: S::OneShotChannelSnd<i32>,
    },

    /// A request to change identity
    ChangeIdentity
    {
        identity: Option<String>,
    },

    /// Updates the tap settings
    UpdateTap
    {
        tap_type: D,//TapTypeData,
        loopback: S::OneShotChannelSnd<SyRes<()>>,
    },

    ConnectLog
    {
        loopback: S::OneShotChannelSnd<SyRes<()>>
    },

    DisconnectLog
    {
        loopback: S::OneShotChannelSnd<SyRes<()>>
    },

    /// A request to rotate file or reconnect.
    Reconnect,

    /// A request to stop processing and quit
    #[allow(unused)]
    Stop,
}


impl<F: SyslogFormatter, D: SyslogDestination, S: SyslogQueueChannel<F, D>> SyCmd<F, D, S>
{
    /// Construct a message with data to send.
    pub(crate) 
    fn form_syslog(pri: Priority, msg: F) -> Self
    {
        return 
            Self::Syslog
            {
                pri, msg
            };
    }

    pub(crate) 
    fn form_connectlog() -> (Self, S::OneShotChannelRcv<SyRes<()>>)
    {
        let (tx, rx) = S::create_oneshot_channel::<SyRes<()>>();

        return 
            (Self::ConnectLog{ loopback: tx }, rx);
    }

    pub(crate) 
    fn form_disconnectlog() -> (Self, S::OneShotChannelRcv<SyRes<()>>)
    {
        let (tx, rx) = S::create_oneshot_channel::<SyRes<()>>();

        return 
            (Self::DisconnectLog{ loopback: tx }, rx);
    }

    /// Constructs a message to make logmask with or without previous PRI.
    /// 
    /// # Arguments
    /// 
    /// * `logmask` - a new logmask
    pub(crate) 
    fn form_logmask(logmask: i32) -> (Self, S::OneShotChannelRcv<i32>)
    {
        let (tx, rx) = S::create_oneshot_channel::<i32>();

        return 
            (Self::Logmask{ logmask, loopback: tx }, rx);
    }

    /// Constructs a message which should change the identity (appname) of the
    /// instance.
    pub(crate) 
    fn form_change_ident(identity: Option<String>) -> Self
    {
        return 
            Self::ChangeIdentity
            {
                identity: identity
            };
    }

    /// Constructs a message which changes the destination of the log messages i.e
    /// changing path of the dst file or address. The `new_tap_type` 
    /// should be the same variant [TapTypeData] as previous.
    pub(crate)
    fn form_update_tap(new_tap_type: D/*TapTypeData*/) -> (Self, S::OneShotChannelRcv<SyRes<()>>)
    {
        let (tx, rx) = S::create_oneshot_channel::<SyRes<()>>();

        return (
            Self::UpdateTap  
            { 
                tap_type: new_tap_type,
                loopback: tx
            },
            rx
        );
    }

    /// Constructs a message to handle SIGHUP. This is usefull only when the instance
    /// is writing directly into the file. Or just reconnect.
    pub(crate) 
    fn form_reconnect() -> Self
    {
        return Self::Reconnect;
    }

    /// Constructs a message to stop thread gracefully. After receiving this
    /// message a thread will quit and all messages that would be sent after
    /// this message will be cleared from queue and a new messages will not be
    /// received.
    #[allow(unused)]
    pub(crate) 
    fn form_stop() -> Self
    {
        return Self::Stop;
    }
}

/// Internal struct of the syslog client thread.
struct SyslogInternal<F: SyslogFormatter, D: SyslogDestination, S: SyslogQueueChannel<F, D>>
{
    /// A explicit stop flag
    run_flag: Arc<AtomicBool>,

    /// commands channel
    tasks: S::ChannelRcv,

    /// Log config
    log_items: LogItems,

    /// socket
    socket: SyslogSocketLockless<D>,
}



impl<F, D, S> SyslogInternal<F, D, S>
where F: SyslogFormatter, D: SyslogDestination, S: SyslogQueueChannel<F, D>
{
    fn new(log_items: LogItems, socket: SyslogSocketLockless<D>) -> SyRes<(Self, S::ChannelSnd, Weak<AtomicBool>)>
    {
        // control flag
        let run_flag: Arc<AtomicBool> = Arc::new(AtomicBool::new(true));
        let run_control = Arc::downgrade(&run_flag);

        // creating queue for messages
        let (sender, receiver) = S::create_channel();

        // creating internal syslog struct
        let mut inst = 
            SyslogInternal
            {
                run_flag: run_flag,
                tasks: receiver,
                log_items: log_items,
                socket: socket
            };

        if inst.log_items.logstat.contains(LogStat::LOG_NDELAY) == true
        {
            inst.socket.connectlog()?;
        }

        return Ok((inst, sender, run_control));
    }

    fn thread_worker(mut self)
    {
        loop
        {
            // self will be dropped as soon as thread will be stopped
            if self.run_flag.load(Ordering::Relaxed) == false
            {
                // force leave
                break;
            }	

            match self.tasks.q_recv_blocking()
			{
				Some(task) =>
				{
                    match task
                    {
                        SyCmd::Syslog{ pri, msg } =>
                        {
                            let Some(formatted) = self.log_items.vsyslog1_msg::<F, D>(pri, &msg)
                                else { continue };

                            let _ = self.socket.vsyslog1(formatted.1, formatted.0);
                        },
                        SyCmd::Logmask{ logmask, loopback } =>
                        {
                            let pri = self.log_items.set_logmask(logmask);

                            let _ = loopback.send_once_blocking(pri);
                        },
                        SyCmd::ChangeIdentity{ identity } =>
                        {
                            self.log_items.set_identity(identity.as_ref().map(|v| v.as_str()));
                        },

                        SyCmd::UpdateTap{ tap_type, loopback } =>
                        {
                            let res = self.socket.update_tap_data(tap_type);
                            
                            if let Err(Err(e)) = loopback.send_once_blocking(res)
                            {
                                self.log_items.logstat.send_to_stderr(&e.to_string());
                            }
                        },

                        SyCmd::ConnectLog{ loopback} => 
                        {
                            if let Err(Err(e)) = loopback.send_once_blocking(self.socket.connectlog())
                            {
                                self.log_items.logstat.send_to_stderr(&e.to_string());
                            }
                        },

                        SyCmd::DisconnectLog{ loopback} => 
                        {
                            if let Err(Err(e)) = loopback.send_once_blocking(self.socket.disconnectlog())
                            {
                                self.log_items.logstat.send_to_stderr(&e.to_string());
                            }
                        },

                        SyCmd::Reconnect =>
                        {
                            if let Err(e) = self.socket.disconnectlog()
                            {
                                self.log_items.logstat.send_to_stderr(&e.to_string());
                            }
                                
                            if let Err(e) = self.socket.connectlog()
                            {
                                self.log_items.logstat.send_to_stderr(&e.to_string());
                            }
                        },
                        SyCmd::Stop =>
                        {
                            // ignore the rest
                            break;
                        }
                    }
                },
                None =>
                {
                    break;
                }
            } // match

        } // loop

        return;
    }
}

/// A trait which should be implemented by the channel provider which forms a command queue.
/// This trait provides a blocking receive interface on the receiver side.
pub trait SyslogQueueChanRcv<F: SyslogFormatter, D: SyslogDestination, S: SyslogQueueChannel<F, D>>: fmt::Debug + Send
{
    /// Receive from channel in blocking mode.
    fn q_recv_blocking(&mut self) -> Option<SyCmd<F, D, S>>;
}

/// A trait which should be implemented by the channel provider which forms a command queue.
/// This trait provides both or either the blocking send interface.
#[allow(async_fn_in_trait)]
pub trait SyslogQueueChanSnd<F: SyslogFormatter, D: SyslogDestination, S: SyslogQueueChannel<F, D>>: fmt::Debug + Clone
{
    /// Sends the message over the channel in blocking mode.
    fn q_send_blocking(&self, msg: SyCmd<F, D, S>) -> SyRes<()>;

    /// Sends the message over the channel in async mode. By default, it returns error.
    async fn q_send(&self, _msg: SyCmd<F, D, S>) -> SyRes<()>
    {
        crate::throw_error!("async is not availabe here"); 
    }
}

/// A trait which should be implemented by the channel provider which forms a command queue.
/// This trait provides a Oneshot channel a receive interface for both sync and async modes.
#[allow(async_fn_in_trait)]
pub trait SyslogQueueOneChanRcv<C>
{
    /// Receives once from the channel in sync mode.
    fn recv_once_blocking(self) -> SyRes<C>;

    /// Receives once from the channel in async mode. By default, it returns error if not 
    /// implemented.
    async fn recv_once(self) -> SyRes<C> where Self: Sized
    {
        crate::throw_error!("async is not availabe here"); 
    }
}

/// A trait which should be implemented by the channel provider which forms a command queue.
/// This trait provides a Oneshot channel a send interface for blocking mode.
pub trait SyslogQueueOneChanSnd<C: Send>: fmt::Debug + Send
{
    /// Send to channel in blocing mode.
    fn send_once_blocking(self, data: C) -> Result<(), C>;
}

/// A trait which should be implemented by the channel provider which forms a command queue.
/// This trait provides a common interface which includes everything i.e channel, oneshot 
/// channel and manipulations.
pub trait SyslogQueueChannel<F: SyslogFormatter, D: SyslogDestination>: fmt::Debug + Send + Clone + 'static
{
    const ADAPTER_NAME: &'static str;
    
    /// A send side of the channel type.
    type ChannelSnd: SyslogQueueChanSnd<F, D, Self>;
    
    /// A receive side of the channel type.
    type ChannelRcv: SyslogQueueChanRcv<F, D, Self>;

    /// A oneshot send side of the channel type.
    type OneShotChannelSnd<C: Send + fmt::Debug>: SyslogQueueOneChanSnd<C>;

    /// A oneshor receive side of the channel type.
    type OneShotChannelRcv<C>: SyslogQueueOneChanRcv<C>;

    /// Creates unbounded channel.
    fn create_channel() -> (Self::ChannelSnd, Self::ChannelRcv);   

    /// Creates oneshot channel.
    fn create_oneshot_channel<C: Send + fmt::Debug>() -> (Self::OneShotChannelSnd<C>, Self::OneShotChannelRcv<C>);
}



/// A parallel, shared instance of the syslog client which is running in the 
/// separate thread and uses a crossbeam channel to receive the messages from 
/// the program. It is also capable to combine sync and async i.e sync code and
/// async code is writing to the same syslog connection.
/// 
/// For this isntance a [SyslogApi] and [SyStreamApi] are implemented.
/// 
/// Also if `async` is enabled, a [AsyncSyslogQueueApi] is implemented.
/// 
/// ```ignore
/// let log = 
///     QueuedSyslog::openlog(
///         Some("test1"), 
///         LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
///         LogFacility::LOG_DAEMON,
///         SyslogLocal::new()
///     );
/// ```
/// 
/// ```ignore
/// let log = 
///     QueuedSyslog
///         ::<DefaultQueueAdapter, 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(|| 
///         {
///             QueuedSyslog
///                 ::<DefaultQueueAdapter, DefaultSyslogFormatter, SyslogLocal>
///                 ::openlog_with(
///                     Some("test1"), 
///                     LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
///                     LogFacility::LOG_DAEMON,
///                     SyslogLocal::new()
///                 )
///                 .unwrap()
///         }
///     );
/// ```
/// 
/// A stream is availble via [SyStreamApi].
/// 
/// ```ignore
/// let _ = write!(SYSLOG.stream(Priority::LOG_DEBUG), "test {} 123 stream test ", d);
/// ```
/// 
/// # Generics
/// 
/// * `S` - a [SyslogQueueChannel] a MPSC provider.
/// 
/// * `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 QueuedSyslog<S = DefaultQueueAdapter, F = DefaultSyslogFormatter, D = DefaultLocalSyslogDestination>
where F: SyslogFormatter, D: SyslogDestination, S: SyslogQueueChannel<F, D>
{   
    /// Control flag
    run_control: Weak<AtomicBool>,

    /// commands channel
    pub(crate) tasks: S::ChannelSnd,//q_adapter::SendChannelSyCmd<D>,

    /// process thread
    thread: Arc<Mutex<Option<thread::JoinHandle<()>>>>,

    /// phantom for [SyslogFormatter]
    _p: PhantomData<F>,

    /// phantom for [SyslogDestination]
    _p2: PhantomData<D>,
}


unsafe impl<F, D, S> Send for QueuedSyslog<S, F, D> 
where F: SyslogFormatter, D: SyslogDestination, S: SyslogQueueChannel<F, D>
{}


impl<F, D, S> Drop for QueuedSyslog<S, F, D>
where F: SyslogFormatter, D: SyslogDestination, S: SyslogQueueChannel<F, D>
{
    fn drop(&mut self) 
    {
        if let Some(ctrl) = self.run_control.upgrade()
        {   
            ctrl.store(false, Ordering::SeqCst);

            if let Err(_e) = self.tasks.q_send_blocking(SyCmd::form_stop())
            {

            }

            let join_handle = self.thread.lock().unwrap().take().unwrap();

            let _ = join_handle.join();
        }
    }
}

impl QueuedSyslog
{
    /// Opens a default connection to the local syslog server with default formatter with
    /// formatter [SyslogFormatter] and destination [SyslogLocal].
    /// 
    /// # 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>
    {
        // creating internal syslog struct

         let log_items = 
                LogItems::new(ident, 0xff, logstat, facility);

        let stream = 
            SyslogSocketLockless::<DefaultLocalSyslogDestination>::new(logstat, net_tap_prov)?;

        let (inst, sender, run_ctrl) = 
            SyslogInternal
                ::<DefaultSyslogFormatter, DefaultLocalSyslogDestination, DefaultQueueAdapter>
                ::new(log_items, stream)?;
        
        
        let thr_name: String = "syslog_queue/0".into();

        // initiate a thread
        let thread_hnd = 
            thread::Builder::new()
                .name(thr_name.clone())
                .spawn(move || 
                    SyslogInternal
                        ::<DefaultSyslogFormatter, DefaultLocalSyslogDestination, DefaultQueueAdapter>
                        ::thread_worker(inst)
                )
                .map_err(|e| 
                    map_error!("{} thread spawn failed. {}", thr_name, e)
                )?;

        // creating a syslog public struct instance
        let ret = 
            Self
            {
                run_control: run_ctrl,
                tasks: sender,
                thread: Arc::new(Mutex::new(Some(thread_hnd))),
                _p: PhantomData,
                _p2: PhantomData
            };

        return Ok(ret);
    }
}

impl<F, D, S> QueuedSyslog<S, F, D>
where F: SyslogFormatter, D: SyslogDestination, S: SyslogQueueChannel<F, D>
{
    /// Opens a default connection to the local syslog server with default formatter with
    /// provided generics.
    /// 
    /// # 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_with(ident: Option<&str>, logstat: LogStat, facility: LogFacility, net_tap_prov: D) -> SyRes<QueuedSyslog<S, F, D>>
    {
        // creating internal syslog struct

         let log_items = 
                LogItems::new(ident, 0xff, logstat, facility);

        let stream = 
            SyslogSocketLockless::<D>::new(logstat, net_tap_prov)?;

        let (inst, sender, run_ctrl) = 
            SyslogInternal::<F, D, S>::new(log_items, stream)?;
        
        
        let thr_name: String = "syslog_queue/0".into();

        // initiate a thread
        let thread_hnd = 
            thread::Builder::new()
                .name(thr_name.clone())
                .spawn(move || SyslogInternal::<F, D, S>::thread_worker(inst))
                .map_err(|e| 
                    map_error!("{} thread spawn failed. {}", thr_name, e)
                )?;

        // creating a syslog public struct instance
        let ret = 
            Self
            {
                run_control: run_ctrl,
                tasks: sender,
                thread: Arc::new(Mutex::new(Some(thread_hnd))),
                _p: PhantomData::<F>,
                _p2: PhantomData::<D>,
            };

        return Ok(ret);
    }
}


impl<F: SyslogFormatter, D: SyslogDestination, S: SyslogQueueChannel<F, D>> QueuedSyslog<S, F, D>
{
    /// Connects the current instance to the syslog server (destination).
    pub 
    fn connectlog(&self) -> SyRes<()>
    {
        let (sy_cmd, loopback) = 
            SyCmd::form_connectlog();

        self.tasks.q_send_blocking(sy_cmd)?;

        return 
            loopback
                .recv_once_blocking()?;
    }

    /// 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 (sy_cmd, loopback) = 
            SyCmd::form_logmask(logmask);

        self.tasks.q_send_blocking(sy_cmd)?;

        return 
            loopback
                .recv_once_blocking();
    }

    /// Closes connection to the syslog server (destination).
    pub 
    fn closelog(&self) -> SyRes<()> 
    {
        let (sy_cmd, loopback) = 
            SyCmd::form_disconnectlog();

        // send stop
        self.tasks.q_send_blocking(sy_cmd)?;

        return 
            loopback
                .recv_once_blocking()?;
    }

    /// 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.
    pub 
    fn syslog(&self, pri: Priority, fmt: F) -> SyRes<()>
    {
        // even if the thread is in a process of termination, there is
        // no need to sync access to the run_control field as even if
        // syslog thread will terminate before someone push something on the
        // queue, it will be left in the queue until the end of program's time.
        
        let sy_cmd = SyCmd::form_syslog(pri, fmt);

        return self.tasks.q_send_blocking(sy_cmd);
    }

    /// 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<()>
    {
        let sy_cmd = 
            SyCmd::form_change_ident(ident.map(|v| v.to_string()));

        return 
            self.tasks.q_send_blocking(sy_cmd);
    }

    /// 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.tasks.q_send_blocking(SyCmd::form_reconnect());
    }

    /// 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<()>
    {
        let (tap_data_cmd, loopback) = SyCmd::form_update_tap(tap_data);

        self.tasks.q_send_blocking(tap_data_cmd)?;

        return 
            loopback
                .recv_once_blocking()?;
    }
}

impl<F, D, S> QueuedSyslog<S, F, D>
where F: SyslogFormatter, D: SyslogDestination, S: SyslogQueueChannel<F, D>
{
    /// 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, D, S> SyStreamSyslogApi<F, D>  
for &QueuedSyslog<S, F, D>
where F: SyslogFormatter, D: SyslogDestination, S: SyslogQueueChannel<F, D>
{
    type SYSLOG<'t> = &'t QueuedSyslog<S, F, D>;

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


/// A queued implementation for ASYNC.
#[cfg(all(feature = "build_with_queue", feature = "async_enabled"))]
pub mod syslog_async_queue
{
    use crate::error::SyRes;
    use crate::sy_sync_queue::{SyCmd, SyslogQueueChanSnd, SyslogQueueChannel, SyslogQueueOneChanRcv};
    use crate::Priority;
    use crate::{formatters::SyslogFormatter, SyslogDestination, QueuedSyslog};
    use crate::a_sync::syslog_trait::AsyncSyslogQueueApi;

    impl<F: SyslogFormatter, D: SyslogDestination, S: SyslogQueueChannel<F, D>> AsyncSyslogQueueApi<F, D> 
    for QueuedSyslog<S, F, D>
    {
        async 
        fn a_connectlog(&mut self) -> SyRes<()> 
        {
            let (sy_cmd, loopback) = 
                SyCmd::form_connectlog();

            self.tasks.q_send(sy_cmd).await?;

            return 
                loopback
                    .recv_once()
                    .await?;
        }

        /// Sets the logmask to filter out the syslog calls. This function behaves 
        /// differently as it behaves in syslog_sync.rs or syslog_async.rs.
        /// It may return an error if: syslog thread had exit and some thread calls
        /// this function. Or something happened with channel. 
        /// This function blocks until the previous mask is received.
        /// 
        /// 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) 
        async 
        fn a_setlogmask(&self, logmask: i32) -> SyRes<i32>
        {
            let (sy_cmd, loopback) = 
                SyCmd::form_logmask(logmask);

            self.tasks.q_send(sy_cmd).await?;

            return 
                loopback
                    .recv_once()
                    .await;
        }

        /// Closes connection to the syslog server
        async 
        fn a_closelog(&self) -> SyRes<()>
        {
            let (sy_cmd, loopback) = 
                SyCmd::form_disconnectlog();

            // send stop
            self.tasks.q_send(sy_cmd).await?;

            return 
                loopback
                    .recv_once()
                    .await?;
        }

        /// Similar to libc, syslog() sends data to syslog server, but asynchroniously.
        /// 
        /// # Arguments
        ///
        /// * `pri` - a priority [Priority]
        ///
        /// * `fmt` - a program's message to be sent as payload. The message is encoded with the
        ///     [SyslogFormatter] and may be different for different formatters.
        #[inline]
        async 
        fn a_syslog(&self, pri: Priority, fmt: F) -> SyRes<()>
        {
            let sy_cmd = SyCmd::form_syslog(pri, fmt);

            return self.tasks.q_send(sy_cmd).await;
        }


        /// Performs the reconnection to the syslog server or file re-open.
        /// 
        /// # Returns
        /// 
        /// A [Result] is retured as [SyRes].
        /// 
        /// * [Result::Ok] - with empty inner type.
        /// 
        /// * [Result::Err] - an error code and description
        async 
        fn a_reconnect(&self) -> SyRes<()>
        {
            return 
                self.tasks.q_send(SyCmd::form_reconnect()).await;
        }

        async 
        fn a_change_identity(&self, ident: &str) -> SyRes<()> 
        {
            let sy_cmd = 
                SyCmd::form_change_ident(Some(ident.to_string()));

            return 
                self.tasks.q_send(sy_cmd).await;
        }

        /// Updates the inner instance destionation i.e path to file
        /// or server address. The type of destination can not be changed.
        /// 
        /// This function disconnects from syslog server if previously was 
        /// connected (and reconnects if was connected previously).
        /// 
        /// # Arguments 
        /// 
        /// * `new_tap` - a consumed instance of type `D` [SyslogDestination]
        /// 
        /// # Returns 
        /// 
        /// A [SyRes] is returned. An error may be returned if:
        /// 
        /// * connection to server was failed
        /// 
        /// * incorrect type
        /// 
        /// * disconnect frm server failed
        async 
        fn a_update_tap_data(&self, new_tap: D) -> SyRes<()>
        {
            let (tap_data_cmd, loopback) = SyCmd::form_update_tap(new_tap);

            self.tasks.q_send(tap_data_cmd).await?;

            return 
                loopback
                    .recv_once()
                    .await?;
        }
    }
}