Solved

provide a function for logging in jython

Posted on 2011-02-28
21
1,049 Views
Last Modified: 2012-05-11
HonorGod,
 How are you, i hope you are doing good.

 I need help for the following question
 Please provide me a logging function, where i can reuse it for calling it in my other functions, like i have lot of functions and class for doing various task like copying the jboss zip file,
 unzipping it, creating clusters, backing up config xml files and modifying them and few other tasks my jython script will do, so i should be able call the logging function provided by you in functions
 i write. If needed i can import it as module.

Please let me know if you need more info
0
Comment
Question by:wasman
  • 11
  • 8
  • 2
21 Comments
 
LVL 41

Expert Comment

by:HonorGod
ID: 35000925
I'm doing ok, thanks for asking.  ;-)  I hope that you too are doing well.

Are you asking for logging along the lines of what is discussed here?
http://www.jython.org/docs/library/logging.html

Or something else?
0
 

Author Comment

by:wasman
ID: 35003657
yeah i found a similar doc in python, yes please provide logging facility for the attached file,
http://docs.python.org/library/logging.html?highlight=import%20logging
the log should rotate every time i run the script with time stamp.


postconfig1.py
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 35006623
Be careful though.  Your question specifically identifies Jython.

What version of Jython are you using?

Is it bundled with another product?

If so, which one?

e.g., the version of Jython used by the wsadmin tool/utility in the WebSphere Application Server is at version 2.1, not 2.3 as is identified by your link to the Python logging facility.
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 35006641
You can find out by starting an interactive session, and executing the following

import sys;
print sys.version;

Open in new window

0
 

Author Comment

by:wasman
ID: 35008121
sorry for the confusion, after reading python and jython books, i came to know there is not much difference between python and jython,
the only major difference is in jython we can write java classes

Also i am not using the jython scripting for WebSphere env, i am using it for automating the installing and manual configurations in jboss env.

In my redhat linux environment, i am using jython standalone jar file sometimes and sometimes i am using jython full installation.
the version i am using is jython2.5.2
[webadmin@fedora scripts]$ java -jar jython.jar
Jython 2.5.2rc3 (Release_2_5_2rc3:7184, Jan 10 2011, 22:54:57)
[Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.6.0_23
Type "help", "copyright", "credits" or "license" for more information.
>>>

all sample code i get from python book is getting executed in this jython interpreter
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 35008893
Excellent!  Thanks for that clarification.

So, how else can I help?
0
 

Author Comment

by:wasman
ID: 35009235

Please provide answer to my initial question, provide logging function and give me an example how i can call it from different functions, remember my logging function should be
 able to rotate logs with time stamp, every time i restart my script , use the attached the python script.

By the way the i didn't written this script, i am not that expert yet :)
engine.txt
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 35010254
ok, this is going to require some clarification.  Please forgive me for my lack of understanding.

> Please provide me a logging function, where i can reuse it for calling it in my other functions,
> like i have lot of functions and class for doing various task like copying the jboss zip file,

I thought that you had "found" it with the logging module mentioned above:
  http://e-e.com/Q_26853472.html#a35003657

I will modify the example engine.txt after I get the answers to the following questions

Q: What, exactly, do you mean by "able to rotate logs with time stamp"?

Q: Do you have different "levels" of severity for the messages to be written?

Q: Do you want the name of the log file to be passed in as a script parameter, or hard coded in the script, or do you want the script to prompt the user for the filename?

> i am not that expert yet :)

  Don't worry about it.  We're here to help.

Thanks for the clarifications!
0
 

Author Comment

by:wasman
ID: 35010466
i passed that link for only reference, i don't know how to implement that in the current attached engine.txt,

Q: What, exactly, do you mean by "able to rotate logs with time stamp"?
like below, don't worry about timestamp
logging_rotatingfile_example.out
logging_rotatingfile_example.out.1
logging_rotatingfile_example.out.2
logging_rotatingfile_example.out.3
logging_rotatingfile_example.out.4
logging_rotatingfile_example.out.5

Q. o you have different "levels" of severity for the messages to be written?
Debug level is good for now

Q. Do you want the name of the log file to be passed in as a script parameter, or hard coded in the script, or do you want the script to prompt the user for the filename?
hardcoded in script

Here is the another python script i attached, where i defined all the classes
tags.txt
0
 
LVL 28

Expert Comment

by:pepr
ID: 35011082
I do not want to mix to your communication.  Just one suggestion.  Define your own function like log(s) (possibly in some module like log.py).  It may be easier for you to use the simplified interface.

You can implement the function so that anything else is hidden behind the scene -- including the filename choice, the implementation possibly via the standard logging module or via some simpler "append line to the file".
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 28

Expert Comment

by:pepr
ID: 35012218
I also suggest to compose the date to the log filename and erase the logs older than... It depends on situation.  In my opinion, it does not help too much to reuse say 10 names of the files.  It is easier and more practical to generate new filenames that are better bound via their name to the time of their creations.  It should be as easy as possible to say what the name of the log file should be used "just now".
0
 

Author Comment

by:wasman
ID: 35017876
HonorGod,

Any updates!!! i am waiting on your input
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 35020286
tags.py is non-trivial.  As such, your request to add logging raises some questions, e.g.,

Q: In order to to better understand the code that you provided, is the source for "util.py" available?

Q: How, exactly, (and why) do you want logging to be added?

Q: Are you simply trying to understand how the code works?

Q: Or, are you trying to make the code more robust / maintainable by having the logging as an integral part of the code?

Q: From where did this code originate?  [this is not super important, I'm just curious]
0
 

Author Comment

by:wasman
ID: 35020808
i have the util.py but i don't want to complicate any further, i attached another file which is written by you only earlier, please write a seperate module for logging and import it into postconfig.py ( attached to ticket),
make all functions in postconfig.py to through output to log when they get executed. Simple to say is , what ever i see in the console when i run postconfig.py, i should see them in logs also. And i need new log everytime i
execute my python script

I was trying to write log module my self, but i can't make it work,
import glob
import logging
import logging.handlers


LOG_FILENAME = 'example.log'
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=20, backupCount=5)

def jboss_log(LOG_FILENAME):
    my_logger.addHandler(handler)



Yes this is important for me, bcz my project manager is waiting on this, this is kind learn and work project.
   
postconfig1.txt
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 35021057
It's not your fault.

The tutorial has some mistakes. ;-(

This may be simple enough for your situation:
>>> import logging
>>>
>>> def g() :
...   1/0
...
>>>
>>> def f() :
...   logging.debug( 'Enter: f()' )
...   try :
...     g()
...   except :
...     logging.exception( 'Houston, we have a problem.' )
...   logging.debug( ' Exit: f()' )
...
>>> # Log everything, writing to stderr by default
>>> logging.basicConfig( level=logging.DEBUG )
>>>
>>> f()
DEBUG:root:Enter: f()
ERROR:root:Houston, we have a problem.
Traceback (most recent call last):
  File "<stdin>", line 4, in f
  File "<stdin>", line 2, in g
ZeroDivisionError: integer division or modulo by zero
DEBUG:root: Exit: f()
>>>

Open in new window

0
 
LVL 41

Accepted Solution

by:
HonorGod earned 500 total points
ID: 35021170
A slightly more complex example:

Sample output:
----------------------------------------------------------------------
DEBUG 2011-03-02 15:04:00,124 f 8 Enter: f()
ERROR 2011-03-02 15:04:00,124 exception 1021 Houston, we have a problem.
Traceback (most recent call last):
  File "bob.py", line 10, in f
    g()
  File "bob.py", line 4, in g
    1/0
ZeroDivisionError: integer division or modulo by zero
DEBUG 2011-03-02 15:04:00,154 f 13  Exit: f()
----------------------------------------------------------------------
import logging

def g() :
  1/0

def f() :
  flog = logging.getLogger( 'flog' )
  flog.debug( 'Enter: f()' )
  try :
    g()
  except Exception, e :
    flog.exception( 'Houston, we have a problem.' )
  flog.debug( ' Exit: f()' )

def init() :
  global_log = logging.getLogger( 'flog' )
  global_log.setLevel( logging.DEBUG )
  handler   = logging.StreamHandler()
  formatter = logging.Formatter( '%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s' )
  handler.setFormatter( formatter )
  global_log.addHandler( handler )

if __name__ == '__main__' :
  init()
  f()
else :
  print 'Usage: jython %s.py'

Open in new window

0
 
LVL 41

Expert Comment

by:HonorGod
ID: 35021333
ah, I found the mistake I was making with the example from the tutorial.

When I put the following code into a file, and executed it with Jython, the output is:
------------------------------------------------------------
logging_rotatingfile_example.out
logging_rotatingfile_example.out.1
logging_rotatingfile_example.out.2
logging_rotatingfile_example.out.3
logging_rotatingfile_example.out.4
logging_rotatingfile_example.out.5
------------------------------------------------------------
as expected... as long as you expect log file rotation to include the renaming of
existing files when log file rollover occurs.


import glob
import logging
import logging.handlers

LOG_FILENAME = 'logging_rotatingfile_example.out'

# Set up a specific logger with our desired output level
my_logger = logging.getLogger( 'MyLogger' )
my_logger.setLevel( logging.DEBUG )

# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler( LOG_FILENAME, maxBytes=20, backupCount=5 )

my_logger.addHandler( handler )

# Log some messages
for i in range(20):
    my_logger.debug('i = %d' % i)

# See what files are created
logfiles = glob.glob('%s*' % LOG_FILENAME)

for filename in logfiles:
    print filename

Open in new window

0
 
LVL 41

Expert Comment

by:HonorGod
ID: 35021373
I believe that what you don't appear to realize, from your post:

http://e-e.com/Q_26853472.html#a35020808

is that this code:

def jboss_log(LOG_FILENAME):
    my_logger.addHandler(handler)

doesn't generate, or log any output.

As I said earlier, it is non-trivial, and will take quite a bit of explanation.

Let me take a look at tags.py, as provided in http://e-e.com/Q_26853472.html#a35010466
to see how I would add logging to it.
0
 

Author Closing Comment

by:wasman
ID: 35022360
Thanks for trying, i will open another ticket with clean  and fresh start.
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 35027094
Thank you so much for the grade & points.

Good luck & have a great day.

Unfortunately, I'm home sick today, and having difficulty concentrating. ;-(
0
 

Author Comment

by:wasman
ID: 35027550
oh man i am really sorry to put pressure on you. Take rest...Hope you will get well soon.

My tickets can wait. :)
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

This article will show the steps for installing Python on Ubuntu Operating System. I have created a virtual machine with Ubuntu Operating system 8.10 and this installing process also works with upgraded version of Ubuntu OS. For installing Py…
Introduction On September 29, 2012, the Python 3.3.0 was released; nothing extremely unexpected,  yet another, better version of Python. But, if you work in Microsoft Windows, you should notice that the Python Launcher for Windows was introduced wi…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now