@@ -113,6 +113,7 @@ pub struct LogStorage {
113
113
min_level : LevelFilter ,
114
114
max_size : Option < usize > ,
115
115
max_lines : Option < usize > ,
116
+ max_line_length : Option < usize > ,
116
117
}
117
118
118
119
impl LogStorage {
@@ -127,6 +128,7 @@ impl LogStorage {
127
128
min_level,
128
129
max_size : None ,
129
130
max_lines : None ,
131
+ max_line_length : None ,
130
132
}
131
133
}
132
134
@@ -135,6 +137,11 @@ impl LogStorage {
135
137
self . max_size = Some ( size) ;
136
138
}
137
139
140
+ /// Set the maximum amount of bytes per line before truncating the line.
141
+ pub fn set_max_line_length ( & mut self , length : usize ) {
142
+ self . max_line_length = Some ( length) ;
143
+ }
144
+
138
145
/// Set the maximum amount of lines stored in this struct before truncating the output.
139
146
pub fn set_max_lines ( & mut self , lines : usize ) {
140
147
self . max_lines = Some ( lines) ;
@@ -149,6 +156,7 @@ impl LogStorage {
149
156
min_level : self . min_level ,
150
157
max_size : self . max_size ,
151
158
max_lines : self . max_lines ,
159
+ max_line_length : self . max_line_length ,
152
160
}
153
161
}
154
162
}
@@ -176,7 +184,18 @@ impl SealedLog for LogStorage {
176
184
return ;
177
185
}
178
186
}
179
- let message = record. args ( ) . to_string ( ) ;
187
+ let mut message = record. args ( ) . to_string ( ) ;
188
+
189
+ if let Some ( max_line_length) = self . max_line_length {
190
+ if message. len ( ) > max_line_length {
191
+ let mut length = max_line_length - 3 ;
192
+ while !message. is_char_boundary ( length) {
193
+ length -= 1 ;
194
+ }
195
+ message = format ! ( "{}..." , & message[ ..length] ) ;
196
+ }
197
+ }
198
+
180
199
if let Some ( max_size) = self . max_size {
181
200
if inner. size + message. len ( ) >= max_size {
182
201
inner. records . push ( StoredRecord {
@@ -352,4 +371,28 @@ mod tests {
352
371
. message
353
372
. contains( "too many lines" ) ) ;
354
373
}
374
+
375
+ #[ test]
376
+ fn test_too_long_line ( ) {
377
+ logging:: init ( ) ;
378
+
379
+ let mut storage = LogStorage :: new ( LevelFilter :: Info ) ;
380
+ storage. set_max_line_length ( 5 ) ;
381
+ logging:: capture ( & storage, || {
382
+ info ! ( "short" ) ;
383
+ info ! ( "this is too long" ) ;
384
+ info ! ( "a🧗" ) ; // 4 bytes
385
+ info ! ( "ab🧗" ) ; // 6 bytes
386
+ info ! ( "end" ) ;
387
+ } ) ;
388
+
389
+ let inner = storage. inner . lock ( ) . unwrap ( ) ;
390
+ assert ! ( !inner. truncated) ;
391
+ assert_eq ! ( inner. records. len( ) , 5 ) ;
392
+ assert_eq ! ( inner. records[ 0 ] . message, "short" ) ;
393
+ assert_eq ! ( inner. records[ 1 ] . message, "th..." ) ;
394
+ assert_eq ! ( inner. records[ 2 ] . message, "a🧗" ) ;
395
+ assert_eq ! ( inner. records[ 3 ] . message, "ab..." ) ;
396
+ assert_eq ! ( inner. records[ 4 ] . message, "end" ) ;
397
+ }
355
398
}
0 commit comments