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
use crate::build::BuilderCommon;
use crate::misc;
#[cfg(feature = "slog-kvfilter")]
use crate::types::KVFilterParameters;
use crate::types::{Format, OverflowStrategy, Severity, SourceLocation, TimeZone};
use crate::{Build, Config, ErrorKind, Result};
use chrono::{DateTime, Local, TimeZone as ChronoTimeZone, Utc};
#[cfg(feature = "libflate")]
use libflate::gzip::Encoder as GzipEncoder;
use serde::{Deserialize, Serialize};
use slog::Logger;
use slog_term::{CompactFormat, FullFormat, PlainDecorator};
use std::fmt::Debug;
use std::fs::{self, File, OpenOptions};
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};
#[cfg(feature = "libflate")]
use std::sync::mpsc;
#[cfg(feature = "libflate")]
use std::thread;
use std::time::{Duration, Instant};
#[derive(Debug)]
pub struct FileLoggerBuilder {
    common: BuilderCommon,
    format: Format,
    timezone: TimeZone,
    appender: FileAppender,
}
impl FileLoggerBuilder {
    
    
    
    
    pub fn new<P: AsRef<Path>>(path: P) -> Self {
        FileLoggerBuilder {
            common: BuilderCommon::default(),
            format: Format::default(),
            timezone: TimeZone::default(),
            appender: FileAppender::new(path),
        }
    }
    
    pub fn format(&mut self, format: Format) -> &mut Self {
        self.format = format;
        self
    }
    
    pub fn source_location(&mut self, source_location: SourceLocation) -> &mut Self {
        self.common.source_location = source_location;
        self
    }
    
    pub fn overflow_strategy(&mut self, overflow_strategy: OverflowStrategy) -> &mut Self {
        self.common.overflow_strategy = overflow_strategy;
        self
    }
    
    pub fn timezone(&mut self, timezone: TimeZone) -> &mut Self {
        self.timezone = timezone;
        self
    }
    
    pub fn level(&mut self, severity: Severity) -> &mut Self {
        self.common.level = severity;
        self
    }
    
    pub fn channel_size(&mut self, channel_size: usize) -> &mut Self {
        self.common.channel_size = channel_size;
        self
    }
    
    
    
    #[cfg(feature = "slog-kvfilter")]
    pub fn kvfilter(&mut self, parameters: KVFilterParameters) -> &mut Self {
        self.common.kvfilterparameters = Some(parameters);
        self
    }
    
    
    pub fn truncate(&mut self) -> &mut Self {
        self.appender.truncate = true;
        self
    }
    
    
    
    
    
    
    
    
    
    
    
    
    pub fn rotate_size(&mut self, size: u64) -> &mut Self {
        self.appender.rotate_size = size;
        self
    }
    
    
    
    
    
    pub fn rotate_keep(&mut self, count: usize) -> &mut Self {
        self.appender.rotate_keep = count;
        self
    }
    
    
    
    
    
    
    #[cfg(feature = "libflate")]
    pub fn rotate_compress(&mut self, compress: bool) -> &mut Self {
        self.appender.rotate_compress = compress;
        self
    }
}
impl Build for FileLoggerBuilder {
    fn build(&self) -> Result<Logger> {
        let timestamp = misc::timezone_to_timestamp_fn(self.timezone);
        let logger = match self.format {
            Format::Full => {
                let decorator = PlainDecorator::new(self.appender.clone());
                let format = FullFormat::new(decorator).use_custom_timestamp(timestamp);
                self.common.build_with_drain(format.build())
            }
            Format::Compact => {
                let decorator = PlainDecorator::new(self.appender.clone());
                let format = CompactFormat::new(decorator).use_custom_timestamp(timestamp);
                self.common.build_with_drain(format.build())
            }
            #[cfg(feature = "json")]
            Format::Json => {
                let drain = slog_json::Json::new(self.appender.clone())
                    .set_flush(true)
                    .add_default_keys()
                    .build();
                self.common.build_with_drain(drain)
            }
        };
        Ok(logger)
    }
}
#[derive(Debug)]
struct FileAppender {
    path: PathBuf,
    file: Option<BufWriter<File>>,
    truncate: bool,
    written_size: u64,
    rotate_size: u64,
    rotate_keep: usize,
    #[cfg(feature = "libflate")]
    rotate_compress: bool,
    #[cfg(feature = "libflate")]
    wait_compression: Option<mpsc::Receiver<io::Result<()>>>,
    next_reopen_check: Instant,
    reopen_check_interval: Duration,
}
impl Clone for FileAppender {
    fn clone(&self) -> Self {
        FileAppender {
            path: self.path.clone(),
            file: None,
            truncate: self.truncate,
            written_size: 0,
            rotate_size: self.rotate_size,
            rotate_keep: self.rotate_keep,
            #[cfg(feature = "libflate")]
            rotate_compress: self.rotate_compress,
            #[cfg(feature = "libflate")]
            wait_compression: None,
            next_reopen_check: Instant::now(),
            reopen_check_interval: self.reopen_check_interval,
        }
    }
}
impl FileAppender {
    pub fn new<P: AsRef<Path>>(path: P) -> Self {
        FileAppender {
            path: path.as_ref().to_path_buf(),
            file: None,
            truncate: false,
            written_size: 0,
            rotate_size: default_rotate_size(),
            rotate_keep: default_rotate_keep(),
            #[cfg(feature = "libflate")]
            rotate_compress: false,
            #[cfg(feature = "libflate")]
            wait_compression: None,
            next_reopen_check: Instant::now(),
            reopen_check_interval: Duration::from_millis(1000),
        }
    }
    fn reopen_if_needed(&mut self) -> io::Result<()> {
        
        
        
        
        
        let now = Instant::now();
        let path_exists = if now >= self.next_reopen_check {
            self.next_reopen_check = now + self.reopen_check_interval;
            self.path.exists()
        } else {
            
            true
        };
        if self.file.is_none() || !path_exists {
            let mut file_builder = OpenOptions::new();
            file_builder.create(true);
            if self.truncate {
                file_builder.truncate(true);
            }
            
            
            self.file = None;
            let file = file_builder
                .append(!self.truncate)
                .write(true)
                .open(&self.path)?;
            self.written_size = file.metadata()?.len();
            self.file = Some(BufWriter::new(file));
        }
        Ok(())
    }
    fn rotate(&mut self) -> io::Result<()> {
        #[cfg(feature = "libflate")]
        {
            if let Some(ref mut rx) = self.wait_compression {
                use std::sync::mpsc::TryRecvError;
                match rx.try_recv() {
                    Err(TryRecvError::Empty) => {
                        
                        return Ok(());
                    }
                    Err(TryRecvError::Disconnected) => {
                        let e = io::Error::new(
                            io::ErrorKind::Other,
                            "Log file compression thread aborted",
                        );
                        return Err(e);
                    }
                    Ok(result) => {
                        result?;
                    }
                }
            }
            self.wait_compression = None;
        }
        let _ = self.file.take();
        #[cfg(windows)]
        {
            if let Err(err) = self.rotate_old_files() {
                const ERROR_SHARING_VIOLATION: i32 = 32;
                
                
                if err.raw_os_error() != Some(ERROR_SHARING_VIOLATION) {
                    return Err(err);
                }
            }
        }
        #[cfg(not(windows))]
        self.rotate_old_files()?;
        self.written_size = 0;
        self.next_reopen_check = Instant::now();
        self.reopen_if_needed()?;
        Ok(())
    }
    fn rotate_old_files(&mut self) -> io::Result<()> {
        for i in (1..=self.rotate_keep).rev() {
            let from = self.rotated_path(i)?;
            let to = self.rotated_path(i + 1)?;
            if from.exists() {
                fs::rename(from, to)?;
            }
        }
        if self.path.exists() {
            let rotated_path = self.rotated_path(1)?;
            #[cfg(feature = "libflate")]
            {
                if self.rotate_compress {
                    let (plain_path, temp_gz_path) = self.rotated_paths_for_compression()?;
                    let (tx, rx) = mpsc::channel();
                    fs::rename(&self.path, &plain_path)?;
                    thread::spawn(move || {
                        let result = Self::compress(plain_path, temp_gz_path, rotated_path);
                        let _ = tx.send(result);
                    });
                    self.wait_compression = Some(rx);
                } else {
                    fs::rename(&self.path, rotated_path)?;
                }
            }
            #[cfg(not(feature = "libflate"))]
            fs::rename(&self.path, rotated_path)?;
        }
        let delete_path = self.rotated_path(self.rotate_keep + 1)?;
        if delete_path.exists() {
            fs::remove_file(delete_path)?;
        }
        Ok(())
    }
    fn rotated_path(&self, i: usize) -> io::Result<PathBuf> {
        let path = self.path.to_str().ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("Non UTF-8 log file path: {:?}", self.path),
            )
        })?;
        #[cfg(feature = "libflate")]
        {
            if self.rotate_compress {
                Ok(PathBuf::from(format!("{}.{}.gz", path, i)))
            } else {
                Ok(PathBuf::from(format!("{}.{}", path, i)))
            }
        }
        #[cfg(not(feature = "libflate"))]
        Ok(PathBuf::from(format!("{}.{}", path, i)))
    }
    #[cfg(feature = "libflate")]
    fn rotated_paths_for_compression(&self) -> io::Result<(PathBuf, PathBuf)> {
        let path = self.path.to_str().ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("Non UTF-8 log file path: {:?}", self.path),
            )
        })?;
        Ok((
            PathBuf::from(format!("{}.1", path)),
            PathBuf::from(format!("{}.1.gz.temp", path)),
        ))
    }
    #[cfg(feature = "libflate")]
    fn compress(input_path: PathBuf, temp_path: PathBuf, output_path: PathBuf) -> io::Result<()> {
        let mut input = File::open(&input_path)?;
        let mut temp = GzipEncoder::new(File::create(&temp_path)?)?;
        io::copy(&mut input, &mut temp)?;
        temp.finish().into_result()?;
        fs::rename(temp_path, output_path)?;
        fs::remove_file(input_path)?;
        Ok(())
    }
}
impl Write for FileAppender {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.reopen_if_needed()?;
        let size = if let Some(ref mut f) = self.file {
            f.write(buf)?
        } else {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                format!("Cannot open file: {:?}", self.path),
            ));
        };
        self.written_size += size as u64;
        Ok(size)
    }
    fn flush(&mut self) -> io::Result<()> {
        if let Some(ref mut f) = self.file {
            f.flush()?;
        }
        if self.written_size >= self.rotate_size {
            self.rotate()?;
        }
        Ok(())
    }
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct FileLoggerConfig {
    
    #[serde(default)]
    pub level: Severity,
    
    #[serde(default)]
    pub format: Format,
    
    #[serde(default)]
    pub source_location: SourceLocation,
    
    #[serde(default)]
    pub timezone: TimeZone,
    
    
    
    
    #[serde(default = "default_timestamp_template")]
    pub timestamp_template: String,
    
    
    
    
    
    
    pub path: PathBuf,
    
    #[serde(default = "default_channel_size")]
    pub channel_size: usize,
    
    #[serde(default)]
    pub truncate: bool,
    
    
    
    
    
    #[serde(default = "default_rotate_size")]
    pub rotate_size: u64,
    
    
    
    
    
    #[serde(default = "default_rotate_keep")]
    pub rotate_keep: usize,
    
    
    
    
    
    
    
    #[serde(default)]
    #[cfg(feature = "libflate")]
    pub rotate_compress: bool,
    
    
    
    
    
    #[serde(default)]
    pub overflow_strategy: OverflowStrategy,
}
impl FileLoggerConfig {
    
    pub fn new() -> Self {
        Default::default()
    }
}
impl Config for FileLoggerConfig {
    type Builder = FileLoggerBuilder;
    fn try_to_builder(&self) -> Result<Self::Builder> {
        let now = Utc::now();
        let path_template = self.path.to_str().ok_or(ErrorKind::Invalid)?;
        let path =
            path_template_to_path(path_template, &self.timestamp_template, self.timezone, now);
        let mut builder = FileLoggerBuilder::new(&path);
        builder.level(self.level);
        builder.format(self.format);
        builder.source_location(self.source_location);
        builder.timezone(self.timezone);
        builder.overflow_strategy(self.overflow_strategy);
        builder.channel_size(self.channel_size);
        builder.rotate_size(self.rotate_size);
        builder.rotate_keep(self.rotate_keep);
        #[cfg(feature = "libflate")]
        builder.rotate_compress(self.rotate_compress);
        if self.truncate {
            builder.truncate();
        }
        Ok(builder)
    }
}
impl Default for FileLoggerConfig {
    fn default() -> Self {
        FileLoggerConfig {
            level: Severity::default(),
            format: Format::default(),
            source_location: SourceLocation::default(),
            overflow_strategy: OverflowStrategy::default(),
            timezone: TimeZone::default(),
            path: PathBuf::default(),
            timestamp_template: default_timestamp_template(),
            channel_size: default_channel_size(),
            truncate: false,
            rotate_size: default_rotate_size(),
            rotate_keep: default_rotate_keep(),
            #[cfg(feature = "libflate")]
            rotate_compress: false,
        }
    }
}
fn path_template_to_path(
    path_template: &str,
    timestamp_template: &str,
    timezone: TimeZone,
    date_time: DateTime<Utc>,
) -> PathBuf {
    let timestamp_string = match timezone {
        TimeZone::Local => {
            let local_timestamp = Local.from_utc_datetime(&date_time.naive_utc());
            local_timestamp.format(timestamp_template)
        }
        TimeZone::Utc => date_time.format(timestamp_template),
    }
    .to_string();
    let path_string = path_template.replace("{timestamp}", ×tamp_string);
    PathBuf::from(path_string)
}
fn default_channel_size() -> usize {
    1024
}
fn default_rotate_size() -> u64 {
    use std::u64;
    u64::MAX
}
fn default_rotate_keep() -> usize {
    8
}
fn default_timestamp_template() -> String {
    "%Y%m%d_%H%M".to_owned()
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Build, ErrorKind};
    use chrono::NaiveDateTime;
    use std::fs;
    use std::thread;
    use std::time::Duration;
    use tempfile::{Builder as TempDirBuilder, TempDir};
    #[test]
    fn test_reopen_if_needed() {
        let dir = tempdir();
        let log_path = &dir.path().join("foo.log");
        let logger = FileLoggerBuilder::new(log_path).build().unwrap();
        info!(logger, "Goodbye");
        thread::sleep(Duration::from_millis(50));
        assert!(log_path.exists());
        fs::remove_file(log_path).unwrap();
        assert!(!log_path.exists());
        thread::sleep(Duration::from_millis(100));
        info!(logger, "cruel");
        assert!(!log_path.exists()); 
        
        thread::sleep(Duration::from_millis(1000));
        info!(logger, "world");
        thread::sleep(Duration::from_millis(50));
        assert!(log_path.exists());
        assert!(fs::read_to_string(log_path).unwrap().contains("INFO world"));
    }
    #[test]
    fn file_rotation_works() {
        let dir = tempdir();
        let logger = FileLoggerBuilder::new(dir.path().join("foo.log"))
            .rotate_size(128)
            .rotate_keep(2)
            .build()
            .unwrap();
        info!(logger, "hello");
        thread::sleep(Duration::from_millis(50));
        assert!(dir.path().join("foo.log").exists());
        assert!(!dir.path().join("foo.log.1").exists());
        info!(logger, "world");
        thread::sleep(Duration::from_millis(50));
        assert!(dir.path().join("foo.log").exists());
        assert!(dir.path().join("foo.log.1").exists());
        assert!(!dir.path().join("foo.log.2").exists());
        info!(logger, "vec(0): {:?}", vec![0; 128]);
        thread::sleep(Duration::from_millis(50));
        assert!(dir.path().join("foo.log").exists());
        assert!(dir.path().join("foo.log.1").exists());
        assert!(dir.path().join("foo.log.2").exists());
        assert!(!dir.path().join("foo.log.3").exists());
        info!(logger, "vec(1): {:?}", vec![0; 128]);
        thread::sleep(Duration::from_millis(50));
        assert!(dir.path().join("foo.log").exists());
        assert!(dir.path().join("foo.log.1").exists());
        assert!(dir.path().join("foo.log.2").exists());
        assert!(!dir.path().join("foo.log.3").exists());
    }
    #[test]
    fn file_gzip_rotation_works() {
        let dir = tempdir();
        let logger = FileLoggerBuilder::new(dir.path().join("foo.log"))
            .rotate_size(128)
            .rotate_keep(2)
            .rotate_compress(true)
            .build()
            .unwrap();
        info!(logger, "hello");
        thread::sleep(Duration::from_millis(50));
        assert!(dir.path().join("foo.log").exists());
        assert!(!dir.path().join("foo.log.1").exists());
        info!(logger, "world");
        thread::sleep(Duration::from_millis(50));
        assert!(dir.path().join("foo.log").exists());
        assert!(dir.path().join("foo.log.1.gz").exists());
        assert!(!dir.path().join("foo.log.2.gz").exists());
        info!(logger, "vec(0): {:?}", vec![0; 128]);
        thread::sleep(Duration::from_millis(50));
        assert!(dir.path().join("foo.log").exists());
        assert!(dir.path().join("foo.log.1.gz").exists());
        assert!(dir.path().join("foo.log.2.gz").exists());
        assert!(!dir.path().join("foo.log.3.gz").exists());
        info!(logger, "vec(1): {:?}", vec![0; 128]);
        thread::sleep(Duration::from_millis(50));
        assert!(dir.path().join("foo.log").exists());
        assert!(dir.path().join("foo.log.1.gz").exists());
        assert!(dir.path().join("foo.log.2.gz").exists());
        assert!(!dir.path().join("foo.log.3.gz").exists());
    }
    #[test]
    fn test_path_template_to_path() {
        let dir = tempdir();
        let path_template = dir
            .path()
            .join("foo_{timestamp}.log")
            .to_str()
            .ok_or(ErrorKind::Invalid)
            .unwrap()
            .to_string();
        let actual = path_template_to_path(
            &path_template,
            "%Y%m%d_%H%M",
            TimeZone::Utc, 
            Utc.from_utc_datetime(&NaiveDateTime::from_timestamp(1537265991, 0)),
        );
        let expected = dir.path().join("foo_20180918_1019.log");
        assert_eq!(expected, actual);
    }
    fn tempdir() -> TempDir {
        TempDirBuilder::new()
            .prefix("sloggers_test")
            .tempdir()
            .expect("Cannot create a temporary directory")
    }
}