@@ -807,41 +807,49 @@ impl Log for Logger {
807807 static FORMATTER : RefCell <Option <Formatter >> = RefCell :: new( None ) ;
808808 }
809809
810- FORMATTER . with ( |tl_buf| {
811- // It's possible for implementations to sometimes
812- // log-while-logging (e.g. a `std::fmt` implementation logs
813- // internally) but it's super rare. If this happens make sure we
814- // at least don't panic and ship some output to the screen.
815- let mut a;
816- let mut b = None ;
817- let tl_buf = match tl_buf. try_borrow_mut ( ) {
818- Ok ( f) => {
819- a = f;
820- & mut * a
821- }
822- Err ( _) => & mut b,
823- } ;
824-
825- // Check the buffer style. If it's different from the logger's
826- // style then drop the buffer and recreate it.
827- match * tl_buf {
828- Some ( ref mut formatter) => {
829- if formatter. write_style ( ) != self . writer . write_style ( ) {
830- * formatter = Formatter :: new ( & self . writer )
831- }
832- }
833- ref mut tl_buf => * tl_buf = Some ( Formatter :: new ( & self . writer ) ) ,
834- }
835-
836- // The format is guaranteed to be `Some` by this point
837- let mut formatter = tl_buf. as_mut ( ) . unwrap ( ) ;
838-
839- let _ = ( self . format ) ( & mut formatter, record)
810+ let print = |formatter : & mut Formatter , record : & Record | {
811+ let _ = ( self . format ) ( formatter, record)
840812 . and_then ( |_| formatter. print ( & self . writer ) ) ;
841813
842814 // Always clear the buffer afterwards
843815 formatter. clear ( ) ;
844- } ) ;
816+ } ;
817+
818+ let printed = FORMATTER . try_with ( |tl_buf| {
819+ match tl_buf. try_borrow_mut ( ) {
820+ // There are no active borrows of the buffer
821+ Ok ( mut tl_buf) => match * tl_buf {
822+ // We have a previously set formatter
823+ Some ( ref mut formatter) => {
824+ // Check the buffer style. If it's different from the logger's
825+ // style then drop the buffer and recreate it.
826+ if formatter. write_style ( ) != self . writer . write_style ( ) {
827+ * formatter = Formatter :: new ( & self . writer ) ;
828+ }
829+
830+ print ( formatter, record) ;
831+ }
832+ // We don't have a previously set formatter
833+ None => {
834+ let mut formatter = Formatter :: new ( & self . writer ) ;
835+ print ( & mut formatter, record) ;
836+
837+ * tl_buf = Some ( formatter) ;
838+ }
839+ }
840+ // There's already an active borrow of the buffer (due to re-entrancy)
841+ Err ( _) => {
842+ print ( & mut Formatter :: new ( & self . writer ) , record) ;
843+ }
844+ }
845+ } ) . is_ok ( ) ;
846+
847+ if !printed {
848+ // The thread-local storage was not available (because its
849+ // destructor has already run). Create a new single-use
850+ // Formatter on the stack for this call.
851+ print ( & mut Formatter :: new ( & self . writer ) , record) ;
852+ }
845853 }
846854 }
847855
0 commit comments