Solved

provide a function for logging in jython

Posted on 2011-02-28
21
1,092 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Application Discovery Service in AWS

In the era of the cloud, customers migrating away from their existing on-premise infrastructure. This requires lots of planning, strategies, and effort to identify their existing resources and determine how best to migrate.  Datacenter migrations happen in four phases -

 
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 29

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
 
LVL 29

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

Get HTML5 Certified

Want to be a web developer? You'll need to know HTML. Prepare for HTML5 certification by enrolling in July's Course of the Month! It's free for Premium Members, Team Accounts, and Qualified Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Swadhin
Introduction of Lists in Python: There are six built-in types of sequences. Lists and tuples are the most common one. In this article we will see how to use Lists in python and how we can utilize it while doing our own program. In general we can al…
This article will show, step by step, how to integrate R code into a R Sweave document
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

630 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