@@ -35,20 +35,40 @@ pub trait Log: Send {
3535 fn rotate ( & mut self ) -> std:: io:: Result < ( ) > ;
3636}
3737
38+ struct CountingWriter < ' a , W > {
39+ inner : & ' a mut W ,
40+ count : usize ,
41+ }
42+
43+ impl < ' a , W : Write > Write for CountingWriter < ' a , W > {
44+ fn write ( & mut self , buf : & [ u8 ] ) -> std:: io:: Result < usize > {
45+ let n = self . inner . write ( buf) ?;
46+ self . count += n;
47+ Ok ( n)
48+ }
49+
50+ fn flush ( & mut self ) -> std:: io:: Result < ( ) > {
51+ self . inner . flush ( )
52+ }
53+ }
54+
3855pub struct Logger {
3956 file : std:: fs:: File ,
4057 path : PathBuf ,
4158 rotation_threshold : u64 ,
59+ current_size : u64 ,
4260}
4361
4462impl Logger {
4563 pub fn new < P : AsRef < Path > > ( path : P , rotation_threshold : u64 ) -> std:: io:: Result < Self > {
4664 let path = path. as_ref ( ) . to_path_buf ( ) ;
4765 let file = OpenOptions :: new ( ) . create ( true ) . append ( true ) . open ( & path) ?;
66+ let current_size = file. metadata ( ) ?. len ( ) ;
4867 Ok ( Logger {
4968 file,
5069 path,
5170 rotation_threshold,
71+ current_size,
5272 } )
5373 }
5474}
@@ -68,12 +88,19 @@ impl Log for Logger {
6888 let span = span ! ( Level :: DEBUG , "log" , op_type, op_id) ;
6989 let _enter = span. enter ( ) ;
7090
71- if self . file . metadata ( ) ? . len ( ) > self . rotation_threshold {
91+ if self . current_size > self . rotation_threshold {
7292 self . rotate ( ) ?;
7393 }
7494 let entry = LogEntry { ts : Utc :: now ( ) , op } ;
75- let json = serde_json:: to_string ( & entry) ?;
76- writeln ! ( self . file, "{}" , json)
95+
96+ let mut writer = CountingWriter {
97+ inner : & mut self . file ,
98+ count : 0 ,
99+ } ;
100+ serde_json:: to_writer ( & mut writer, & entry) ?;
101+ writer. write_all ( b"\n " ) ?;
102+ self . current_size += writer. count as u64 ;
103+ Ok ( ( ) )
77104 }
78105
79106 fn rotate ( & mut self ) -> std:: io:: Result < ( ) > {
@@ -83,6 +110,7 @@ impl Log for Logger {
83110 . create ( true )
84111 . append ( true )
85112 . open ( & self . path ) ?;
113+ self . current_size = 0 ;
86114 Ok ( ( ) )
87115 }
88116}
0 commit comments