Python LMF library
 All Classes Namespaces Files Functions Variables
log.py
Go to the documentation of this file.
1 #! /usr/bin/env python
2 
3 """! @package utils
4 """
5 
6 from utils.io import open_file, EOL
7 from utils.error_handling import Error
8 
9 def log(msg, options=None):
10  """! @brief Write message into log file if any, or to standard output if verbose mode is on.
11  @param msg String to log.
12  @param options User options.
13  """
14  try:
15  import sys
16  ## If provided, set function variables according to user options
17  if options is not None:
18  # Keep log filename and verbose mode in function variables
19  setattr(log, "log_filename", options.log_filename)
20  setattr(log, "verbose", options.verbose)
21  # Initialize log file
22  if log.log_filename is not None:
23  log_file = open_file(log.log_filename, 'w+')
24  log_file.close()
25  ## Prepare message to log: add end of line to message
26  msg += EOL
27  ## Depending on options, log into file or standard output
28  if hasattr(log, "log_filename") and log.log_filename is not None:
29  # Open log file
30  log_file = open_file(log.log_filename, 'a')
31  # Write message into log file
32  log_file.write(msg)
33  # Close log file
34  log_file.close()
35  # If no log filename has been specified, check if verbose mode has been set by user
36  elif hasattr(log, "verbose") and log.verbose:
37  sys.stdout.write(msg)
38  except IOError as exception:
39  raise Error("Cannot write into log file '%s'." % options.log_filename, exception)
def open_file
Open file in specified mode (automatically decode file in unicode).
Definition: io.py:20
def log
Write message into log file if any, or to standard output if verbose mode is on.
Definition: log.py:9