|
| 1 | +# Categories |
| 2 | +Categories are groups of log events. The category for log events is defined when you get a _Logger_ from log4js (`log4js.getLogger('somecategory')`). Log events with the same _category_ will go to the same _appenders_. |
| 3 | + |
| 4 | +## Default configuration |
| 5 | +When defining your appenders through a configuration, at least one category must be defined. |
| 6 | + |
| 7 | +```javascript |
| 8 | +const log4js = require('log4js'); |
| 9 | +log4js.configure({ |
| 10 | + appenders: { |
| 11 | + out: { type: 'stdout' }, |
| 12 | + app: { type: 'file', filename: 'application.log' } |
| 13 | + }, |
| 14 | + categories: { |
| 15 | + default: { appenders: [ 'out' ], level: 'trace' }, |
| 16 | + app: { appenders: ['app'], level: 'trace' } |
| 17 | + } |
| 18 | +}); |
| 19 | + |
| 20 | +const logger = log4js.getLogger(); |
| 21 | +logger.trace('This will use the default category and go to stdout'); |
| 22 | +const logToFile = log4js.getLogger('app'); |
| 23 | +logToFile.trace('This will go to a file'); |
| 24 | +``` |
| 25 | + |
| 26 | +## Categories inheritance |
| 27 | +Log4js supports a hierarchy for categories, using dots to separate layers - for example, log events in the category 'myapp.submodule' will use the level for 'myapp' if none is defined for 'myapp.submodule', and also any appenders defined for 'myapp'. |
| 28 | +This behaviour can be disabled by setting inherit=false on the sub-category. |
| 29 | + |
| 30 | +```javascript |
| 31 | +const log4js = require('log4js'); |
| 32 | +log4js.configure({ |
| 33 | + appenders: { |
| 34 | + console: { type: 'console' }, |
| 35 | + app: { type: 'file', filename: 'application.log' } |
| 36 | + }, |
| 37 | + categories: { |
| 38 | + default: { appenders: [ 'console' ], level: 'trace' }, |
| 39 | + catA: { appenders: ['console'], level: 'error' }, |
| 40 | + 'catA.catB': { appenders: ['app'], level: 'trace' }, |
| 41 | + } |
| 42 | +}); |
| 43 | + |
| 44 | +const loggerA = log4js.getLogger('catA'); |
| 45 | +loggerA.error('This will be written to console with log level ERROR'); |
| 46 | +loggerA.trace('This will not be written'); |
| 47 | +const loggerAB = log4js.getLogger('catA.catB'); |
| 48 | +loggerAB.error('This will be written with log level ERROR to console and to a file'); |
| 49 | +loggerAB.trace('This will be written with log level TRACE to console and to a file'); |
| 50 | +``` |
| 51 | +Two categories are defined: |
| 52 | +- Log events with category 'catA' will go to appender 'console' only. |
| 53 | +- Log events with category 'catA.catB' will go to appenders 'console' and 'app'. |
| 54 | + |
| 55 | +Appenders will see and log an event only if the category level is less than or equal to the event's level. |
0 commit comments