Monday, October 06, 2008

WINDOW.OPEN using POST instead of GET

function toPreview(f) {

f.action = "";

f.onsubmit = "return true;";
f.target ="preview";

var theHeight = 550;
var theWidth = 480;
var theTop=(screen.height/2)-(theHeight/2);
var theLeft=(screen.width/2)-(theWidth/2);
var features='height='+theHeight+',width='+theWidth+',top='+theTop+',left='+theLeft+",scrollbars=yes";
window.open('','preview',features);
}

Tuesday, September 02, 2008

db2pd -

A new DB2 UDB utility for monitoring DB2 instances and databases

ref

How can I make an SQL INSERT faster?

DB2 has added a new keyword to the CREATE and ALTER TABLE SQL statements: APPEND. This new keyword enables a pretty simple concept. If you CREATE or ALTER a TABLE to APPEND YES, DB2 simply sticks the new row at the end of the table*, makes no attempt at searching for available space, and makes no effort to preserve any kind of clustering order. Because you can ALTER this attribute on and off, you can switch it on (YES) for that massive insert batch job you run once a month and always follow with REORG/RUNSTATS anyway, then switch it back off (NO) for your day to day online insert processing. REORG is unaffected by the APPEND option so you can use it in conjunction with a tables clustering options allowing the object to take advantage of a faster insert and still maintaining a clustered sequence by the REORG and LOAD utilities.

The APPEND will work for all tables except those created in LOB, XML, and work files table spaces. BTW, this process is for insert and online LOAD operations. There is also a new column, APPEND, in SYSIBM.SYSTABLES so you can track when this feature has been turned on or off. In addition, you are going to see some index relief for inserts in DB2 9. But I'll save that for another post.



Ref

Revision: Runstats vs Reorg

In case you are new, we run REORG & then RUNSTAT when we do mass inserts/updates/deletes on DB or individual tables,so that the query runs faster . REORG and RUNSTAT are DB command.
RUNSTATS
1) Updates datadictionary stats. When a query is fired it reads the data dictionary table (dictionary managed) and calculates the cost,etc.

2) Gathers summary information about the characteristics of the data in table spaces and indexes. This information is recorded in the DB2 catalog, and is used by DB2 to select access paths to data during the bind process. It is available to the database administrator for evaluating database design, and determining when table spaces or indexes should be reorganized .




REORG
1) Put all the contiginous blocks together,so data reads / inserts will happen faster as it need not scan the pages. (example is defragmentation in windows)

2) Reorganized a table space to improve access performance and reclaim fragmented space. In addition, the utility can reorganize a single partition of either a partitioned index ora partitioned table space. If you specify REORG UNLOAD ONLY or REORG UNLOAD PAUSE, the REORG utility unloads data in a format acceptable to the LOAD utility of the same DB2 table space.
REORGCHK
do a reorgchk on a certain schema, which will runstat all tables in the schema, whereas doing runstats alone,
then you need to do it table by table.


TIPS
1) Run REORG & then RUNSTAT.

2) It is not necessary to run reorg for all tables :use REORGCHK ON TABLE ALL find which tables require reoganization and run REORG & then RUNSTAT for that specified tables.


EXAMPLE
REORG INDEXES ALL FOR TABLE MYSCHEMA.TABLEA ALLOW WRITE ACCESS;
RUNSTATS ON TABLE MYSCHEMA.TABLEA WITH DISTRIBUTION AND DETAILED INDEXES ALL;
RUNSTATS ON TABLE MYSCHEMA.TABLEA ON ALL COLUMNS ALLOW WRITE ACCESS;


ref


Where exactly is a DB2 plan stored?

Catalog contains information about plans in the following tables:
  • SYSIBM.SYSDBRM
  • SYSIBM.SYSPLAN
  • SYSIBM.SYSPLANAUTH
  • SYSIBM.SYSPLANDEP
  • SYSIBM.SYSSTMT

And, the DB2 Catalog contains information about packages in the following tables:

  • SYSIBM.SYSPACKAGE
  • SYSIBM.SYSPACKAUTH
  • SYSIBM.SYSPACKDEP
  • SYSIBM.SYSPACKLIST
  • SYSIBM.SYSPACKSTMT
  • SYSIBM.SYSPKSYSTEM
  • SYSIBM.SYSPLSYSTEM
ref

Step SQL Optimize

db2expln -d tibsdb -f xx/sql -o xx.log

db2expln - SQL Explain Command
http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/core/r0005736.htm

The Two Biggest DB2 Performance Things
ref

Check index
====
db2 "describe indexes for table tibsadmin.fundtransferhistory"
db2 "SELECT colnames,tbname FROM SYSIBM.SYSINDEXES where upper(tbname) =upper('fundtransferhistory') ";

db2expln -d tibsdb -f 1.sql -o 1.log


drop index ;
CREATE INDEX {index_name} ON {table} ( {column1} ASC,
{column2} ASC) ;
CREATE INDEX
{index_name} ON {table} ( {column1} ASC) CLUSTER ;
**cluster index is physical index. Only 1 cluster index per table

Setup JMeter for load test
====================
pre requisite-put the db2 drirver.jar to jmeter/lib

1)Test Plan -> Add Thread Group
2)Thread Group->Add->Config Element ->JDBC Connection Configuration
3)Max number of connection = {> Number of thread}
Database url = jdbc:db2://{host}:{port}/{dbname}
Jdbc driver classess = com.ibm.db2.jcc.DB2Driver
username=
password=
**package for "com.ibm.db2.jcc" is ibm jdbc driver type4
**package for "COM.ibm.db2.jdbc" is ibm jdbc driver type2 which use by websphere server
**"DB2Driver" class is normal driver
**"DB2ConnectionPoolDataSource" class is connection pool data source.
****jdbc:db2://10.100.101.30:61099/tibsdb


4)Thread Group->Add->Sampler->JDBC Request
**For insert sql, u can create Non Duplicate ID using this function
CHAR( ${__counter(FALSE,100)} )

example:
INSERT INTO Schema.Mytable VALUES ( CHAR( ${__counter(FALSE,100)} )
, 'AbcValue')

5)ThreadGroup ->Add->Listner
i)Summary report - to view summary statistic
ii)View Results Tree - to check the request and response data
iii) Aggregate Report - Have 90% line











ref 1 : How to easily populate a table with random data

Thursday, August 21, 2008

Rational Software Development Conference 2008

19th August 2008 @ Sheraton Subang Hotel

Presentation Slide to be downloaded
http://www-07.ibm.com/my/events/rsdc2008/download.html

What is Jazz?

Developing software in a team is much like playing an instrument in a band. Both require a balance of collaboration and virtuosity. Jazz defines a vision for the way products can integrate to support this kind of collaborative work, and a technology platform to deliver on this vision.

Jazz is an IBM Rational project to build a scalable, extensible team collaboration platform for integrating work across the phases of the development lifecycle. We believe Jazz will help teams build software more effectively while making the software development activity more productive and enjoyable.

Reference

https://jazz.net/pub/index.jsp Jazz.net
i) Collaborative in Context
- Build better

ii)Right size governance
- workflow for check in source code
- earlier bug detection
-pick right process for you

iii)Day One productivity -easy setup development environment

iv)Open & Extensible architecture
http://www.ibm.com/software/rational/collaborate
the flexibility to assemble your own software delivery platform, relying on your preferred vendors and solutions.

"Suppose we expose data to internet?"
Ans:Internet create challenge, solve it.

Scaling Agile Software Deveploment: Apply Agile in Complex Situations

Agile software development refers to a group of software development methodologies that promotes development iterations, open collaboration, and process adaptability throughout the life-cycle of the project. Surveys Exploring The Current State of Information Technology Practices
http://www.ambysoft.com/surveys/
Leader of tomorrow -Adapt Agile technique Jazz platform
-Team concert
-Rational Requirement Composer
-Rational Quality Manager

RMC 7.5 Agile Core -Iteration Development
-Continuous integration
-Test driven Development Reason

------- Whole team will focus for the next iteration Focus more time in planning, compare with traditional methodology which is get everything requirement in the beginning stage which may have alot unseen thing. Statistic saying there is 45% of features of system never use. http://www.agiledata.org/essays/enterpriseArchitecture.html

Enable Security Testing across the Software Development Life cycle with AppScan
Make securty as QA task

Using Rational Requirment Tools to implement Business Driven Development
IBM Rational Requirements Composer http://www.ibm.com/software/rational/announce/rrc -rich test requirement
-use cases
<->good because from user point of view
-UI sketching and storyboarding
-process sketching
-contain iRise + RavenFlow

Wednesday, August 13, 2008

Check index db2

db2 "describe indexes for table tibsadmin.fundtrasnferhistory"

SELECT colnames,tbname FROM SYSIBM.SYSINDEXES
where tbname ='ECEREMITTANCE';

Thursday, July 24, 2008

Retro

Operates by transforming Java class files compiled by a 1.5 compiler into version 1.4 class files which can then be run on any 1.4 virtual machine.

Tuesday, July 01, 2008

catalog node and catalog db @ db2

CATALOG [ADMIN] TCPIP NODE node-name REMOTE hostname [SERVER service-name]
db2 => catalog tcpip node rhbdemo remote 192.168.1.23 server 50000

db2 => list node directory

CATALOG DATABASE database-name [AS alias] [ON drive | AT NODE node-name]
db2 => catalog database ibsdb as rhbdb at node rhbdemo

Tuesday, June 24, 2008

LAB 1: Install OS Zone & DB2

1.LAB 1: Install OS Zone & DB2

1.1.Prerequisites / Hardware Requirement

  1. Solaris OS needs 4 GB disk space and 400MB RAM

  2. Each additional zone needs 70MB hard disk

  3. Swap space

    1. Normally same as the VM physical RAM

    2. Disk space for tmp folder

    3. Check how many swap space for each application servers and sum up (may check from info center)

      • WAS & WPS 6.0, tmp folder needs minimum 1.5GB

      • DB2 512MB RAM

      • IBM HTTP Server 0.5GB RAM, 1GB disk space

      • LDAP

      • Network Deployment

  4. VM Hard disk space = Solaris OS disk space + Swap space

  5. How many zones required? Depending on the infrastructure designs.

Define Zone

Memory

Hard disk (GB)

Zone 1: DB2

0.5 GB

0.2

Zone 2: Network Deployment

0.5 GB (512MB)

0.3

Zone 3: WAS/WPS Cluster 1


(1.7x2)+(1.5x2) = 6.4

Zone 4: WAS/WPS Cluster 2


(1.7x2)+(1.5x2) = 6.4

Zone 5: Web Server

0.5 GB

1

Zone 6: LDAP


0.2

Zone 7: Solaris 10

0.4 GB

4

Swap Space

Equal to physical memory

1.5

TOTAL:

4 GB

20 GB

1.2.Create Virtual Machine

  1. Name and Location

  1. Guest Operating System – Solaris Operating System (64-Bit)

  1. Memory and Processor - 4GB and 2 processors

  1. Hard Disk – 20GB

  1. Network Adapter – Bridged

Notes:

  • Bridged – network created is visible inside and outside.

  • Host Only – invisible from inside and outside.

  • NAT – invisible inside, but can go out.

  1. CD / DVD Drive – Use an ISO image (sol-10-u4-ga-x86-dvd.iso)

  1. Floppy Drive – Don’t add a floppy drive.

  1. USB Controller – either one will do.

  2. Ready to complete – verify summary and click finish.

1.3.Install Solaris 10

  1. Installation Summary

Network: Yes

DHCP: No

Hostname: [Juice/Kfc/Arsenal]

IP: [192.168.16.1 / 192.168.17.1 / 192.168.18.1]

Subnet mask: 255.255.0.0

Enable IPv6: No

  1. Steps for installing

Check Route Table

$ netstat -rn

Shut down Solaris

$ shutdown –g0 –i5 –y OR $ init 5

Reboot Solaris

$ shutdown –g0 –i6 –y OR init 6 OR reboot

  1. DHCP is dynamically assigned IP. If yes, the server is dependant on DHCP (not HA), means if DHCP server down, this will affect our own server.

  2. To know which network it routes to, netmask (BINARY) AND destination IP.

  3. After installation, at VMWare console, click “Add VMWare Plugin” to install plugin to Guest. Select 800x600 resolution.

1.4.Configure SSH

  1. To allow root login remotely

    1. $ cd /etc/ssh

    2. $ vi sshd_config (server config)

  1. edit PermitRootLogin from no to yes

    1. $ svcadm restart ssh

    2. Verify: ssh from another machine

  1. Generate trust key (Every time root remotely login, no need to key in password)

  1. Navigate to root’s home directory

  2. $ ls –a

  3. $cd .ssh

  4. Check if there is id_rsa.pub inside. If no, generate the public and private key:

    1. $ ssh-keygen –t rsa [-f keyname]

  5. If no directory .ssh, generate using command:

    1. $ ssh localhost date (generate .ssh directory in home directory)

  6. $scp id-rsa.pub_root@coffee:/tmp

  7. in coffee server, mv /tmp/id_rsa.pub /root/.ssh/authorized_keys2

  1. Disable send mail

$ svcadm disable sendmail

1.5.Create Virtual Hard Disk

  1. At the VMWare Host,

    1. $ vmware-vdiskmanager –c –s 4GB 0a lsilogic –t 0 disk1.vmdk

  2. At the VMWare Guest GUI, Add Hardware > Add Hard disk

  1. At the VMWare Guest

    1. $ touch/reconfigure (Issue scan OS hardware)

    2. $ init 6

1.6.Create Storage Pool and Zone

Check available disk

$ format

c1t0d0

c1t1d0 (new virtual disk)

Check file system usage

$ df –h

Create storage pool

- zpool create <pool> <virtual device>

$ zpool create tank c1t1d0

Check storage pool status

$ zpool status

Create new ZFS file system

$ zfs create tank/zones

Set mount point to global zone

$ zfs set mountpoint=/zones tank/zones

List all ZFS

$ zfs list

Create a new zone

- zfs create <zone path/zone name>

$ zfs create tank/zones/db

Create zone conf file to install the zone

$ vi /zones/db/db.cfg

Create

set zonepath=/zones/db

set autoboot=false

add net

set physical=e1000g0

set address=192.168.16.2

end

add fs

set type=lofs

set special=/software

set dir=/sw

end

verify

commit

Configure zone

$ zonecfg –z db –f db.cfg

List zones with status

Status: CONFIGURED, INSTALLED, RUNNING

$ zoneadm –z list –cv (zone now is configured)

$ zonecfg –z db info

Change zone mod

Change the file permission for zone root before install

$ chmod 700 db

Install package to zone

(It takes some time to install)

$ zoneadm –z db install

Boot/Start the zone

(Boot the zone since set the autoboot to false)

$ zoneadm –z boot

Login to zone’s system console

$ zlogin –C db

Choose DECVT100 Terminal

Logout zone

$ exit

Login: ~.

Password: ~.

Check zone status continually

$ while true; do zoneadm list –cv; sleep 3; done

1.7.Add Domain Name

  1. Login to the zone

  2. Edit /etc/hosts

  3. Add one domain name to the server ip address

  4. Test the domain name

$ ping <ip address>

$ ping –s <domain name>

1.8.Install DB2 Server on DB Zone

Copy installation file (SSH & Untar)

$ cat C9658ML.tar | ssh root@192.168.16.1 “(mkdir -p /software/db2; cd /software/db2; gzip -cd; tar -xvf -)”

Install DB2 Server

$ cd /software/db2

$ ./db2_install

Enter: DB2.ESE

Import DB2 License

$ /opt/IBM/db2/v8.1/adm/db2licm -a <license: db2ese.lic >

Create group

$ groupadd –g 100 db2fgrp1

$ groupadd –g 101 db2agrp

$ groupadd –g 102 db2igrp1

Create user

$ useradd –u 100 –g db2fgrp1 –d /export/home/db2fenc1-m db2fenc1

$ useradd –u 101 –g db2agrp –d /export/home/db2adm -m db2adm

$ useradd –u 100 –g db2igrp1 –d /export/home/db2inst1-m db2inst1

Change user password

$ passwd db2fenc1

$ passwd db2adm

$ passwd db2inst1

Add instance service port

$ vi /etc/services

Add: db2c_db2inst1 50000/tcp

Create DB instance (It will generate sqllib directory)

$ cd /opt/IBM/db2/V8.1/instance

$ ./db2icrt –a SERVER –p db2c_db2inst1 –s ese –w 64 –u db2fenc1 db2inst1

(To drop the instance, use db2idrop)

Add project

$ projadd –c “DB2 instance 1” user.db2inst1

Set tuning parameter on resources control

$ su – db2inst1

$ id –p

$ exit

Modify project

Login to the zone again and set these:

$ projmod –s –K “project.max-shm-memory=(priv,4G,deny)” user.db2inst1

$ projmod –s –K “project.max-shm-ids=(priv,4K,deny)” user.db2inst1

$ projmod –s –K “project.max-msg-ids=(priv,4K,deny)” user.db2inst1

$ projmod –s –K “project.max-sem-ids=(priv,4K,deny)” user.db2inst1

Create SAMPLE database

$ cd /opt/IBM/db2/V8.1/bin

$ ./db2sampl

Verify database connection

$ db2 list db directory

$ db2 connect to sample user db2inst1

1.9.Install DB2 Client on Application Zone

Install DB2 Client

$ cd /software/db2

$ ./db2_install

Enter: DB2.ADMCL

Create group

$ groupadd –g 100 db2fgrp1

$ groupadd –g 101 db2agrp

$ groupadd –g 102 db2cgrp1

Create user

$ useradd –u 100 –g db2cgrp1 –d /export/home/db2inst1-m db2inst1

Change user password

$ passwd db2inst1

Add instance port

$ vi /etc/services

Add: db2c_db2inst1 50000/tcp

Create instance

$ cd /opt/IBM/db2/instance

$ ./db2icrt –a SERVER –s client –w 32 –u db2inst1 db2inst1

Login as client user

$ su – db2inst1

Catalog node

$ db2 “catalog tcpip node WPSNODE remote <DB Server IP/Hostname> server db2c_db2inst1

Catalog database

$ db2 “catalog database SAMPLE as SAMPLE at node WPSNODE”

1.10.Create Zone Snapshot

Shutdown all zones

$ zlogin <zone> init 5

Snapshot zone

$ zfs snapshot –r tank/zones@<filename>

Tuesday, May 27, 2008

Code Analysis

1) 1.jpg Right click on selected package or particular .java file ->Analysis-> Analysis / New_configuration(1) Here you can actually define the rules of code analysis. 2) 2.jpg Check the result in VIEW "Analysis Result" 3)
3.jpg Clicked the item of Analysis Result will bring you to the source of the issue. 4)
4.jpg Some issue provide u the quick fixed and solution when u clicked on the small symbol at your left handside.

Friday, May 02, 2008

Log4j PatternLayout

ConversionPattern =[%d{ISO8601}] %-5p : : %C{1}.%M : %m%n

Conversion Character Effect
c Used to output the category of the logging event. The category conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.

If a precision specifier is given, then only the corresponding number of right most components of the category name will be printed. By default the category name is printed in full.

For example, for the category name "a.b.c" the pattern %c{2} will output "b.c".

C Used to output the fully qualified class name of the caller issuing the logging request. This conversion specifier can be optionally followed by precision specifier, that is a decimal constant in brackets.

If a precision specifier is given, then only the corresponding number of right most components of the class name will be printed. By default the class name is output in fully qualified form.

For example, for the class name "org.apache.xyz.SomeClass", the pattern %C{1} will output "SomeClass".

WARNING Generating the caller class information is slow. Thus, it's use should be avoided unless execution speed is not an issue.

d Used to output the date of the logging event. The date conversion specifier may be followed by a date format specifier enclosed between braces. For example, %d{HH:mm:ss,SSS} or %d{dd MMM yyyy HH:mm:ss,SSS}. If no date format specifier is given then ISO8601 format is assumed.

The date format specifier admits the same syntax as the time pattern string of the SimpleDateFormat. Although part of the standard JDK, the performance of SimpleDateFormat is quite poor.

For better results it is recommended to use the log4j date formatters. These can be specified using one of the strings "ABSOLUTE", "DATE" and "ISO8601" for specifying AbsoluteTimeDateFormat, DateTimeDateFormat and respectively ISO8601DateFormat. For example, %d{ISO8601} or %d{ABSOLUTE}.

These dedicated date formatters perform significantly better than SimpleDateFormat.

F Used to output the file name where the logging request was issued.

WARNING Generating caller location information is extremely slow. It's use should be avoided unless execution speed is not an issue.

l Used to output location information of the caller which generated the logging event.

The location information depends on the JVM implementation but usually consists of the fully qualified name of the calling method followed by the callers source the file name and line number between parentheses.

The location information can be very useful. However, it's generation is extremely slow. It's use should be avoided unless execution speed is not an issue.

L Used to output the line number from where the logging request was issued.

WARNING Generating caller location information is extremely slow. It's use should be avoided unless execution speed is not an issue.

m Used to output the application supplied message associated with the logging event.
M Used to output the method name where the logging request was issued.

WARNING Generating caller location information is extremely slow. It's use should be avoided unless execution speed is not an issue.

n Outputs the platform dependent line separator character or characters.

This conversion character offers practically the same performance as using non-portable line separator strings such as "\n", or "\r\n". Thus, it is the preferred way of specifying a line separator.

p Used to output the priority of the logging event.
r Used to output the number of milliseconds elapsed from the construction of the layout until the creation of the logging event.
t Used to output the name of the thread that generated the logging event.
x Used to output the NDC (nested diagnostic context) associated with the thread that generated the logging event.
X

Used to output the MDC (mapped diagnostic context) associated with the thread that generated the logging event. The X conversion character must be followed by the key for the map placed between braces, as in %X{clientNumber} where clientNumber is the key. The value in the MDC corresponding to the key will be output.

See MDC class for more details.

% The sequence %% outputs a single percent sign.



ref

Is it possible to direct log output to different appenders by level?

Is it possible to direct log output to different appenders by level?

Yes it is. Setting the Threshold option of any appender extending AppenderSkeleton, (most log4j appenders extend AppenderSkeleton) to filter out all log events with lower level than the value of the threshold option.


ref

Rolling File and errors to email

Log messages with Level info to fatal to a file and send messages from error to fatal by email. The file should be rolled every 100 KB.

You need mail.jar and activation.jar libraries from J2EE to send emails. Further properties of the SmtpAppender are described here:

http://logging.apache.org/log4j/docs/api/org/apache/log4j/net/SMTPAppender.html

log4j.properties

### file appender
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.maxFileSize=100KB
log4j.appender.file.maxBackupIndex=5
log4j.appender.file.File=test.log
log4j.appender.file.threshold=info
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

#email appender
log4j.appender.mail=org.apache.log4j.net.SMTPAppender
#defines how othen emails are send
log4j.appender.mail.BufferSize=1
log4j.appender.mail.SMTPHost="smtp.myservername.xx"
log4j.appender.mail.From=fromemail@myservername.xx
log4j.appender.mail.To=toemail@myservername.xx
log4j.appender.mail.Subject=Log ...
log4j.appender.mail.threshold=error
log4j.appender.mail.layout=org.apache.log4j.PatternLayout
log4j.appender.mail.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.rootLogger=warn, file, mail


ref

Reconfigure a running log4j configuration

If you analyse a problem you frequently want to change the log level of a running application server. This chapter explains how you can do this. I used Tomcat as example server but you can use any application server you like.

The XML actually offers a method to watch changes in config files.

http://logging.apache.org/log4j/docs/api/org/apache/log4j/xml/DOMConfigurator.html#configureAndWatch(java.lang.String)

The problem is that it seems not to work in some situations. But this is no problem as it is quite easy to develop a short tool by yourself. We have two options. We could change the log level during runtime:

Logger root = Logger.getRootLogger();
root.setLevel(Level.WARN);

or we can reload the configuration:

// PropertyConfigurator.configure(url);
DOMConfigurator.configure(url);

The following example will check the configuration file in defined intervals and reconfigure log4j if any changes are found.

We need to create three things:

a) a monitor thread, monitoring the configuration file and reconfiguring log4j if needed

b) a servlet starting and stopping the monitor thread

c) an entry in the web.xml, to initialize the servlet

The following class monitors the logj4 configuration file and checks with the last change date has changed:

package de.laliluna.logexample;

import java.io.File;
import java.net.URL;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;

public class MonitorThread implements Runnable {

private static Logger log = Logger.getLogger(MonitorThread.class);

boolean interruped;

private long checkIntervalMillis = 10000;

private URL url;

private File file;

// stores the last modification time of the file
private long lastModified = 0;

public void run() {
System.out.println("Initialize " + url.getPath());
file = new File(url.getPath());
// PropertyConfigurator.configure(url);
DOMConfigurator.configure(url);
lastModified = file.lastModified();

monitor();
}

private void monitor() {
log.info("Starting log4j monitor");

while (!interruped) {

// check if File changed
long temp = file.lastModified();
if (lastModified != temp) {
log.info("Initialize log4j configuration " + url.getPath());
// PropertyConfigurator.configure(url);
DOMConfigurator.configure(url);

lastModified = temp;

} else
log.debug("Log4j configuration is not modified");
try {
Thread.currentThread().sleep(checkIntervalMillis);
} catch (InterruptedException e) {
interruped = true;
}
}
log.info("Shutting down log4j monitor");

}

public URL getUrl() {
return url;
}

public void setUrl(URL url) {
this.url = url;
}

public long getCheckIntervalMillis() {
return checkIntervalMillis;
}

/**
* Sets the interval for checking the url for changes. Unit is
* milliseconds, 10000 = 10 seconds
*
* @param checkIntervalMillis
*/
public void setCheckIntervalMillis(long checkIntervalMillis) {
this.checkIntervalMillis = checkIntervalMillis;
}

public boolean isInterruped() {
return interruped;
}

public void setInterruped(boolean interruped) {
this.interruped = interruped;
}

}

The servlet starts and stops the monitor thread:

package de.laliluna.logexample;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

public class Log4jConfigLoader extends HttpServlet {

private Thread thread;

@Override
public void destroy() {
thread.interrupt();
super.destroy();
}

public void init() throws ServletException {
super.init();
MonitorThread monitorThread = new MonitorThread();
monitorThread.setCheckIntervalMillis(10000);
monitorThread.setUrl(Log4jConfigLoader.class.getResource("/log4j.xml"));
thread = new Thread(monitorThread);
thread.start();
}

}

We add the servlet to the web.xml to initialize it.



xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

log4j-init
de.laliluna.logexample.Log4jConfigLoader
10




ref

Wednesday, April 30, 2008

log4j

log4j.rootCategory=debug, rolling
# log4j.rootCategory=warn, stdout, rolling, socketLogger, lf5, xml, lf5Rolling

# Example of adding a specific package/class at a different
# logging level...
# --log everything in the com.johnmunsch package at debug level
# ..even better, send it to a different appender. Note, however, that
# this doesn't mean that any loggers from a lower level won't be used:
# everything still inherits, so this new logger is used _in_addition_to_
# the loggers it would have otherwise already used.
log4j.category.com.johnmunsch=debug, socketLogger

# --on the other hand, everything in the
# com.johnmunsch.stuff class _shouldn't_ log
# unless the log message is at 'warn' level or worse.
# (It just so happens that stuff generates a _lot_ of
# logging when it's used)
log4j.category.com.johnmunsch.stuff=warn

# --also, it just so happens that we have a different
# appender that we're using that we want to have
# log information from a specific location, and we
# don't want to send that information anywhere else.
log4j.category.com.johnmunsch.otherstuff=warn, xml
log4j.additivity.com.johnmunsch.otherstuff=false

# BEGIN APPENDER: CONSOLE APPENDER (stdout)
# first: type of appender (fully qualified class name)
log4j.appender.stdout=org.apache.log4j.ConsoleAppender

# second: Any configuration information needed for that appender.
# Many appenders require a layout.
log4j.appender.stdout.layout=org.apache.log4j.TTCCLayout
# log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout

# Possible information overload?
# log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# additionally, some layouts can take additional information --
# like the ConversionPattern for the PatternLayout.
# log4j.appender.stdout.layout.ConversionPattern=%d %-5p %-17c{2} (%30F:%L) %3x
- %m%n
# END APPENDER: CONSOLE APPENDER (stdout)

# BEGIN APPENDER: ROLLING FILE APPENDER (rolling)
# first: type of appender (fully qualified class name)
log4j.appender.rolling=org.apache.log4j.RollingFileAppender

# second: Any configuration information needed for that appender.
# Many appenders require a layout.
log4j.appender.rolling.File=example.log

log4j.appender.rolling.MaxFileSize=100KB
# Keep one backup file
log4j.appender.rolling.MaxBackupIndex=1

log4j.appender.rolling.layout=org.apache.log4j.PatternLayout
log4j.appender.rolling.layout.ConversionPattern=%p %t %c - %m%n

# Possible information overload?
# log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# additionally, some layouts can take additional information --
# like the ConversionPattern for the PatternLayout.
# log4j.appender.stdout.layout.ConversionPattern=%d %-5p %-17c{2} (%30F:%L) %3x
- %m%n
# END APPENDER: ROLLING FILE APPENDER (rolling)

# BEGIN APPENDER: SOCKET APPENDER (socketLogger)
# Note: if you don't have anything configured to accept the events
# from the socketLogger appender, you'll see an exception on program
# startup (to console), and occasional status messages (to console)
# on if the log4j system has managed to connect to the specified
# socket..
log4j.appender.socketLogger=org.apache.log4j.net.SocketAppender
log4j.appender.socketLogger.RemoteHost=localhost
log4j.appender.socketLogger.Port=4445
log4j.appender.socketLogger.LocationInfo=false
# END APPENDER: SOCKET APPENDER (socketLogger)

# BEGIN APPENDER: LogFactor5 APPENDER (lf5)
# LogFactor5 is a Swing window that directly receives logging messages and
# displays them. It offers filtering, searching etc. similar to Chainsaw or
# Lumbermill but you don't have to use a socket appender so it should be faster
# when the logging display is on the same machine as the program issuing
# messages.
log4j.appender.lf5=org.apache.log4j.lf5.LF5Appender
log4j.appender.lf5.MaxNumberOfRecords=1000
# END APPENDER: LogFactor5 APPENDER (lf5)

# BEGIN APPENDER: XML APPENDER (xml)
# A standard file appender where we have put an XML layout onto the output
# event records. A file put out using this technique can be loaded after
# the fact into Chainsaw for viewing, filtering, searching, etc.
log4j.appender.xml=org.apache.log4j.FileAppender
log4j.appender.xml.file=example_xml.log
log4j.appender.xml.append=false
log4j.appender.xml.layout=org.apache.log4j.xml.XMLLayout
# END APPENDER: XML APPENDER (xml)

# BEGIN APPENDER: LogFactor5 Rolling APPENDER (lf5Rolling)
# Like the XML appender above, this is a specialized format designed to be read
# from a tool. In this case LogFactor5 can load up files in this format for
# after the fact review.
log4j.appender.lf5Rolling=org.apache.log4j.RollingFileAppender
log4j.appender.lf5Rolling.File=example_lf5.log
log4j.appender.lf5Rolling.layout=org.apache.log4j.PatternLayout

log4j.appender.lf5Rolling.layout.ConversionPattern=[slf5s.start]%d{DATE}[slf5s.DATE]%n
%p[slf5s.PRIORITY]%n%x[slf5s.NDC]%n%t[slf5s.THREAD]%n%c[slf5s.CATEGORY]%n
%l[slf5s.LOCATION]%n%m[slf5s.MESSAGE]%n%n
# END APPENDER: LogFactor5 Rolling APPENDER (lf5Rolling)

ref
========================================


# Set root logger level to (ALL, DEBUG, INFO, WARN, ERROR, FATAL).
#log4j.rootCategory=INFO, CONSOLE
#log4j.rootCategory=INFO, CONSOLE, LOGFILE
#log4j.rootCategory=INFO, CONSOLE, LOGFILE, adminLogger
log4j.rootCategory=ALL, CONSOLE, LOGFILE


# -----------------------------
# Setup category logger
# -----------------------------
#log4j.category.com.cv.tibs=ERROR, adminLogger
#log4j.category.com.cv.tibs.enquiry=DEBUG, CONSOLE, LOGFILE, adminLogger
#log4j.category.com.cv.tibs.service.util.TIBSFilter=DEBUG, CONSOLE, LOGFILE, adminLogger
#log4j.category.com.cv.tibs.service.internal=ERROR, adminLogger
#log4j.category.com.cv.tibs.service.internal.util=ERROR, adminLogger
#log4j.category.com.cv.tibs.service.internal.UserEnquiry=ERROR, adminLogger

#log4j.additivity.com.cv.tibs=false


# -----------------------------
# Set the enterprise logger priority to FATAL
# -----------------------------
log4j.logger.org.apache.axis2.enterprise=INFO
log4j.logger.de.hunsicker.jalopy.io=INFO
log4j.logger.httpclient.wire.header=INFO
log4j.logger.org.apache.commons.httpclient=INFO

#log4j.logger.com.cv.tibs=DEBUG
#log4j.logger.com.cv.tibs.service.internal.UserEnquiry=ERROR
#log4j.logger.com.cv.tibs.service.internal=ERROR
#log4j.logger.com.cv.tibs.service.internal.util=ERROR


# -----------------------------
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
# -----------------------------
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
#log4j.appender.CONSOLE.layout.ConversionPattern=[%p] %m%n
log4j.appender.CONSOLE.layout.ConversionPattern =[%d{yyyy-MM-dd HH:mm:ss,SSS}] | [%t] | %-5p | %c | %m | %n


# -----------------------------
# LOGFILE is set to be a File appender using a PatternLayout.
# -----------------------------
log4j.appender.LOGFILE=org.apache.log4j.RollingFileAppender
#log4j.appender.LOGFILE.File=axis2.log
log4j.appender.LOGFILE.File=C:\\clicks\\wsear\\axis2.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
#log4j.appender.LOGFILE.layout.ConversionPattern=%d [%t] %-5p %c %x - %m%n
log4j.appender.LOGFILE.layout.ConversionPattern =[%d{yyyy-MM-dd HH:mm:ss,SSS}] | [%t] | %-5p | %c | %m | %n
# Keep 100 old files around.
log4j.appender.LOGFILE.MaxBackupIndex=10
log4j.appender.LOGFILE.MaxFileSize=10240KB

# -----------------------------
# TIBSWS wsAppender
# -----------------------------
# wsLogger is set to be a FileAppender.
log4j.logger.com.cv.tibs.chequemanagement=DEBUG, wsLogger
log4j.logger.com.cv.tibs.enquiry=DEBUG, wsLogger
log4j.logger.com.cv.tibs.favaccountmanagement=DEBUG, wsLogger
log4j.logger.com.cv.tibs.onetimeownft=DEBUG, wsLogger
log4j.logger.com.cv.tibs.remittance=DEBUG, wsLogger
log4j.logger.com.cv.tibs.security=DEBUG, wsLogger
log4j.logger.com.cv.tibs.transaction=DEBUG, wsLogger
log4j.logger.com.cv.tibs.usermanagement=DEBUG, wsLogger
log4j.logger.com.cv.tibs.service.util.TIBSFilter=DEBUG, wsLogger
log4j.appender.wsLogger=org.apache.log4j.RollingFileAppender
log4j.appender.wsLogger.File=C:\\clicks\\wsear\\io.log
log4j.appender.wsLogger.layout=org.apache.log4j.PatternLayout

# Keep 100 old files around.
log4j.appender.wsLogger.MaxBackupIndex=100
log4j.appender.wsLogger.MaxFileSize=10240KB

# Format almost same as WebSphere's common log format.
log4j.appender.wsLogger.layout.ConversionPattern =[%d{yyyy-MM-dd HH:mm:ss,SSS}] %-5p %c %x - %m %n