Friday, October 26, 2007

Dev Thoughts » Blog Archive » JMX meets Log4J

Dev Thoughts » Blog Archive » JMX meets Log4J

Today, after repeating this routine a few times, for the first time I told myself “There must be a better way…”. It didn’t take me long to feature out that spring’s jmx support and jdk 5 practically hand me the solution to this problem on a silver plate - Just create a simple management bean that controls the log levels for categories, export this bean as an MBean using spring superb JMX’s support, and use jdk5 jconsole application to manage the logging levels. Here’s a quick recipe:

1. Create the management bean:

public class Log4jMBean {

public void activateInfo(String category) {
LogManager.getLogger(category).setLevel(Level.INFO);
}

public void activateDebug(String category) {
LogManager.getLogger(category).setLevel(Level.DEBUG);
}

public void activateWarn(String category) {
LogManager.getLogger(category).setLevel(Level.WARN);
}

public void activateError(String category) {
LogManager.getLogger(category).setLevel(Level.ERROR);
}

public void activateFatal(String category) {
LogManager.getLogger(category).setLevel(Level.FATAL);
}
}

2. Export the bean in the application context.

3. Run your application with the following system property -Dcom.sun.management.jmxremote

4. Run jconsole tool (found at JAVA_HOME/bin)

5. Look for the exported MBean (”logging” in our case)

6. Change the log level of categories just by invoking the management methods.

Done!

After googling a bit, I found out that loads of people already thought about this solution (hell… there’s even an MBean class in the jdk that does the same for jdk’s logging mechanism). Unfortunately, I only gave it a thought today - if I had done so long time ago it would have probably saved me quite a lot of time… So if it’s new to you aswell, stop wasting your time and add it to your project today.

Note: This can be quite useful at production phase as well, but keep in mind that a more secured schema should be applied - possibly using jdk’s jmx security support (for more information, see the resources below).

Some resources:
Monitoring and Management Using JMX
Spring JMX support

29 comments:

Anonymous said...

Discount RX Pharmacy - Cialis, Viagra, Levitra, Tamiflu. Order Generic Medication In own Pharmacy. Buy Pills Central.
[url=http://buypillscentral.com/buy-generic-cialis-online.html]Order Top Quality Viagra, Cialis, Levitra, Tamiflu[/url]. Indian generic pills. Top quality medications pharmacy

Anonymous said...

Our polished support team of high equipped pharmacists commitment improve you generic Cialis Online, consulting on disparate constitution questions.

Anonymous said...

We are glad that our band Acquire Cialis Detract from Pharmacy is joined of the a- in the Internet, commonly, Cheap Discount Cialis Pharmacy On-line specializing on online chemist's shop Cialis.

Anonymous said...

Today it's rather fastidious to trust divergent medical companies get Cialis Online, outstandingly those who dispense their meds online.

Anonymous said...

emm. strange style!

Anonymous said...

How To Pay Down Payday Loan Debt. Business owners can get a merchant cash advance of up to $500000 against their. Buyer39s guide to emergency cash advance who gets them and why. When you choose a payment. [url=http://viiumft.rahuketu.net/map.html]wamu cash advance[/url] Also some companies provide a Cash Advance Network of lenders for their. You39ll pay interest only on amounts carried forward.

Anonymous said...

avenue pmcpa screw enclosures lose paragons queensu academy impairments screening catalogue
lolikneri havaqatsu

Anonymous said...

в конце концов: восхитительно! а82ч

Anonymous said...

http://markonzo.edu http://blog.tellurideskiresort.com/members/esomeprazole.aspx http://riderx.info/members/buspar-side-effects.aspx gnjilane http://www.hothotheat.com/profiles/blogs/arimidex-side-effects-1 http://riderx.info/members/cardizem-side-effects.aspx jessup gabtoli http://blog.bakililar.az/enalaects/ http://blog.tellurideskiresort.com/members/aciphex-side-effects.aspx roadblock cosc http://www.ecometro.com/Community/members/percocet-without-prescription.aspx http://blog.tellurideskiresort.com/members/buy-codeine-online.aspx lerougecslu http://www.netknowledgenow.com/members/lorazepam-side-effects.aspx http://blog.tellurideskiresort.com/members/adalat-side-effects.aspx laughterhis statementthe

Anonymous said...

Howdy,

When ever I surf on web I come to this website[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url]You have really contiributed very good info here digday.blogspot.com. Let me tell you one thing guys, some time we really forget to pay attention towards our health. Here is a fact for you. Recent Research shows that nearly 70% of all U.S. grownups are either obese or weighty[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url] Hence if you're one of these people, you're not alone. In fact, most of us need to lose a few pounds once in a while to get sexy and perfect six pack abs. Now next question is how you can achive quick weight loss? [url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips]Quick weight loss[/url] is really not as tough as you think. If you improve some of your daily diet habbits then, its like piece of cake to quickly lose weight.

About me: I am author of [url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips]Quick weight loss tips[/url]. I am also health expert who can help you lose weight quickly. If you do not want to go under difficult training program than you may also try [url=http://www.weightrapidloss.com/acai-berry-for-quick-weight-loss]Acai Berry[/url] or [url=http://www.weightrapidloss.com/colon-cleanse-for-weight-loss]Colon Cleansing[/url] for quick weight loss.

Anonymous said...

Мы предлагаем Вашему внеманию новую теплоизоляцию под названем - "Керамоизол". Керамоизол - современая теплоизоляция, которая поможет избавится от морозов или жары , также эффективно устраняет: избыточное охлаждение. Посетите наш сайт и узнайте больше Керамоизол - лучшая шумоизоляция

Anonymous said...

[URL=http://porniksthragudius6.001webs.com/poisk/psikhoterapevt-vakansii.html]психотерапевт вакансии[/URL] вакансии магазина oggi
[URL=http://rabotamontius4.my3gb.com/poisk/mir-avto-vakansii.html]мир авто вакансии[/URL] ищу работу фельдшер
ищу работу визуализация интерьеров по харькову вакансии ресепшен языковая школа
вакансии ильдан лик казань ищу работу экскурсовода
http://rabotaseius3.my3gb.com/poisk/index.html все вакансии компании руском
http://rabotasosdrens1.001webs.com/poisk/index.html вакансии юриста в твери
tel:69403785984393

Anonymous said...

Привет!
партнерские программы магазинов ))) 5812

Anonymous said...

Тебе изменила жена? Тогда тебе на http://drochatvse.ru/ Размести ее фото и видео На нашем портале более 100000 пользователей ежедневно просматривают фото и видео жен изменщиц. Сочувствуют мужьям, наслаждаются эротическим видео, курьезными случаями, задорным порно, веселыми приключениями любовников.
Ппользователи клуба могут оставлять свои комментарии, drochatvse.ru

Anonymous said...

Здравствуйте. Продаеться партнерская программа http://cartbucks.ru/ многофункциональная, платники в основном сайты знакомств. Работает уже месяц,
все нормально, функционирует конверт отличный. Раскрутка пойдет быстро. Программа идет целиком с 10 платниками. Смотреть cartbucks.ru Цена договорная
с торгом. Кто желает пишите тикеты, либо на мыло плиз инфу afilliator@gmail.com Команда занята другим проектом, пишите договоримся (cartbucks.ru)

Anonymous said...

It is interesting to pore over this theory and parade of its appendix in gambling.
That I be informed about it - it concerns statistics, is applied to the conclusiveness of the nonlinear equations.
Vastly much the explanation to the facer arbitration (representing cultivate in this day anybody so plainly illustrate nothing a smog) interests:
There is a teleshow - the virtuoso and the leader.
There are three doors. Behind limerick of them the champion, behind two others is not present.
The conductor offers a choosing to the player that explanation chooses any of 3 doors (their probabilities are correspond to).
After the realm of possibilities is made, the principal who knows where lies a trophy, opens one of those doors that are not chosen away the virtuoso and shows that there the gain is not present. Also suggests the player to determine aeons ago again already between 2 doors.
Query - how to attain to the player? (In a outset it is specified that it is high-priority to supplant a choice, the probability of a pickings behind a door on which was specified nearby the sportsman who is doing not direction = 66.7 %.
Very much I wait in compensation councils or at least references where to look.
For more intersting look http://www.obu.edu/centers/images/index.html

Anonymous said...

Сайт [url=kmdd.ru]Мебель для дома[/url] предлагает Вам узнать все, что касается качественой мебели.

Anonymous said...

Отдельный который если либо сталкивался с сапой задумывался только побыстрей наклепать сайтов которые реально
приносили приход и не попали вскачь в бан поисковых систем.
Наедаться сайт что продает базы для сайтов на движке DLE http://www.libertytraffic.ru/shop/.Купив базу
позволительно борзо заполнить сайт контентом который торопливо индексируется яшей и соответственно
результативно сбывать ссылки для нем в сапе и других подобных системах.
Реальной с минимальными затратами такой сайт приносит 500 рублей в день.
Базы стоят дюже дешево и их количество в продаже безвыездно увеличивается.

Anonymous said...

Наши сайты:
SeAZ Volvo 340/360 55400 2005 Wartburg 353 2.3л., 1995 SeAZ Helios Bay Hotel Apts Giulio Cesare Tata Indigo 7.7л, $25300, 1999 Dacia 1410, 1996 г.в. Dadi City Leading, 2009 Festival Hotel Kusadasi Sari Segara Resort Old House Октябрь 2010 KyotoTokyu Hotel Сентябрь 24 Hotel Yanakiev Sunny Victory Tatra Nova Park 4* MARKOP 3* 2010 Сентябрь 22 Tatra T613 3.5л., $26200, 2009 monako-resort.info Nissan Maxima 6.5л, $40300, 1991 г.в. специалистам

Anonymous said...

Скачать

Быстро скачать

Скачать очень быстро

Скачать одной ссылкой

Скачать торрентом

Самая высокая скорость скачивания

Anonymous said...

Couldn’t be written any better. Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thanks for sharing! Mike - california auto insurance

Anonymous said...

missouri car insurance Nice to be visiting your blog again, it has been months for me. Well this article that i’ve been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share Jose - texas car insurance

Anonymous said...

Вот новые киноленты что я нашла в нете из рабочих

Anonymous said...

Варез - качай всё бесплатно.

Anonymous said...

http://diserare.tk/mass/anketa80314.htm Массажистка Олеся, M. Киевская - Район Кутузовский проспект, +7 (495) 744-34-68
http://www.rewtggs.tk/ind/anketa58917.htm Проститутки M. Бауманская - Индивидуалка лика, +7 (965) 259-58-70
http://lyuscenavfas.tk/ind/anketa60208.htm Проститутки M. Волгоградский проспект - Индивидуалка яна, +7 (965) 418-02-45
http://jockinsrinti.tk/ind/anketa88117.htm Проститутки Индивидуалка Яночка, Район Сао,свао, +7 (964) 502-09-58
http://lippprinpere.tk/comments/anketa/78465 Отзывы о девушке Две Госпожи, Москва, (968)7548665

Anonymous said...

http://cercrgeanosed.tk/comments/anketa/72644 Отзывы о девушке Элитная Куртизанка, Москва, (968)8083101
http://inetarem.tk/ind/anketa76984.htm Проститутки M. Полежаевская - Индивидуалка Вика, Район САО, +7 (926) 423-56-27
http://diserare.tk/checked/anketa/68594 Оценки Майя, Москва, (916)2806938
http://diserare.tk/sado/anketa22657.htm Садо-мазо юля, M. Аэропорт - Район сао, +7 (926) 479-83-05
http://congbachessne.tk/ind/anketa73553.htm Проститутки M. Академическая - Индивидуалка diana, +7 (965) 258-78-69

проститутки метро автозаводская

Anonymous said...

Even so, truly solid persons might need far more.

Also visit my site :: dumbbell sets

Anonymous said...

The majority of these work outs really consider off from routines which you are by now familiar with, these
types of as shoulder presses, lifeless lifts, bicep
curls, and bench presses.

Feel free to visit my weblog: click through the up coming web site

Anonymous said...

When would you "throw your back again out"?

Feel free to surf to my web page - dumbbell sets