How to use _log_file method in autotest

Best Python code snippet using autotest_python

log.py

Source:log.py Github

copy

Full Screen

1# Copyright 2011 The Chromium Authors. All rights reserved.2# Use of this source code is governed by a BSD-style license that can be3# found in the LICENSE file.4import atexit5import fcntl6import json7import os8import sys9import time10import threading11_lock = threading.Lock()12_enabled = False13_log_file = None14_cur_events = [] # events that have yet to be buffered15_tls = threading.local() # tls used to detect forking/etc16_atexit_regsitered_for_pid = None17_control_allowed = True18class TraceException(Exception):19 pass20def _note(msg, *args):21 pass22# print "%i: %s" % (os.getpid(), msg)23def _locked(fn):24 def locked_fn(*args,**kwargs):25 _lock.acquire()26 try:27 ret = fn(*args,**kwargs)28 finally:29 _lock.release()30 return ret31 return locked_fn32def _disallow_tracing_control():33 global _control_allowed34 _control_allowed = False35def trace_enable(log_file=None):36 _trace_enable(log_file)37 38@_locked39def _trace_enable(log_file=None):40 global _enabled41 if _enabled:42 raise TraceException("Already enabled")43 if not _control_allowed:44 raise TraceException("Tracing control not allowed in child processes.")45 _enabled = True46 global _log_file47 if log_file == None:48 if sys.argv[0] == '':49 n = 'trace_event'50 else:51 n = sys.argv[0]52 log_file = open("%s.json" % n, "ab", False)53 _note("trace_event: tracelog name is %s.json" % n)54 elif isinstance(log_file, basestring):55 _note("trace_event: tracelog name is %s" % log_file)56 log_file = open("%s" % log_file, "ab", False)57 elif not hasattr(log_file, 'fileno'):58 raise TraceException("Log file must be None, a string, or a file-like object with a fileno()")59 _log_file = log_file60 fcntl.lockf(_log_file.fileno(), fcntl.LOCK_EX)61 _log_file.seek(0, os.SEEK_END)62 lastpos = _log_file.tell()63 creator = lastpos == 064 if creator:65 _note("trace_event: Opened new tracelog, lastpos=%i", lastpos)66 _log_file.write('[')67 tid = threading.current_thread().ident68 if not tid:69 tid = os.getpid()70 x = {"ph": "M", "category": "process_argv",71 "pid": os.getpid(), "tid": threading.current_thread().ident,72 "ts": time.time(),73 "name": "process_argv", "args": {"argv": sys.argv}}74 _log_file.write("%s\n" % json.dumps(x))75 else:76 _note("trace_event: Opened existing tracelog")77 _log_file.flush()78 fcntl.lockf(_log_file.fileno(), fcntl.LOCK_UN)79@_locked80def trace_flush():81 if _enabled:82 _flush()83@_locked84def trace_disable():85 global _enabled86 if not _control_allowed:87 raise TraceException("Tracing control not allowed in child processes.")88 if not _enabled:89 return90 _enabled = False91 _flush(close=True)92def _flush(close=False):93 global _log_file94 fcntl.lockf(_log_file.fileno(), fcntl.LOCK_EX)95 _log_file.seek(0, os.SEEK_END)96 if len(_cur_events):97 _log_file.write(",\n")98 _log_file.write(",\n".join([json.dumps(e) for e in _cur_events]))99 del _cur_events[:]100 if close:101 # We might not be the only process writing to this logfile. So,102 # we will simply close the file rather than writign the trailing ] that103 # it technically requires. The trace viewer understands that this may happen104 # and will insert a trailing ] during loading.105 pass106 _log_file.flush()107 fcntl.lockf(_log_file.fileno(), fcntl.LOCK_UN)108 if close:109 _note("trace_event: Closed")110 _log_file.close()111 _log_file = None112 else:113 _note("trace_event: Flushed")114@_locked115def trace_is_enabled():116 return _enabled117@_locked118def add_trace_event(ph, ts, category, name, args=None):119 global _enabled120 if not _enabled:121 return122 if not hasattr(_tls, 'pid') or _tls.pid != os.getpid():123 _tls.pid = os.getpid()124 global _atexit_regsitered_for_pid125 if _tls.pid != _atexit_regsitered_for_pid:126 _atexit_regsitered_for_pid = _tls.pid127 atexit.register(_trace_disable_atexit)128 _tls.pid = os.getpid()129 del _cur_events[:] # we forked, clear the event buffer!130 tid = threading.current_thread().ident131 if not tid:132 tid = os.getpid()133 _tls.tid = tid134 if ts:135 ts = 1000000 * ts136 _cur_events.append({"ph": ph, "category": category,137 "pid": _tls.pid, "tid": _tls.tid,138 "ts": ts,139 "name": name, "args": args or {}});140def trace_begin(name, args=None):141 add_trace_event("B", time.time(), "python", name, args)142def trace_end(name, args=None):143 add_trace_event("E", time.time(), "python", name, args)144def _trace_disable_atexit():...

Full Screen

Full Screen

logger.py

Source:logger.py Github

copy

Full Screen

1#!/usr/bin/python2.42#3#4# Copyright 2007, The Android Open Source Project5#6# Licensed under the Apache License, Version 2.0 (the "License");7# you may not use this file except in compliance with the License.8# You may obtain a copy of the License at9#10# http://www.apache.org/licenses/LICENSE-2.011#12# Unless required by applicable law or agreed to in writing, software13# distributed under the License is distributed on an "AS IS" BASIS,14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15# See the License for the specific language governing permissions and16# limitations under the License.17"""Simple logging utility. Dumps log messages to stdout, and optionally, to a18log file.19Init(path) must be called to enable logging to a file20"""21import datetime22_LOG_FILE = None23_verbose = False24_log_time = True25def Init(log_file_path):26 """Set the path to the log file"""27 global _LOG_FILE28 _LOG_FILE = log_file_path29 print "Using log file: %s" % _LOG_FILE30def GetLogFilePath():31 """Returns the path and name of the Log file"""32 global _LOG_FILE33 return _LOG_FILE34def Log(new_str):35 """Appends new_str to the end of _LOG_FILE and prints it to stdout.36 Args:37 # new_str is a string.38 new_str: 'some message to log'39 """40 msg = _PrependTimeStamp(new_str)41 print msg42 _WriteLog(msg)43def _WriteLog(msg):44 global _LOG_FILE45 if _LOG_FILE is not None:46 file_handle = file(_LOG_FILE, 'a')47 file_handle.write('\n' + str(msg))48 file_handle.close()49def _PrependTimeStamp(log_string):50 """Returns the log_string prepended with current timestamp """51 global _log_time52 if _log_time:53 return "# %s: %s" % (datetime.datetime.now().strftime("%m/%d/%y %H:%M:%S"),54 log_string)55 else:56 # timestamp logging disabled57 return log_string 58def SilentLog(new_str):59 """Silently log new_str. Unless verbose mode is enabled, will log new_str60 only to the log file61 Args:62 # new_str is a string.63 new_str: 'some message to log'64 """65 global _verbose66 msg = _PrependTimeStamp(new_str)67 if _verbose:68 print msg69 _WriteLog(msg)70def SetVerbose(new_verbose=True):71 """ Enable or disable verbose logging"""72 global _verbose73 _verbose = new_verbose74 75def SetTimestampLogging(new_timestamp=True):76 """ Enable or disable outputting a timestamp with each log entry"""77 global _log_time78 _log_time = new_timestamp79 80def main():81 pass82if __name__ == '__main__':...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful