473,379 Members | 1,491 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

Logging: Formatter: name of the function

Hi,

Is there a possibility to format a log message to give the function name
where the log appears?

Example

import logging

def aTestFunction():
logger.debug("This is a message")

The log should read:

aTestFunction This is a message.

There is a possibilty to format the module namewith %(module)s, but I
did not find one for the function name.

Is there a possibilty or can I create it myself?
How can I determine the function name within a function?
Introspection?

--
Greg
Dec 23 '05 #1
2 3275
On Fri, 23 Dec 2005 16:23:57 +0100, Gregor Horvath <g.*******@gmx.at> wrote:
Hi,

Is there a possibility to format a log message to give the function name
where the log appears?

Example

import logging

def aTestFunction():
logger.debug("This is a message")

The log should read:

aTestFunction This is a message.

There is a possibilty to format the module namewith %(module)s, but I
did not find one for the function name.

Is there a possibilty or can I create it myself?
How can I determine the function name within a function?
Introspection?

There's not a nice way that I know of, but you can do something like
import sys
def foo(): ... print 'logger string containing function name "%s"'%sys._getframe().f_code.co_name
... foo() logger string containing function name "foo"

However, you might want to consider using a decorator that could
wrap a function if debugging and leave it alone otherwise. Also you
can log before and after calling the function. E.g.,
def debugdeco(f): ... if not __debug__: return f
... def wrap(*args, **kw):
... print 'before entering function "%s" ...'%f.func_name
... result = f(*args, **kw)
... print 'after returning from function "%s" ...'%f.func_name
... return result
... wrap.func_name = f.func_name # make it look the same if desired
... return wrap
... @debugdeco ... def foo(something): print something; return 'whatever'
... foo('hello') before entering function "foo" ...
hello
after returning from function "foo" ...
'whatever' __debug__ = False File "<stdin>", line 1
SyntaxError: can not assign to __debug__

Oops, can't experiment that way ;-) ^Z
We'll just start it with -O to set __debug__ False:

[ 8:45] E:\Info\Politics>py24 -O
Python 2.4b1 (#56, Nov 3 2004, 01:47:27)
[GCC 3.2.3 (mingw special 20030504-1)] on win32
Type "help", "copyright", "credits" or "license" for more information. def debugdeco(f): ... if not __debug__: return f
... def wrap(*args, **kw):
... print 'before entering function "%s" ...'%f.func_name
... result = f(*args, **kw)
... print 'after returning from function "%s" ...'%f.func_name
... return result
... wrap.func_name = f.func_name # make it look the same if desired
... return wrap
... @debugdeco ... def foo(something): print something; return 'whatever'
... foo('hello')

hello
'whatever'

You could still do stuff unconditionally of course, and also inside foo.

Regards,
Bengt Richter
Dec 23 '05 #2
Le vendredi 23 décembre 2005 Ã* 16:23 +0100, Gregor Horvath a écrit :
Hi,

Is there a possibility to format a log message to give the function name
where the log appears?

Example

import logging

def aTestFunction():
logger.debug("This is a message")

The log should read:

aTestFunction This is a message.


You can use the currentframe of the inspect module. For example :
import inspect
def debug(string): ... frame = inspect.currentframe(1)
... print frame.f_code.co_name, string def a_test_function(): ... debug("This is a message") a_test_function()

a_test_function This is a message

But please take note that this is not recommended. As stated in the
documentation of inspect.currentframe : "[t]his function should be used
for internal and specialized purposes only."
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?

Dec 23 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Marek Augustyn | last post by:
Hello, I'm getting strange exception raised using module logging. It's strange because it happens only sometimes, and it happens in different places (but always in a logging method). i.e. this...
6
by: Ville Vainio | last post by:
Just posting this for the sake of google: Like everyone else, I figured it's time to start using the 'logging' module. I typically want to dump "info" level (and up) log information to...
1
by: jjesso | last post by:
I am trying to add a new logging level. logging.config.fileConfig("bengineLog.cfg") logging.CLIENT = logging.INFO + 1 logging.addLevelName( logging.CLIENT, 'CLIENT' ) logging.root.setLevel( )...
2
by: rh0dium | last post by:
Hi all, So I have a slice of code which calls other python code. I have started to take a real liking to the logging module, but I want to extend this into the called python code. I have no...
1
by: Joel.Hedlund | last post by:
Hi! I'm writing a server and I want to use the logging module for logging stuff. I want to log all transactions in detail, and if everything goes haywire I want to know which client did it....
5
by: Ritesh Raj Sarraf | last post by:
import os, sys, logging logger = logging.getLogger("my_app") conerr = logging.StreamHandler(sys.stderr) conerr.setLevel(logging.DEBUG) conerr_formatter = logging.Formatter('%(levelname)s...
0
by: rajesh.hanchate | last post by:
Please help me in resolving this issue. I am using EnterpriseLibrary 2.0 Exception and logging block for logging exceptions to event log. It works fine for sometime. After some time it stops...
12
by: Tekkaman | last post by:
I'm getting a strange behaviour from the "pathname" and "lineno" formatter mapping keys. Instead of my file and my line number I get: /usr/lib/python2.4/logging/__init__.py as the file, and...
3
by: seb | last post by:
Hi, I am writing to a file some basic information using the logging module. It is working but in the log file some line are printed several time. I had put some print debugging messages in the...
10
by: davy zhang | last post by:
mport logging import pickle # create logger logger = logging.getLogger("simple_example") logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch =...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.