Best Python code snippet using refurb_python
logging_management.py
Source:logging_management.py  
1#! /usr/bin/env python2# -*- mode: python; c-basic-offset: 2; indent-tabs-mode: nil; -*-3# vim:expandtab:shiftwidth=2:tabstop=2:smarttab:4#5# Copyright (C) 2009 Sun Microsystems6# Copyright (C) 2011 Patrick Crews7#8# Authors:9#10#  Jay Pipes <joinfu@sun.com>11#  Monty Taylor <mordred@sun.com>12#  Patrick Crews 13#14# This program is free software; you can redistribute it and/or modify15# it under the terms of the GNU General Public License as published by16# the Free Software Foundation; either version 2 of the License, or17# (at your option) any later version.18#19# This program is distributed in the hope that it will be useful,20# but WITHOUT ANY WARRANTY; without even the implied warranty of21# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the22# GNU General Public License for more details.23#24# You should have received a copy of the GNU General Public License25# along with this program; if not, write to the Free Software26# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA27#28#29# This code is modified from the logging module used in the 30# drizzle-automation project - https://launchpad.net/drizzle-automation31""" Simple replacement for python logging module that doesn't suck """32import os33import time, sys34class loggingManager():35    """ Class to deal with logging36        We make a class just because we forsee ourselves being37        multi-threaded and it will be nice to have a single38        point of control for managing i/o.39        Also, this is the cleanest way I can think of to deal40        with test-reporting (again, multi-threaded and such41    """42    def __init__(self, variables):43        self.log_file = sys.stdout44        self.subunit_file = variables['subunitoutfile']45        # TODO - introduce an option to manually toggle46        # whether or not to reset or append to pre-existing file47        if os.path.exists(self.subunit_file):48            os.remove(self.subunit_file)49        self.report_fmt = '{0:<42} {1} {2:>8}'50        self.report_started = 051        self.thick_line = '='*(80 - len("20110420-105402  "))52        self.thin_line = '-'*(80- len("20110420-105402  "))53        self.verbose_flag = variables['verbose']54        self.debug_flag = variables['debug']55        self.test_debug_flag = variables['testdebug']56    def _write_message(self,level, msg):57      self.log_file.write("%s %s %s\n" % (time.strftime("%Y%m%d-%H%M%S"), level, str(msg)))58      self.log_file.flush()59    def setOutput(self,file_name):60      if file_name == 'stdout':61        self.log_file= sys.stdout62      else:63        self.log_file= open(variables['log_file'],'w+')64    def info(self,msg):65      self._write_message("INFO", msg)66    def warning(self,msg):67      self._write_message("WARNING", msg)68    def error(self,msg):69      self._write_message("ERROR", msg)70    def verbose(self,msg):71      if self.verbose_flag:72          self._write_message("VERBOSE", msg)73    def debug(self,msg):74      if self.debug_flag:75          self._write_message("DEBUG", msg)76    def test_debug(self,msg):77        if self.test_debug_flag:78            self._write_message("TEST_DEBUG", msg)79 80    def debug_class(self,codeClass):81      if self.debug_flag:82        self._write_message("DEBUG**",codeClass)83        skip_keys = ['skip_keys', 'debug', 'verbose']84        for key, item in sorted(vars(codeClass).items()):85            if key not in codeClass.skip_keys and key not in skip_keys:86                self._write_message("DEBUG**",("%s: %s" %(key, item)))87    def test_report( self, test_name, test_status88                   , execution_time, additional_output = None89                   , report_output = False):90        """ We use this method to deal with writing out the test report91        """92        if not self.report_started:93            self.report_started = 194            self.write_report_header()95        test_status = "[ %s ]" %(test_status)96        msg = self.report_fmt.format( test_name, test_status97                                    , execution_time)98        self._write_message("", msg)99        if additional_output and report_output:100            additional_output=additional_output.split('\n')101            for line in additional_output:102                line = line.strip()103                self._write_message("",line)104    def write_report_header(self):105        self.write_thick_line()106        self.test_report("TEST NAME", "RESULT", "TIME (ms)")107        self.write_thick_line()108    def write_thin_line(self):109        self._write_message("",self.thin_line)110    def write_thick_line(self):111        self._write_message("",self.thick_line)112    def subunit_start(self,test_name):113        """ We log a test being started for subunit output """114        with open(self.subunit_file,'a') as subunit_outfile:115            subunit_outfile.write("time: %sZ\n" %(time.strftime("%Y-%m-%d-%H:%M:%S")))116            subunit_outfile.write("test: %s\n" %(test_name))117    def subunit_stop(self, test_name, retcode, output):118        """ We log the return of a test appropriately:119            success, skip, failure, etc120        """121        result_map = {'pass':'success'122                     ,'fail':'failure'123                     }124        result = result_map[retcode]125        with open(self.subunit_file,'a') as subunit_outfile:126            subunit_outfile.write(time.strftime("time: %Y-%m-%d-%H:%M:%SZ\n"))127            if output:128                output_string = " [\n%s]\n" %(output)129            else:130                output_string = "\n" # we just want a newline if nothing here 131            subunit_outfile.write("%s: %s%s" %( result132                                              , test_name133                                              , output_string))134            ...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
