<s> import HydrusConstants as HC <EOL> import HydrusData <EOL> import os <EOL> import sys <EOL> import time <EOL> class HydrusLogger ( object ) : <EOL> def __init__ ( self , log_filename ) : <EOL> self . _log_filename = log_filename <EOL> def __enter__ ( self ) : <EOL> self . _previous_sys_stdout = sys . stdout <EOL> self . _previous_sys_stderr = sys . stderr <EOL> self . _problem_with_previous_stdout = False <EOL> sys . stdout = self <EOL> sys . stderr = self <EOL> self . _log_file = open ( os . path . join ( HC . LOGS_DIR , self . _log_filename ) , '<STR_LIT:a>' ) <EOL> return self <EOL> def __exit__ ( self , exc_type , exc_val , exc_tb ) : <EOL> self . _log_file . close ( ) <EOL> sys . stdout = self . _previous_sys_stdout <EOL> sys . stderr = self . _previous_sys_stderr <EOL> return False <EOL> def flush ( self ) : <EOL> if not self . _problem_with_previous_stdout : <EOL> try : <EOL> self . _previous_sys_stdout . flush ( ) <EOL> except IOError : <EOL> self . _problem_with_previous_stdout = True <EOL> self . _log_file . flush ( ) <EOL> def write ( self , value ) : <EOL> if value in ( os . linesep , '<STR_LIT:\n>' ) : <EOL> prefix = '<STR_LIT>' <EOL> else : <EOL> prefix = time . strftime ( '<STR_LIT>' , time . localtime ( ) ) <EOL> message = HydrusData . ToByteString ( prefix + value ) <EOL> if not self . _problem_with_previous_stdout : <EOL> try : <EOL> self . _previous_sys_stdout . write ( message ) <EOL> except IOError : <EOL> self . _problem_with_previous_stdout = True <EOL> self . _log_file . write ( message ) </s>
