mdlogger 0.1.2

Multi-device logging system library crate
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
use crate::{
    interfaces::{LogHandler, LogHandlerFactory}, 
    logmessage::LogMessage, 
    pretty_function, 
    types::{LogHandlerBase, LogMsgType, LOG_MSG_TYPE_NUM}, 
    utils::{
        check_log_handler_common_parameters, get_log_handler_common_parameters,
        network_index, network_interface_exists
    }
};
use std::{
    fmt::Display, 
    io::{self, ErrorKind}, 
    net::{
        IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr
    }, 
    str::FromStr
};

use serde_json::{json, Value};
use socket2::{Domain, SockAddr, Socket, Type};


const UDP_NETWORK_PROTOCOL: &str = "udp";
const MCAST_NETWORK_PROTOCOL: &str = "mcast";
const TCP_NETWORK_PROTOCOL: &str = "tcp";
const VALID_NETWORK_PROTOCOLS: [&str; 2] = [
    UDP_NETWORK_PROTOCOL,
    TCP_NETWORK_PROTOCOL
];

const PROTOCOL_KEY: &str = "protocol";
const REMOTE_ADDRESS_KEY: &str = "remote_address";
const MULTICAST_IF_KEY: &str = "multicast_if";
const REMOTE_PORT_KEY: &str = "remote_port";
const SUN_PATH_KEY: &str = "sun_path";

// Network protocol enumeration
enum NetworkProtocol {
    UdpProtocol(String),
    MCastProtocol(String),
    TcpProtocol(String)
}

// Network protocol enumeration implementation
impl NetworkProtocol {
    // Return Network protocol value as text
    fn unwrap(&self) -> &String {
        match self {
            Self::UdpProtocol(value) => { value }
            Self::MCastProtocol(value) => { value }
            Self::TcpProtocol(value) => { value }
        }
    }
}

// PartialEq trait implementation for Network protocol enumeration
impl PartialEq for NetworkProtocol {
    fn eq(&self, other: &Self) -> bool {
        self.unwrap() == other.unwrap()
    }
}

// Network protocol format error object
struct NetworkProtocolFormatError {
    message: String
}

// Display trait implementation for Network protocol format error object
impl Display for NetworkProtocolFormatError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

// FromStr trait implementation for Network protocol enumeration
impl FromStr for NetworkProtocol {
    type Err = NetworkProtocolFormatError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s_lowercase = s.to_lowercase();
        if UDP_NETWORK_PROTOCOL == s_lowercase {
            Ok(NetworkProtocol::UdpProtocol(UDP_NETWORK_PROTOCOL.to_string()))
        } else if MCAST_NETWORK_PROTOCOL == s_lowercase {
            Ok(NetworkProtocol::MCastProtocol(MCAST_NETWORK_PROTOCOL.to_string()))
        } else if TCP_NETWORK_PROTOCOL == s_lowercase {
            Ok(NetworkProtocol::TcpProtocol(TCP_NETWORK_PROTOCOL.to_string()))
        } else {
            Err(NetworkProtocolFormatError{message: format!("Invalid network protocol '{}' valid are: {}",
                s, VALID_NETWORK_PROTOCOLS.join(", "))})
        }
    }
}

// Display trait implementatio for Network protocol enumeration
impl Display for NetworkProtocol {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.unwrap())
    }
}


// Network protocol factory object
pub (crate) struct NetworkLogHandlerFactory {

}

// LogHandlerFactory trait implementation for Network protocol factory object 
impl LogHandlerFactory for NetworkLogHandlerFactory {
    
    // Return log handler type name
    fn type_name(&self) -> &str {
        "network"
    }

    // Check Network log handler configuration parametrs 
    // * `self` itself reference
    // * `settings` reference to mdlogger settings file
    // * `log_handler_name` log handler name (SECTION name of settings file)
    fn check_parameters(&self, settings: &rssettings::Settings, log_handler_name: &str) -> Result<(), String> {
        check_log_handler_common_parameters(settings, self.type_name(), log_handler_name)?;

        let network_protocol = settings.get(log_handler_name,PROTOCOL_KEY, "".to_string());
        if network_protocol.error.len() > 0 {
            return Err(format!("Log handler: '{}' type: '{}' error: '{}'", 
                    log_handler_name, self.type_name(), network_protocol.error));
        }
        if let Err(parse_error) = network_protocol.value.parse::<NetworkProtocol>() {
            return Err(format!("Log handler: '{}' type: '{}' error: '{}'",
                    log_handler_name, self.type_name(), parse_error));
        }

        let remote_address = settings.get(log_handler_name, REMOTE_ADDRESS_KEY, "".to_string());
        if remote_address.error.len() > 0 {
            return Err(format!("Log handler: '{}' type: '{}' error: '{}'", 
                    log_handler_name, self.type_name(), remote_address.error));
        }


        match remote_address.value.parse::<IpAddr>() {
            Ok(address) => {
                if address.is_multicast() {
                    if network_protocol.value != MCAST_NETWORK_PROTOCOL {
                        return Err(format!("Log handler: '{}' type: '{}' error: {} is multicast address but {} is unicast",
                            log_handler_name, self.type_name(), REMOTE_ADDRESS_KEY, PROTOCOL_KEY));
                    }
                    let multicast_if = settings.get(log_handler_name, MULTICAST_IF_KEY, "".to_string()).value;
                    

                    if !multicast_if.is_empty() {
                        match multicast_if.parse::<IpAddr>() {
                            Ok(if_addr) => {
                                if if_addr.is_multicast() {
                                    return Err(format!("Log handler: '{}' type: '{}' error: {} has to be an unicast address",
                                        log_handler_name, self.type_name(), MULTICAST_IF_KEY));
                                }
                                if address.is_ipv4() && if_addr.is_ipv6() {
                                    return Err(format!("Log handler: '{}' type: '{}' error: {} is and IPV4 addrees while {} is and IVP6 address",
                                        log_handler_name, self.type_name(), REMOTE_ADDRESS_KEY, MULTICAST_IF_KEY));
                                }
                                if address.is_ipv6() && if_addr.is_ipv4() {
                                    return Err(format!("Log handler: '{}' type: '{}' error: {} is and IPV6 addrees while {} is and IVP4 address",
                                        log_handler_name, self.type_name(), REMOTE_ADDRESS_KEY, MULTICAST_IF_KEY));

                                }
                            },
                            Err(parse_error) => {
                                return Err(format!("Log handler: '{}' type: '{}' error: '{}' {}",
                                log_handler_name, self.type_name(), MULTICAST_IF_KEY, parse_error));                            
                            }
                        } 
                        if false == network_interface_exists(&multicast_if) {
                            return Err(format!("Log handler: '{}' type: '{}' error: {} '{}' is not a valid local network interface address",
                                log_handler_name, self.type_name(), MULTICAST_IF_KEY, multicast_if));
                        }
                    }
                } else {
                    if network_protocol.value == MCAST_NETWORK_PROTOCOL {
                        return Err(format!("Log handler: '{}' type: '{}' error: {} is unicast but {} is multicast",
                            log_handler_name, self.type_name(), REMOTE_ADDRESS_KEY, PROTOCOL_KEY));
                    }
                }        
            },
            Err(parse_error) =>  {
                return Err(format!("Log handler: '{}' type: '{}' error: '{}' {}",
                    log_handler_name, self.type_name(), REMOTE_ADDRESS_KEY, parse_error));        
            }
        }

        let remote_port = settings.get(log_handler_name, REMOTE_PORT_KEY, 0);

        if remote_port.error.len() > 0 {
            return Err(format!("Log handler: '{}' type: '{}' error: '{}'", 
                    log_handler_name, self.type_name(), remote_port.error));
        }

        if (remote_port.value <= 0) || (remote_port.value > u16::MAX as i32) {
            return Err(format!("Log handler: '{}' type: '{}' error: '{}' has value '{}' that is out of range 1..{} ", 
                    log_handler_name, self.type_name(), REMOTE_PORT_KEY, remote_port.value, u16::MAX));
        }

        Ok(())
    }

    // Create a Network log handler
    // * `self` itself reference
    // * `settings` reference to mdlogger settings file
    // * `log_handler_name` log handler name (SECTION name of settings file)
    // * `appname` application name as passed to mdlogger::initialize funtion
    // * `appver` application version as passed to mdlogger::initialize funtion
    fn create_log_handler(&self, settings: &rssettings::Settings, log_handler_name: &str, appname: &str, appver: &str) -> Box<dyn crate::interfaces::LogHandler> {
        let mut enabled = false;
        let mut pattern =  String::new();
        let mut timestamp_format = String::new();
        let mut msg_types_enabled: [bool; LOG_MSG_TYPE_NUM] = [false, false, false, false, false]; 
        let mut msg_types_text: [String; LOG_MSG_TYPE_NUM] = [
            String::new(), String::new(), String::new(),
            String::new(), String::new()
        ];
        let mut message_format = String::new();
        get_log_handler_common_parameters(
            &mut enabled, &mut pattern, &mut timestamp_format,
            &mut msg_types_enabled, &mut msg_types_text,
            &mut message_format, settings, log_handler_name,
        pretty_function!());

        let protocol_type = settings.get(log_handler_name, PROTOCOL_KEY, "".to_string()).value;
        let protocol: NetworkProtocol = protocol_type.parse().unwrap_or(NetworkProtocol::UdpProtocol(UDP_NETWORK_PROTOCOL.to_string()));

        let mut address = settings.get(log_handler_name, REMOTE_ADDRESS_KEY, "".to_string()).value;
        let remote_address: IpAddr = address.parse().unwrap_or(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
        
        address = settings.get(log_handler_name, MULTICAST_IF_KEY, "".to_string()).value;
        
        let multicast_if: IpAddr;
        if remote_address.is_ipv4() {
            multicast_if = address.parse().unwrap_or(IpAddr::V4(Ipv4Addr::UNSPECIFIED));
        } else {
            multicast_if = address.parse().unwrap_or(IpAddr::V6(Ipv6Addr::UNSPECIFIED));
        }
        let remote_port = settings.get(log_handler_name, REMOTE_PORT_KEY, 0u16).value;
        Box::new(
            NetworkLogHandler::new(log_handler_name.to_string(), 
            enabled,
            timestamp_format, 
            msg_types_enabled, 
            msg_types_text,
            message_format,
            pattern,
            appname.to_string(),
            appver.to_string(),
            protocol,
            remote_address,
            multicast_if,
            remote_port))
    }
}

// Network log handler object
struct NetworkLogHandler {
    base: LogHandlerBase,
    protocol: NetworkProtocol,
    remote_address: Option<SocketAddr>,
    multicast_if: IpAddr,
    socket: Option<Socket>,
    is_connected: bool, // TCP Only
    errors_list: Vec<ErrorKind>
}

// Network log handler object implementation
impl NetworkLogHandler {

    // Create a Network log handler object
    // * `name` log handler name
    // * `enabled` log handler enabling flag
    // * `timestamp_format` time stampt format
    // * `msg_types_enabled` log message type enabling flags
    // * `msg_types_text` log message type texts
    // * `message_format` log message output format (plain , json, json_pretty)
    // * `pattern` log message format pattern
    // * `appname` application name as passed to mdlogger::initialize funtion
    // * `appver` application version as passed to mdlogger::initialize funtion
    // * `protocol` network protocol type
    // * `remote_address` network remote ip (4 or 6) address
    // * `multicast_if` network interface in case rmote address is a multicast ip
    // * `remote_port` network remote port
    fn new(name: String,
        enabled: bool,
        timestamp_format: String,
        msg_types_enabled: [bool; LOG_MSG_TYPE_NUM],
        msg_types_text: [String; LOG_MSG_TYPE_NUM],
        message_format: String, 
        pattern: String,
        appname: String,
        appver: String,
        protocol: NetworkProtocol,
        remote_address: IpAddr,
        multicast_if: IpAddr,
        remote_port: u16
    ) -> Self {
        let mut result = Self {
            base: LogHandlerBase::new(name,
                                    enabled,
                                    timestamp_format,
                                    msg_types_enabled,
                                    msg_types_text,
                                    message_format,
                                    pattern, appname, appver),
            protocol,
            remote_address: None,
            multicast_if,
            socket: None,
            is_connected: false,
            errors_list: vec![]
        };

        let is_multicast: bool = remote_address.is_multicast();
        result.remote_address = Some(SocketAddr::new(remote_address, remote_port));
        
        if let Err(error) = Self::create(&mut result) {
            eprintln!("Cannot create socket: {}", error);
        } else {
            let socket = result.socket.unwrap();
            println!("Log handler '{}' socket created to send log to: {} port {}", 
                    result.base.get_name(), remote_address.to_string(), remote_port);
            if is_multicast && !result.multicast_if.is_unspecified() {
                let itf_index = network_index(&result.multicast_if);
                match &result.multicast_if {
                    IpAddr::V4(interface) => {
                        if let Err(socket_error) = socket.set_multicast_if_v4(interface) {
                            eprintln!("Log handler '{}' cannot set IPV4 multicast interface: {}",
                                result.base.get_name(), socket_error);
                        } else {
                            println!("Log handler '{}' set multicast interface: {}", 
                                result.base.get_name(), interface.to_string())
                        }
                    },
                    IpAddr::V6(interface) => {
                        if let Some(itf_idx) = itf_index {
                            if let Err(socket_error) = socket.set_multicast_if_v6(itf_idx) {
                                eprintln!("Log handler '{}' cannot set IPV6 multicast interface: {}",
                                    result.base.get_name(), socket_error);
                            } else {
                                println!("Log handler '{}' set multicast interface: {}", 
                                    result.base.get_name(), interface.to_string())
                            }
                        }
                    }
                }
            }
            result.socket = Some(socket);
        }

    
        result
    }

    // Create a network socket interface
    // * `handler` mutable network log handler reference
    fn create(handler: &mut NetworkLogHandler) -> io::Result<()> {
        if let None = handler.socket {
            if let Some(remote_address) = handler.remote_address {
                let mut domain = Domain::IPV4;
                let mut socket_type = Type::DGRAM;
                if handler.protocol.unwrap() == TCP_NETWORK_PROTOCOL {
                    socket_type = Type::STREAM;
                }
                if remote_address.ip().is_ipv6() {
                        domain = Domain::IPV6;
                }
                handler.socket = Some(Socket::new(domain, socket_type, None)?);
            }
        }
        Ok(())
    }
    
}

// LogHandler trait implementation for Network log handler
impl LogHandler for NetworkLogHandler {

    // Return log handler name
    fn get_name(&self) ->&String {
        self.base.get_name()
    }

    // Return if log handler is enabled
    fn is_enabled(&self) ->bool {
        self.base.is_enabled()
    }

    // Return if log handler is enabled to log a specific message type
    // * `self` itself reference
    // * `msg_type` log message type to check for
    fn is_msg_type_enabled(&self, msg_type: &LogMsgType) -> bool{
        self.base.is_msg_type_enabled(msg_type)
    }

    // Return log handler messag format pattern
    fn get_pattern(&self) ->&String {
        &self.base.get_pattern()
    }

    // Return a json Value representing log handler configuration
    fn get_config(&self) -> Value {
        let mut config = self.base.get_config();
        config.insert(String::from(PROTOCOL_KEY), json!(self.protocol.to_string()));
        let remote_addres: String;
        let mut remote_port: u16 = 0;
        let mut multicast_if: String = String::new();
        match &self.remote_address {
            Some(addr) => {
                remote_addres = addr.ip().to_string();
                remote_port = addr.port().clone();
                if addr.ip().is_multicast() {
                    multicast_if = self.multicast_if.to_string();
                }
            },
            None => {
                remote_addres = String::from("None");
            }
        } 
        config.insert(String::from(REMOTE_ADDRESS_KEY), json!(remote_addres));
        config.insert(String::from(REMOTE_PORT_KEY), json!(remote_port));
        config.insert(String::from(MULTICAST_IF_KEY), json!(multicast_if));
        Value::Object(config)
    }

    // Set log handler configuration value
    // * `self` itself mutable reference
    // * `key` log message configuration key
    // * `value` log message new configuration value
    fn set_config(&mut self, key: &str, value: &Value) -> Result<Option<String>, String> {
        if self.base.is_abaseconfig(key) {
            return self.base.set_config(key, value);
        } else if REMOTE_ADDRESS_KEY == key {
            if let Some(remote_address) = value.as_str() {
                if let Err(parse_error) = remote_address.parse::<IpAddr>() {
                        return Err(format!("{}", parse_error));
                }
                return Ok(Some(format!("Changing '{}' has meaning only if you save it for next run",
                                key)));
            } else {
                return Err(String::from("needs a string value"));
            }
        } else if REMOTE_PORT_KEY == key {
            if let Some(remote_port) = value.as_u64() {
                if  (remote_port > 0u64) && (remote_port <= u16::MAX as u64) {
                    return Ok(Some(format!("Changing '{}' has meaning only if you save it for next run",
                            key)));
                } else {
                    return Err(format!("'{}' out of range 0..{}", remote_port, u16::MAX));
                }
            } else {
                return Err(String::from("needs a positive integer value"));
            }
        } else if MULTICAST_IF_KEY == key {
            if self.protocol.unwrap() != MCAST_NETWORK_PROTOCOL {
                return Err(format!("{} is not multicast but is {}",
                            PROTOCOL_KEY, self.protocol.unwrap()));
            } 
            if let Some(multicast_if) = value.as_str() {
                match multicast_if.parse::<IpAddr>() {
                    Ok(ip) => {
                        if ip.is_multicast() {
                            return Err(format!("{} cannot be a multicast address", key));
                        } else {
                            if self.multicast_if.is_ipv4() && ip.is_ipv6() {
                                return Err(format!("{} has to be an IPV4 address", MULTICAST_IF_KEY));
                            }
                            if self.multicast_if.is_ipv6() && ip.is_ipv4() {
                                return Err(format!("{} has to be an IPV6 address", MULTICAST_IF_KEY));
                            }
                            return Ok(Some(format!("Changing '{}' has meaning only if you save it for next run", key)));
                        }
                    }, 
                    Err(parse_error) => {
                        return Err(format!("{}", parse_error));
                    }
                }
            } else {
                return Err(String::from("needs string value"));
            }
        } else {    
            return Err(format!("'{}' is not a valid parameter key", key));
        }
    }

    // Log handler log function
    // * `self` itself mutable reference
    // * `msg_type` log message type enumeration
    // * `log_message` log message object
    fn log(&mut self, msg_type: &LogMsgType, log_message: &LogMessage) {
        if self.is_enabled() && self.is_msg_type_enabled(msg_type) {
            let mut formatted_message = log_message.formatted_message(
                self.base.get_message_format(),
                self.base.get_pattern(),
                self.base.get_appname(),
                self.base.get_appver(),
                self.base.get_timestamp_format(),
                self.base.get_msg_types_text());


            if let Some(socket_addres) = self.remote_address {
                let protocol_type = self.protocol.unwrap();
                if (protocol_type == UDP_NETWORK_PROTOCOL) ||
                   (protocol_type == MCAST_NETWORK_PROTOCOL) {
                    if let Some(udp_socket) = &self.socket {
                        if let Err(ioerror) = udp_socket.send_to(formatted_message.as_bytes(), &socket_addres.into()) {
                            if !self.errors_list.contains(&ioerror.kind()) {
                                eprintln!("Log handler '{}' protocol '{}' io error: '{:#}'", 
                                        self.base.get_name(), self.protocol, ioerror);
                                self.errors_list.push(ioerror.kind());
                            }
                        }
                    }
                } else if protocol_type == TCP_NETWORK_PROTOCOL {
                    formatted_message.push(0x03 as char);
                    if let Some(socket) = &self.socket {
                        if !self.is_connected {
                            if let Err(ioerror) = socket.connect(&socket_addres.into()) {
                                if !self.errors_list.contains(&ioerror.kind()) {
                                    eprintln!("Log handler '{}' protocol '{}' io error: '{:#}'", 
                                            self.base.get_name(), self.protocol, ioerror);
                                    self.errors_list.push(ioerror.kind());
                                }
                            } else {
                                println!("Log handler '{}' protocol '{}' connected to: {:#?}", 
                                    self.base.get_name(), self.protocol, socket_addres);
                                self.is_connected = true;
                                self.errors_list.clear();
                            }
                        }

                        if self.is_connected {
                            if let Err(ioerror) = socket.send(&formatted_message.as_bytes()) {
                                if !self.errors_list.contains(&ioerror.kind()) {
                                    eprintln!("Log handler '{}' protocol '{}' io error: '{:#}'", 
                                            self.base.get_name(), self.protocol, ioerror);
                                    self.errors_list.push(ioerror.kind());
                                }
                                self.is_connected = false;
                                self.socket = None;
                                if let Err(ioerror) = Self::create(self) {
                                    if !self.errors_list.contains(&ioerror.kind()) {
                                        eprintln!("Log handler '{}' protocol '{}' io error: '{:#}'", 
                                                self.base.get_name(), self.protocol, ioerror);
                                        self.errors_list.push(ioerror.kind());
                                    }
                                } else {
                                    self.errors_list.clear();
                                }
                            }
                        }
                    }
                }
            }                
        }
    }
}

// Unix domain protocol enumeration
enum UnixDomainProtocol {
    UdpProtocol(String),
    TcpProtocol(String)
}

// Unix domain protocol enumeration implementation
impl UnixDomainProtocol {
    // Return Unix domain protocol value as text
    fn unwrap(&self) -> &String {
        match self {
            Self::UdpProtocol(value) => { value }
            Self::TcpProtocol(value) => { value }
        }
    }
}

// PartialEq trait implementation for Unix domain protocol enumeration
impl PartialEq for UnixDomainProtocol {
    fn eq(&self, other: &Self) -> bool {
        self.unwrap() == other.unwrap()
    }
}

// Unix domain protocol format error object
struct UnixDomainProtocolFormatError {
    message: String
}

// Display trait implementation for Unix domain protocol format error object
impl Display for UnixDomainProtocolFormatError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

// FromStr trait implementation for Unix domain protocol enumeration
impl FromStr for UnixDomainProtocol {
    type Err = UnixDomainProtocolFormatError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s_lowercase = s.to_lowercase();
        if UDP_NETWORK_PROTOCOL == s_lowercase {
            Ok(UnixDomainProtocol::UdpProtocol(UDP_NETWORK_PROTOCOL.to_string()))
        } else if TCP_NETWORK_PROTOCOL == s_lowercase {
            Ok(UnixDomainProtocol::TcpProtocol(TCP_NETWORK_PROTOCOL.to_string()))
        } else {
            Err(UnixDomainProtocolFormatError{message: format!("Invalid unix domain protocol '{}' valid are: {}",
                s, VALID_NETWORK_PROTOCOLS.join(", "))})
        }
    }
}

// Display trait implementation for Unix domain protocol enumeration
impl Display for UnixDomainProtocol {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.unwrap())
    }
}

// Unix domain log handler factory object
pub (crate) struct UnixDomainLogHandlerFactory {

}

// LogHandlerFactory trait implementation for Unix domain log handler factory object 
impl LogHandlerFactory for UnixDomainLogHandlerFactory {

    // Return log handler type name
    fn type_name(&self) -> &str {
        "unix-domain"
    }

    // Check Network log handler configuration parametrs 
    // * `self` itself reference
    // * `settings` reference to mdlogger settings file
    // * `log_handler_name` log handler name (SECTION name of settings file)
    fn check_parameters(&self, settings: &rssettings::Settings, log_handler_name: &str) -> Result<(), String> {
        check_log_handler_common_parameters(settings, self.type_name(), log_handler_name)?;

        let unixdomain_protocol = settings.get(log_handler_name,PROTOCOL_KEY, "".to_string());
        if unixdomain_protocol.error.len() > 0 {
            return Err(format!("Log handler: '{}' type: '{}' error: '{}'", 
                    log_handler_name, self.type_name(), unixdomain_protocol.error));
        }
        if let Err(parse_error) = unixdomain_protocol.value.parse::<UnixDomainProtocol>() {
            return Err(format!("Log handler: '{}' type: '{}' error: '{}'",
                    log_handler_name, self.type_name(), parse_error));
        }

        if cfg!(windows) && unixdomain_protocol.value == UDP_NETWORK_PROTOCOL {
            return Err(format!("Log handler: '{}' type: '{}' error: protocol '{}' is not valid on windows systems",
                    log_handler_name, self.type_name(), unixdomain_protocol.value));
        }

        let mut sun_path = settings.get(log_handler_name, SUN_PATH_KEY, String::from(""));
        if sun_path.error.len() > 0 {
            return Err(format!("Log handler: '{}' type: '{}' error: '{}'", 
                    log_handler_name, self.type_name(), unixdomain_protocol.error));
        }
        if sun_path.value.is_empty() {
            return Err(format!("Log handler: '{}' type: '{}' {}: is empty", 
                    log_handler_name, self.type_name(), SUN_PATH_KEY));
        }

        let mut env_var_name = "";
        let mut env_var_value = String::new();
        if let Some(start) = sun_path.value.find("${") {
            if let Some(end) = sun_path.value.find("}") {
                if start < end {
                    env_var_name = &sun_path.value[start + 2..end];
                    match std::env::var(env_var_name) {
                        Ok(value) => {
                            env_var_value = value;
                        },
                        Err(error) => {
                            return Err(format!("Log handler: '{}' type: '{}'  {} error: '{}' - {} ", 
                                log_handler_name, self.type_name(), SUN_PATH_KEY, env_var_name, error));    
                        }
                    }                    
                }
            }
        }
        
        if !env_var_name.is_empty() {
            sun_path.value = sun_path.value.replace(env_var_name, &env_var_value);
        }
        if let Err(error) = SockAddr::unix(&sun_path.value) {
            return Err(format!("Log handler: '{}' type: '{}'  {} error: '{}' - {}", 
                log_handler_name, self.type_name(), SUN_PATH_KEY, sun_path.value, error));    
        }


        Ok(())
    }

    // Create a Network log handler
    // * `self` itself reference
    // * `settings` reference to mdlogger settings file
    // * `log_handler_name` log handler name (SECTION name of settings file)
    // * `appname` application name as passed to mdlogger::initialize funtion
    // * `appver` application version as passed to mdlogger::initialize funtion
    fn create_log_handler(&self, settings: &rssettings::Settings, log_handler_name: &str, appname: &str, appver: &str) -> Box<dyn LogHandler> {
        let mut enabled = false;
        let mut pattern =  String::new();
        let mut timestamp_format = String::new();
        let mut msg_types_enabled: [bool; LOG_MSG_TYPE_NUM] = [false, false, false, false, false]; 
        let mut msg_types_text: [String; LOG_MSG_TYPE_NUM] = [
            String::new(), String::new(), String::new(),
            String::new(), String::new()
        ];
        let mut message_format = String::new();
        get_log_handler_common_parameters(
            &mut enabled, &mut pattern, &mut timestamp_format,
            &mut msg_types_enabled, &mut msg_types_text,
            &mut message_format, settings, log_handler_name,
        pretty_function!());

        
        let unixdomain_protocol = settings.get(log_handler_name,PROTOCOL_KEY, "".to_string()).value;
        let protocol: UnixDomainProtocol = unixdomain_protocol.parse().unwrap_or(UnixDomainProtocol::UdpProtocol(UDP_NETWORK_PROTOCOL.to_string()));

        let mut remote_address = settings.get(log_handler_name, SUN_PATH_KEY, String::from("")).value;
        if let Some(start) = remote_address.find("${") {
            if let Some(end) = remote_address.find("}") {
                if start < end {
                    let env_var_name = String::from(&remote_address[start + 2..end]);
                    let env_var_value = &std::env::var(&env_var_name).unwrap_or(String::new());
                    if !env_var_value.is_empty() {
                        remote_address = remote_address.replace("${", "")
                                    .replace("}", "")
                                    .replace(&env_var_name, env_var_value);
                    }
                }
            }
        }
        if cfg!(windows) {
            remote_address = remote_address.replace("/", "\\");
        } else {
            remote_address = remote_address.replace("\\", "/");
        }
        Box::new(UnixDomainLogHandler::new(log_handler_name.to_string(),
                                enabled,
                                timestamp_format, 
                                msg_types_enabled, 
                                msg_types_text,
                                message_format,
                                pattern,
                                appname.to_string(),
                                appver.to_string(),
                                protocol,
                                remote_address))
    }
}

// Unix domain log handler object
struct UnixDomainLogHandler {
    base: LogHandlerBase,
    protocol: UnixDomainProtocol,
    remote_address: String,
    socket: Option<Socket>,
    is_connected: bool, // TCP Only
    errors_list: Vec<ErrorKind>
}


// Unix domain log handler object implementation
impl UnixDomainLogHandler {

    // Create a Unix domain log handler object
    // * `name` log handler name
    // * `enabled` log handler enabling flag
    // * `timestamp_format` time stampt format
    // * `msg_types_enabled` log message type enabling flags
    // * `msg_types_text` log message type texts
    // * `message_format` log message output format (plain , json, json_pretty)
    // * `pattern` log message format pattern
    // * `appname` application name as passed to mdlogger::initialize funtion
    // * `appver` application version as passed to mdlogger::initialize funtion
    // * `protocol` network protocol type
    // * `remote_address` local socket remote address
    fn new(name: String,
        enabled: bool,
        timestamp_format: String,
        msg_types_enabled: [bool; LOG_MSG_TYPE_NUM],
        msg_types_text: [String; LOG_MSG_TYPE_NUM],
        message_format: String, 
        pattern: String,
        appname: String,
        appver: String,
        protocol: UnixDomainProtocol,
        remote_address: String) -> Self {
            let mut result = Self {
                base: LogHandlerBase::new(name,
                    enabled,
                    timestamp_format,
                    msg_types_enabled,
                    msg_types_text,
                    message_format,
                    pattern, appname, appver),
                protocol,
                remote_address,
                socket: None,
                is_connected: false,
                errors_list: vec![]             
            };
            if let Err(error) = Self::create(&mut result) {
                eprintln!("Log handler '{}' cannot create socket: {}", 
                    result.base.get_name(), error);
            } else {
                println!("Log handler '{}' socket created to send log to: {}", 
                        result.base.get_name(), result.remote_address);

            }
            result
    }

    // Create a unix domain socket interface
    // * `handler` mutable network log handler reference
    fn create(handler: &mut UnixDomainLogHandler) -> io::Result<()> {
        if let None = handler.socket {
            if !handler.remote_address.is_empty() {
                let mut socket_type = Type::DGRAM;
                if handler.protocol.unwrap() == TCP_NETWORK_PROTOCOL {
                    socket_type = Type::STREAM;
                }
                handler.socket = Some(Socket::new(Domain::UNIX, socket_type, None)?);
            }
        }
        println!("OK");
        Ok(())
    }
}

// LogHandler trait implementation for Unix domain log handler
impl LogHandler for UnixDomainLogHandler {

    // Return log handler name
    fn get_name(&self) ->&String {
        self.base.get_name()
    }

    // Return if log handler is enabled
    fn is_enabled(&self) ->bool {
        self.base.is_enabled()
    }

    // Return if log handler is enabled to log a specific message type
    // * `self` itself reference
    // * `msg_type` log message type to check for
    fn is_msg_type_enabled(&self, msg_type: &LogMsgType) -> bool{
        self.base.is_msg_type_enabled(msg_type)
    }

    // Return log handler messag format pattern
    fn get_pattern(&self) ->&String {
        &self.base.get_pattern()
    }

    // Return a json Value representing log handler configuration
    fn get_config(&self) -> Value {
        let mut config = self.base.get_config();
        config.insert(String::from(PROTOCOL_KEY), json!(self.protocol.to_string()));
        config.insert(String::from(REMOTE_ADDRESS_KEY), json!(self.remote_address));
        Value::Object(config)
    }

    // Set log handler configuration value
    // * `self` itself mutable reference
    // * `key` log message configuration key
    // * `value` log message new configuration value
    fn set_config(&mut self, key: &str, value: &Value) -> Result<Option<String>, String> {
        if self.base.is_abaseconfig(key) {
            return self.base.set_config(key, value);
        } else if SUN_PATH_KEY == key {
            if let Some(sun_path) = value.as_str() {
                if let Err(error) = SockAddr::unix(sun_path) {
                    return Err(format!("{}", error));    
                }
                return Ok(Some(format!("Changing '{}' has meaning only if you save it for next run",
                                key)));
            } else {
                return Err(String::from("needs a string value"));
            }
        } else {
            return Err(String::from("is not a valid parameter"));
        }
    }

    // Log handler log function
    // * `self` itself mutable reference
    // * `msg_type` log message type enumeration
    // * `log_message` log message object
    fn log(&mut self, msg_type: &LogMsgType, log_message: &LogMessage) {
        if self.is_enabled() && self.is_msg_type_enabled(msg_type) {
            let mut formatted_message = log_message.formatted_message(
                self.base.get_message_format(),
                self.base.get_pattern(),
                self.base.get_appname(),
                self.base.get_appver(),
                self.base.get_timestamp_format(),
                self.base.get_msg_types_text());
            let protocol_type = self.protocol.unwrap();
            if let Ok(remote_address) = SockAddr::unix(&self.remote_address) {
                if protocol_type == UDP_NETWORK_PROTOCOL {
                    if let Some(udp_socket) = &self.socket {
                        if let Err(ioerror) = udp_socket.send_to(formatted_message.as_bytes(), &remote_address) {
                            if !self.errors_list.contains(&ioerror.kind()) {
                                eprintln!("Log handler '{}' protocol '{}' io error: '{:#}'", 
                                        self.base.get_name(), self.protocol, ioerror);
                                self.errors_list.push(ioerror.kind());
                            }
                        }
                    }    
                } else if protocol_type == TCP_NETWORK_PROTOCOL {
                    formatted_message.push(0x03 as char);
                    if let Some(socket) = &self.socket {
                        if !self.is_connected {
                            if let Err(ioerror) = socket.connect(&remote_address) {
                                if !self.errors_list.contains(&ioerror.kind()) {
                                    eprintln!("Log handler '{}' protocol '{}' io error: '{:#}'", 
                                            self.base.get_name(), self.protocol, ioerror);
                                    self.errors_list.push(ioerror.kind());
                                }
                            } else {
                                println!("Log handler '{}' protocol '{}' connected to: {:#?}", 
                                    self.base.get_name(), self.protocol, self.remote_address);
                                self.is_connected = true;
                                self.errors_list.clear();
                            }
                        }

                        if self.is_connected {
                            if let Err(ioerror) = socket.send(&formatted_message.as_bytes()) {
                                if !self.errors_list.contains(&ioerror.kind()) {
                                    eprintln!("Log handler '{}' protocol '{}' io error: '{:#}'", 
                                            self.base.get_name(), self.protocol, ioerror);
                                    self.errors_list.push(ioerror.kind());
                                }
                                self.is_connected = false;
                                self.socket = None;
                                if let Err(ioerror) = Self::create(self) {
                                    if !self.errors_list.contains(&ioerror.kind()) {
                                        eprintln!("Log handler '{}' protocol '{}' io error: '{:#}'", 
                                                self.base.get_name(), self.protocol, ioerror);
                                        self.errors_list.push(ioerror.kind());
                                    }
                                } else {
                                    self.errors_list.clear();
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}