{
    "mode": "perldoc",
    "parameter": "Log::Log4perl",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Log%3A%3ALog4perl/json",
    "generated": "2026-06-09T19:04:41Z",
    "synopsis": "# Easy mode if you like it simple ...\nuse Log::Log4perl qw(:easy);\nLog::Log4perl->easyinit($ERROR);\nDEBUG \"This doesn't go anywhere\";\nERROR \"This gets logged\";\n# ... or standard mode for more features:\nLog::Log4perl::init('/etc/log4perl.conf');",
    "sections": {
        "NAME": {
            "content": "Log::Log4perl - Log4j implementation for Perl\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "# Easy mode if you like it simple ...\n\nuse Log::Log4perl qw(:easy);\nLog::Log4perl->easyinit($ERROR);\n\nDEBUG \"This doesn't go anywhere\";\nERROR \"This gets logged\";\n\n# ... or standard mode for more features:\n\nLog::Log4perl::init('/etc/log4perl.conf');\n",
            "subsections": [
                {
                    "name": "--or--",
                    "content": "# Check config every 10 secs\nLog::Log4perl::initandwatch('/etc/log4perl.conf',10);\n",
                    "long": "--or--"
                },
                {
                    "name": "--then--",
                    "content": "$logger = Log::Log4perl->getlogger('house.bedrm.desk.topdrwr');\n\n$logger->debug('this is a debug message');\n$logger->info('this is an info message');\n$logger->warn('etc');\n$logger->error('..');\n$logger->fatal('..');\n\n#####/etc/log4perl.conf###############################\nlog4perl.logger.house              = WARN,  FileAppndr1\nlog4perl.logger.house.bedroom.desk = DEBUG, FileAppndr1\n\nlog4perl.appender.FileAppndr1      = Log::Log4perl::Appender::File\nlog4perl.appender.FileAppndr1.filename = desk.log\nlog4perl.appender.FileAppndr1.layout   = \\\nLog::Log4perl::Layout::SimpleLayout\n######################################################\n",
                    "long": "--then--"
                }
            ]
        },
        "ABSTRACT": {
            "content": "Log::Log4perl provides a powerful logging API for your application\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "Log::Log4perl lets you remote-control and fine-tune the logging behaviour of your system from\nthe outside. It implements the widely popular (Java-based) Log4j logging package in pure Perl.\n\nFor a detailed tutorial on Log::Log4perl usage, please read\n\n<http://www.perl.com/pub/a/2002/09/11/log4perl.html>\n\nLogging beats a debugger if you want to know what's going on in your code during runtime.\nHowever, traditional logging packages are too static and generate a flood of log messages in\nyour log files that won't help you.\n\n\"Log::Log4perl\" is different. It allows you to control the number of logging messages generated\nat three different levels:\n\n*   At a central location in your system (either in a configuration file or in the startup code)\nyou specify *which components* (classes, functions) of your system should generate logs.\n\n*   You specify how detailed the logging of these components should be by specifying logging\n*levels*.\n\n*   You also specify which so-called *appenders* you want to feed your log messages to (\"Print\nit to the screen and also append it to /tmp/my.log\") and which format (\"Write the date\nfirst, then the file name and line number, and then the log message\") they should be in.\n\nThis is a very powerful and flexible mechanism. You can turn on and off your logs at any time,\nspecify the level of detail and make that dependent on the subsystem that's currently executed.\n\nLet me give you an example: You might find out that your system has a problem in the\n\"MySystem::Helpers::ScanDir\" component. Turning on detailed debugging logs all over the system\nwould generate a flood of useless log messages and bog your system down beyond recognition. With\n\"Log::Log4perl\", however, you can tell the system: \"Continue to log only severe errors to the\nlog file. Open a second log file, turn on full debug logs in the \"MySystem::Helpers::ScanDir\"\ncomponent and dump all messages originating from there into the new log file\". And all this is\npossible by just changing the parameters in a configuration file, which your system can re-read\neven while it's running!\n\nHow to use it\nThe \"Log::Log4perl\" package can be initialized in two ways: Either via Perl commands or via a\n\"log4j\"-style configuration file.\n",
            "subsections": [
                {
                    "name": "Initialize via a configuration file",
                    "content": "This is the easiest way to prepare your system for using \"Log::Log4perl\". Use a configuration\nfile like this:\n\n############################################################\n# A simple root logger with a Log::Log4perl::Appender::File\n# file appender in Perl.\n############################################################\nlog4perl.rootLogger=ERROR, LOGFILE\n\nlog4perl.appender.LOGFILE=Log::Log4perl::Appender::File\nlog4perl.appender.LOGFILE.filename=/var/log/myerrs.log\nlog4perl.appender.LOGFILE.mode=append\n\nlog4perl.appender.LOGFILE.layout=PatternLayout\nlog4perl.appender.LOGFILE.layout.ConversionPattern=[%r] %F %L %c - %m%n\n\nThese lines define your standard logger that's appending severe errors to \"/var/log/myerrs.log\",\nusing the format\n\n[millisecs] source-filename line-number class - message newline\n\nAssuming that this configuration file is saved as \"log.conf\", you need to read it in the startup\nsection of your code, using the following commands:\n\nuse Log::Log4perl;\nLog::Log4perl->init(\"log.conf\");\n\nAfter that's done *somewhere* in the code, you can retrieve logger objects *anywhere* in the\ncode. Note that there's no need to carry any logger references around with your functions and\nmethods. You can get a logger anytime via a singleton mechanism:\n\npackage My::MegaPackage;\nuse  Log::Log4perl;\n\nsub somemethod {\nmy($param) = @;\n\nmy $log = Log::Log4perl->getlogger(\"My::MegaPackage\");\n\n$log->debug(\"Debug message\");\n$log->info(\"Info message\");\n$log->error(\"Error message\");\n\n...\n}\n\nWith the configuration file above, \"Log::Log4perl\" will write \"Error message\" to the specified\nlog file, but won't do anything for the \"debug()\" and \"info()\" calls, because the log level has\nbeen set to \"ERROR\" for all components in the first line of configuration file shown above.\n\nWhy \"Log::Log4perl->getlogger\" and not \"Log::Log4perl->new\"? We don't want to create a new\nobject every time. Usually in OO-Programming, you create an object once and use the reference to\nit to call its methods. However, this requires that you pass around the object to all functions\nand the last thing we want is pollute each and every function/method we're using with a handle\nto the \"Logger\":\n\nsub function {  # Brrrr!!\nmy($logger, $some, $other, $parameters) = @;\n}\n\nInstead, if a function/method wants a reference to the logger, it just calls the Logger's static\n\"getlogger($category)\" method to obtain a reference to the *one and only* possible logger\nobject of a certain category. That's called a *singleton* if you're a Gamma fan.\n\nHow does the logger know which messages it is supposed to log and which ones to suppress?\n\"Log::Log4perl\" works with inheritance: The config file above didn't specify anything about\n\"My::MegaPackage\". And yet, we've defined a logger of the category \"My::MegaPackage\". In this\ncase, \"Log::Log4perl\" will walk up the namespace hierarchy (\"My\" and then we're at the root) to\nfigure out if a log level is defined somewhere. In the case above, the log level at the root\n(root *always* defines a log level, but not necessarily an appender) defines that the log level\nis supposed to be \"ERROR\" -- meaning that *DEBUG* and *INFO* messages are suppressed. Note that\nthis 'inheritance' is unrelated to Perl's class inheritance, it is merely related to the logger\nnamespace. By the way, if you're ever in doubt about what a logger's category is, use\n\"$logger->category()\" to retrieve it.\n"
                },
                {
                    "name": "Log Levels",
                    "content": "There are six predefined log levels: \"FATAL\", \"ERROR\", \"WARN\", \"INFO\", \"DEBUG\", and \"TRACE\" (in\ndescending priority). Your configured logging level has to at least match the priority of the\nlogging message.\n\nIf your configured logging level is \"WARN\", then messages logged with \"info()\", \"debug()\", and\n\"trace()\" will be suppressed. \"fatal()\", \"error()\" and \"warn()\" will make their way through,\nbecause their priority is higher or equal than the configured setting.\n\nInstead of calling the methods\n\n$logger->trace(\"...\");  # Log a trace message\n$logger->debug(\"...\");  # Log a debug message\n$logger->info(\"...\");   # Log a info message\n$logger->warn(\"...\");   # Log a warn message\n$logger->error(\"...\");  # Log a error message\n$logger->fatal(\"...\");  # Log a fatal message\n\nyou could also call the \"log()\" method with the appropriate level using the constants defined in\n\"Log::Log4perl::Level\":\n\nuse Log::Log4perl::Level;\n\n$logger->log($TRACE, \"...\");\n$logger->log($DEBUG, \"...\");\n$logger->log($INFO, \"...\");\n$logger->log($WARN, \"...\");\n$logger->log($ERROR, \"...\");\n$logger->log($FATAL, \"...\");\n\nThis form is rarely used, but it comes in handy if you want to log at different levels depending\non an exit code of a function:\n\n$logger->log( $exitlevel{ $rc }, \"...\");\n\nAs for needing more logging levels than these predefined ones: It's usually best to steer your\nlogging behaviour via the category mechanism instead.\n\nIf you need to find out if the currently configured logging level would allow a logger's logging\nstatement to go through, use the logger's \"is*level*()\" methods:\n\n$logger->istrace()    # True if trace messages would go through\n$logger->isdebug()    # True if debug messages would go through\n$logger->isinfo()     # True if info messages would go through\n$logger->iswarn()     # True if warn messages would go through\n$logger->iserror()    # True if error messages would go through\n$logger->isfatal()    # True if fatal messages would go through\n\nExample: \"$logger->iswarn()\" returns true if the logger's current level, as derived from either\nthe logger's category (or, in absence of that, one of the logger's parent's level setting) is\n$WARN, $ERROR or $FATAL.\n\nAlso available are a series of more Java-esque functions which return the same values. These are\nof the format \"is*Level*Enabled()\", so \"$logger->isDebugEnabled()\" is synonymous to\n\"$logger->isdebug()\".\n\nThese level checking functions will come in handy later, when we want to block unnecessary\nexpensive parameter construction in case the logging level is too low to log the statement\nanyway, like in:\n\nif($logger->iserror()) {\n$logger->error(\"Erroneous array: @superlongarray\");\n}\n\nIf we had just written\n\n$logger->error(\"Erroneous array: @superlongarray\");\n\nthen Perl would have interpolated @superlongarray into the string via an expensive operation\nonly to figure out shortly after that the string can be ignored entirely because the configured\nlogging level is lower than $ERROR.\n\nThe to-be-logged message passed to all of the functions described above can consist of an\narbitrary number of arguments, which the logging functions just chain together to a single\nstring. Therefore\n\n$logger->debug(\"Hello \", \"World\", \"!\");  # and\n$logger->debug(\"Hello World!\");\n\nare identical.\n\nNote that even if one of the methods above returns true, it doesn't necessarily mean that the\nmessage will actually get logged. What isdebug() checks is that the logger used is configured\nto let a message of the given priority (DEBUG) through. But after this check, Log4perl will\neventually apply custom filters and forward the message to one or more appenders. None of this\ngets checked by isxxx(), for the simple reason that it's impossible to know what a custom\nfilter does with a message without having the actual message or what an appender does to a\nmessage without actually having it log it.\n"
                },
                {
                    "name": "Log and die or warn",
                    "content": "Often, when you croak / carp / warn / die, you want to log those messages. Rather than doing the\nfollowing:\n\n$logger->fatal($err) && die($err);\n\nyou can use the following:\n\n$logger->logdie($err);\n\nAnd if instead of using\n\nwarn($message);\n$logger->warn($message);\n\nto both issue a warning via Perl's warn() mechanism and make sure you have the same message in\nthe log file as well, use:\n\n$logger->logwarn($message);\n\nSince there is an ERROR level between WARN and FATAL, there are two additional helper functions\nin case you'd like to use ERROR for either warn() or die():\n\n$logger->errorwarn();\n$logger->errordie();\n\nFinally, there's the Carp functions that, in addition to logging, also pass the stringified\nmessage to their companions in the Carp package:\n\n$logger->logcarp();        # warn w/ 1-level stack trace\n$logger->logcluck();       # warn w/ full stack trace\n$logger->logcroak();       # die w/ 1-level stack trace\n$logger->logconfess();     # die w/ full stack trace\n"
                },
                {
                    "name": "Appenders",
                    "content": "If you don't define any appenders, nothing will happen. Appenders will be triggered whenever the\nconfigured logging level requires a message to be logged and not suppressed.\n\n\"Log::Log4perl\" doesn't define any appenders by default, not even the root logger has one.\n\n\"Log::Log4perl\" already comes with a standard set of appenders:\n\nLog::Log4perl::Appender::Screen\nLog::Log4perl::Appender::ScreenColoredLevels\nLog::Log4perl::Appender::File\nLog::Log4perl::Appender::Socket\nLog::Log4perl::Appender::DBI\nLog::Log4perl::Appender::Synchronized\nLog::Log4perl::Appender::RRDs\n\nto log to the screen, to files and to databases.\n\nOn CPAN, you can find additional appenders like\n\nLog::Log4perl::Layout::XMLLayout\n\nby Guido Carls <gcarls@cpan.org>. It allows for hooking up Log::Log4perl with the graphical Log\nAnalyzer Chainsaw (see \"Can I use Log::Log4perl with log4j's Chainsaw?\" in Log::Log4perl::FAQ).\n"
                },
                {
                    "name": "Additional Appenders via Log::Dispatch",
                    "content": "\"Log::Log4perl\" also supports *Dave Rolskys* excellent \"Log::Dispatch\" framework which\nimplements a wide variety of different appenders.\n\nHere's the list of appender modules currently available via \"Log::Dispatch\":\n\nLog::Dispatch::ApacheLog\nLog::Dispatch::DBI (by Tatsuhiko Miyagawa)\nLog::Dispatch::Email,\nLog::Dispatch::Email::MailSend,\nLog::Dispatch::Email::MailSendmail,\nLog::Dispatch::Email::MIMELite\nLog::Dispatch::File\nLog::Dispatch::FileRotate (by Mark Pfeiffer)\nLog::Dispatch::Handle\nLog::Dispatch::Screen\nLog::Dispatch::Syslog\nLog::Dispatch::Tk (by Dominique Dumont)\n\nPlease note that in order to use any of these additional appenders, you have to fetch\nLog::Dispatch from CPAN and install it. Also the particular appender you're using might require\ninstalling the particular module.\n\nFor additional information on appenders, please check the Log::Log4perl::Appender manual page.\n"
                },
                {
                    "name": "Appender Example",
                    "content": "Now let's assume that we want to log \"info()\" or higher prioritized messages in the \"Foo::Bar\"\ncategory to both STDOUT and to a log file, say \"test.log\". In the initialization section of your\nsystem, just define two appenders using the readily available \"Log::Log4perl::Appender::File\"\nand \"Log::Log4perl::Appender::Screen\" modules:\n\nuse Log::Log4perl;\n\n# Configuration in a string ...\nmy $conf = q(\nlog4perl.category.Foo.Bar          = INFO, Logfile, Screen\n\nlog4perl.appender.Logfile          = Log::Log4perl::Appender::File\nlog4perl.appender.Logfile.filename = test.log\nlog4perl.appender.Logfile.layout   = Log::Log4perl::Layout::PatternLayout\nlog4perl.appender.Logfile.layout.ConversionPattern = [%r] %F %L %m%n\n\nlog4perl.appender.Screen         = Log::Log4perl::Appender::Screen\nlog4perl.appender.Screen.stderr  = 0\nlog4perl.appender.Screen.layout = Log::Log4perl::Layout::SimpleLayout\n);\n\n# ... passed as a reference to init()\nLog::Log4perl::init( \\$conf );\n\nOnce the initialization shown above has happened once, typically in the startup code of your\nsystem, just use the defined logger anywhere in your system:\n\n##########################\n# ... in some function ...\n##########################\nmy $log = Log::Log4perl::getlogger(\"Foo::Bar\");\n\n# Logs both to STDOUT and to the file test.log\n$log->info(\"Important Info!\");\n\nThe \"layout\" settings specified in the configuration section define the format in which the\nmessage is going to be logged by the specified appender. The format shown for the file appender\nis logging not only the message but also the number of milliseconds since the program has\nstarted (%r), the name of the file the call to the logger has happened and the line number there\n(%F and %L), the message itself (%m) and a OS-specific newline character (%n):\n\n[187] ./myscript.pl 27 Important Info!\n\nThe screen appender above, on the other hand, uses a \"SimpleLayout\", which logs the debug level,\na hyphen (-) and the log message:\n\nINFO - Important Info!\n\nFor more detailed info on layout formats, see \"Log Layouts\".\n\nIn the configuration sample above, we chose to define a *category* logger (\"Foo::Bar\"). This\nwill cause only messages originating from this specific category logger to be logged in the\ndefined format and locations.\n"
                },
                {
                    "name": "Logging newlines",
                    "content": "There's some controversy between different logging systems as to when and where newlines are\nsupposed to be added to logged messages.\n\nThe Log4perl way is that a logging statement *should not* contain a newline:\n\n$logger->info(\"Some message\");\n$logger->info(\"Another message\");\n\nIf this is supposed to end up in a log file like\n\nSome message\nAnother message\n\nthen an appropriate appender layout like \"%m%n\" will take care of adding a newline at the end of\neach message to make sure every message is printed on its own line.\n\nOther logging systems, Log::Dispatch in particular, recommend adding the newline to the log\nstatement. This doesn't work well, however, if you, say, replace your file appender by a\ndatabase appender, and all of a sudden those newlines scattered around the code don't make sense\nanymore.\n\nAssigning matching layouts to different appenders and leaving newlines out of the code solves\nthis problem. If you inherited code that has logging statements with newlines and want to make\nit work with Log4perl, read the Log::Log4perl::Layout::PatternLayout documentation on how to\naccomplish that.\n"
                },
                {
                    "name": "Configuration files",
                    "content": "As shown above, you can define \"Log::Log4perl\" loggers both from within your Perl code or from\nconfiguration files. The latter have the unbeatable advantage that you can modify your system's\nlogging behaviour without interfering with the code at all. So even if your code is being run by\nsomebody who's totally oblivious to Perl, they still can adapt the module's logging behaviour to\ntheir needs.\n\n\"Log::Log4perl\" has been designed to understand \"Log4j\" configuration files -- as used by the\noriginal Java implementation. Instead of reiterating the format description in [2], let me just\nlist three examples (also derived from [2]), which should also illustrate how it works:\n\nlog4j.rootLogger=DEBUG, A1\nlog4j.appender.A1=org.apache.log4j.ConsoleAppender\nlog4j.appender.A1.layout=org.apache.log4j.PatternLayout\nlog4j.appender.A1.layout.ConversionPattern=%-4r %-5p %c %x - %m%n\n\nThis enables messages of priority \"DEBUG\" or higher in the root hierarchy and has the system\nwrite them to the console. \"ConsoleAppender\" is a Java appender, but \"Log::Log4perl\" jumps\nthrough a significant number of hoops internally to map these to their corresponding Perl\nclasses, \"Log::Log4perl::Appender::Screen\" in this case.\n\nSecond example:\n\nlog4perl.rootLogger=DEBUG, A1\nlog4perl.appender.A1=Log::Log4perl::Appender::Screen\nlog4perl.appender.A1.layout=PatternLayout\nlog4perl.appender.A1.layout.ConversionPattern=%d %-5p %c - %m%n\nlog4perl.logger.com.foo=WARN\n\nThis defines two loggers: The root logger and the \"com.foo\" logger. The root logger is easily\ntriggered by debug-messages, but the \"com.foo\" logger makes sure that messages issued within the\n\"Com::Foo\" component and below are only forwarded to the appender if they're of priority\n*warning* or higher.\n\nNote that the \"com.foo\" logger doesn't define an appender. Therefore, it will just propagate the\nmessage up the hierarchy until the root logger picks it up and forwards it to the one and only\nappender of the root category, using the format defined for it.\n\nThird example:\n\nlog4j.rootLogger=DEBUG, stdout, R\nlog4j.appender.stdout=org.apache.log4j.ConsoleAppender\nlog4j.appender.stdout.layout=org.apache.log4j.PatternLayout\nlog4j.appender.stdout.layout.ConversionPattern=%5p (%F:%L) - %m%n\nlog4j.appender.R=org.apache.log4j.RollingFileAppender\nlog4j.appender.R.File=example.log\nlog4j.appender.R.layout=org.apache.log4j.PatternLayout\nlog4j.appender.R.layout.ConversionPattern=%p %c - %m%n\n\nThe root logger defines two appenders here: \"stdout\", which uses\n\"org.apache.log4j.ConsoleAppender\" (ultimately mapped by \"Log::Log4perl\" to\nLog::Log4perl::Appender::Screen) to write to the screen. And \"R\", a\n\"org.apache.log4j.RollingFileAppender\" (mapped by \"Log::Log4perl\" to Log::Dispatch::FileRotate\nwith the \"File\" attribute specifying the log file.\n\nSee Log::Log4perl::Config for more examples and syntax explanations.\n"
                },
                {
                    "name": "Log Layouts",
                    "content": "If the logging engine passes a message to an appender, because it thinks it should be logged,\nthe appender doesn't just write it out haphazardly. There's ways to tell the appender how to\nformat the message and add all sorts of interesting data to it: The date and time when the event\nhappened, the file, the line number, the debug level of the logger and others.\n\nThere's currently two layouts defined in \"Log::Log4perl\": \"Log::Log4perl::Layout::SimpleLayout\"\nand \"Log::Log4perl::Layout::PatternLayout\":\n\n\"Log::Log4perl::SimpleLayout\"\nformats a message in a simple way and just prepends it by the debug level and a hyphen:\n\"\"$level - $message\", for example \"FATAL - Can't open password file\".\n\n\"Log::Log4perl::Layout::PatternLayout\"\non the other hand is very powerful and allows for a very flexible format in \"printf\"-style.\nThe format string can contain a number of placeholders which will be replaced by the logging\nengine when it's time to log the message:\n\n%c Category of the logging event.\n%C Fully qualified package (or class) name of the caller\n%d Current date in yyyy/MM/dd hh:mm:ss format\n%F File where the logging event occurred\n%H Hostname (if Sys::Hostname is available)\n%l Fully qualified name of the calling method followed by the\ncallers source the file name and line number between\nparentheses.\n%L Line number within the file where the log statement was issued\n%m The message to be logged\n%m{chomp} The message to be logged, stripped off a trailing newline\n%M Method or function where the logging request was issued\n%n Newline (OS-independent)\n%p Priority of the logging event\n%P pid of the current process\n%r Number of milliseconds elapsed from program start to logging\nevent\n%R Number of milliseconds elapsed from last logging event to\ncurrent logging event\n%T A stack trace of functions called\n%x The topmost NDC (see below)\n%X{key} The entry 'key' of the MDC (see below)\n%% A literal percent (%) sign\n\nNDC and MDC are explained in \"Nested Diagnostic Context (NDC)\" and \"Mapped Diagnostic\nContext (MDC)\".\n\nAlso, %d can be fine-tuned to display only certain characteristics of a date, according to\nthe SimpleDateFormat in the Java World\n(<http://java.sun.com/j2se/1.3/docs/api/java/text/SimpleDateFormat.html>)\n\nIn this way, %d{HH:mm} displays only hours and minutes of the current date, while %d{yy,\nEEEE} displays a two-digit year, followed by a spelled-out day (like \"Wednesday\").\n\nSimilar options are available for shrinking the displayed category or limit file/path\ncomponents, %F{1} only displays the source file *name* without any path components while %F\nlogs the full path. %c{2} only logs the last two components of the current category,\n\"Foo::Bar::Baz\" becomes \"Bar::Baz\" and saves space.\n\nIf those placeholders aren't enough, then you can define your own right in the config file\nlike this:\n\nlog4perl.PatternLayout.cspec.U = sub { return \"UID $<\" }\n\nSee Log::Log4perl::Layout::PatternLayout for further details on customized specifiers.\n\nPlease note that the subroutines you're defining in this way are going to be run in the\n\"main\" namespace, so be sure to fully qualify functions and variables if they're located in\ndifferent packages.\n\nSECURITY NOTE: this feature means arbitrary perl code can be embedded in the config file. In\nthe rare case where the people who have access to your config file are different from the\npeople who write your code and shouldn't have execute rights, you might want to call\n\nLog::Log4perl::Config->allowcode(0);\n\nbefore you call init(). Alternatively you can supply a restricted set of Perl opcodes that\ncan be embedded in the config file as described in \"Restricting what Opcodes can be in a\nPerl Hook\".\n\nAll placeholders are quantifiable, just like in *printf*. Following this tradition, \"%-20c\" will\nreserve 20 chars for the category and left-justify it.\n\nFor more details on logging and how to use the flexible and the simple format, check out the\noriginal \"log4j\" website under\n\nSimpleLayout <http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/SimpleLayout.html>\nand PatternLayout\n<http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html>\n"
                },
                {
                    "name": "Penalties",
                    "content": "Logging comes with a price tag. \"Log::Log4perl\" has been optimized to allow for maximum\nperformance, both with logging enabled and disabled.\n\nBut you need to be aware that there's a small hit every time your code encounters a log\nstatement -- no matter if logging is enabled or not. \"Log::Log4perl\" has been designed to keep\nthis so low that it will be unnoticeable to most applications.\n\nHere's a couple of tricks which help \"Log::Log4perl\" to avoid unnecessary delays:\n\nYou can save serious time if you're logging something like\n\n# Expensive in non-debug mode!\nfor (@superlongarray) {\n$logger->debug(\"Element: $\");\n}\n\nand @superlongarray is fairly big, so looping through it is pretty expensive. Only you, the\nprogrammer, knows that going through that \"for\" loop can be skipped entirely if the current\nlogging level for the actual component is higher than \"debug\". In this case, use this instead:\n\n# Cheap in non-debug mode!\nif($logger->isdebug()) {\nfor (@superlongarray) {\n$logger->debug(\"Element: $\");\n}\n}\n\nIf you're afraid that generating the parameters to the logging function is fairly expensive, use\nclosures:\n\n# Passed as subroutine ref\nuse Data::Dumper;\n$logger->debug(sub { Dumper($data) } );\n\nThis won't unravel $data via Dumper() unless it's actually needed because it's logged.\n\nAlso, Log::Log4perl lets you specify arguments to logger functions in *message output filter\nsyntax*:\n\n$logger->debug(\"Structure: \",\n{ filter => \\&Dumper,\nvalue  => $someref });\n\nIn this way, shortly before Log::Log4perl sending the message out to any appenders, it will be\nsearching all arguments for hash references and treat them in a special way:\n\nIt will invoke the function given as a reference with the \"filter\" key\n(\"Data::Dumper::Dumper()\") and pass it the value that came with the key named \"value\" as an\nargument. The anonymous hash in the call above will be replaced by the return value of the\nfilter function.\n"
                }
            ]
        },
        "Categories": {
            "content": "Categories are also called \"Loggers\" in Log4perl, both refer to the same thing and these terms\nare used interchangeably. \"Log::Log4perl\" uses *categories* to determine if a log statement in a\ncomponent should be executed or suppressed at the current logging level. Most of the time, these\ncategories are just the classes the log statements are located in:\n\npackage Candy::Twix;\n\nsub new {\nmy $logger = Log::Log4perl->getlogger(\"Candy::Twix\");\n$logger->debug(\"Creating a new Twix bar\");\nbless {}, shift;\n}\n\n# ...\n\npackage Candy::Snickers;\n\nsub new {\nmy $logger = Log::Log4perl->getlogger(\"Candy.Snickers\");\n$logger->debug(\"Creating a new Snickers bar\");\nbless {}, shift;\n}\n\n# ...\n\npackage main;\nLog::Log4perl->init(\"mylogdefs.conf\");\n\n# => \"LOG> Creating a new Snickers bar\"\nmy $first = Candy::Snickers->new();\n# => \"LOG> Creating a new Twix bar\"\nmy $second = Candy::Twix->new();\n\nNote that you can separate your category hierarchy levels using either dots like in Java (.) or\ndouble-colons (::) like in Perl. Both notations are equivalent and are handled the same way\ninternally.\n\nHowever, categories are just there to make use of inheritance: if you invoke a logger in a\nsub-category, it will bubble up the hierarchy and call the appropriate appenders. Internally,\ncategories are not related to the class hierarchy of the program at all -- they're purely\nvirtual. You can use arbitrary categories -- for example in the following program, which isn't\noo-style, but procedural:\n\nsub printportfolio {\n\nmy $log = Log::Log4perl->getlogger(\"user.portfolio\");\n$log->debug(\"Quotes requested: @\");\n\nfor(@) {\nprint \"$: \", getquote($), \"\\n\";\n}\n}\n\nsub getquote {\n\nmy $log = Log::Log4perl->getlogger(\"internet.quotesystem\");\n$log->debug(\"Fetching quote: $[0]\");\n\nreturn yahooquote($[0]);\n}\n\nThe logger in first function, \"printportfolio\", is assigned the (virtual) \"user.portfolio\"\ncategory. Depending on the \"Log4perl\" configuration, this will either call a \"user.portfolio\"\nappender, a \"user\" appender, or an appender assigned to root -- without \"user.portfolio\" having\nany relevance to the class system used in the program. The logger in the second function adheres\nto the \"internet.quotesystem\" category -- again, maybe because it's bundled with other Internet\nfunctions, but not because there would be a class of this name somewhere.\n\nHowever, be careful, don't go overboard: if you're developing a system in object-oriented style,\nusing the class hierarchy is usually your best choice. Think about the people taking over your\ncode one day: The class hierarchy is probably what they know right up front, so it's easy for\nthem to tune the logging to their needs.\n",
            "subsections": [
                {
                    "name": "Turn off a component",
                    "content": "\"Log4perl\" doesn't only allow you to selectively switch *on* a category of log messages, you can\nalso use the mechanism to selectively *disable* logging in certain components whereas logging is\nkept turned on in higher-level categories. This mechanism comes in handy if you find that while\nbumping up the logging level of a high-level (i. e. close to root) category, that one component\nlogs more than it should,\n\nHere's how it works:\n\n############################################################\n# Turn off logging in a lower-level category while keeping\n# it active in higher-level categories.\n############################################################\nlog4perl.rootLogger=DEBUG, LOGFILE\nlog4perl.logger.deep.down.the.hierarchy = ERROR, LOGFILE\n\n# ... Define appenders ...\n\nThis way, log messages issued from within \"Deep::Down::The::Hierarchy\" and below will be logged\nonly if they're \"ERROR\" or worse, while in all other system components even \"DEBUG\" messages\nwill be logged.\n"
                },
                {
                    "name": "Return Values",
                    "content": "All logging methods return values indicating if their message actually reached one or more\nappenders. If the message has been suppressed because of level constraints, \"undef\" is returned.\n\nFor example,\n\nmy $ret = $logger->info(\"Message\");\n\nwill return \"undef\" if the system debug level for the current category is not \"INFO\" or more\npermissive. If Log::Log4perl forwarded the message to one or more appenders, the number of\nappenders is returned.\n\nIf appenders decide to veto on the message with an appender threshold, the log method's return\nvalue will have them excluded. This means that if you've got one appender holding an appender\nthreshold and you're logging a message which passes the system's log level hurdle but not the\nappender threshold, 0 will be returned by the log function.\n\nThe bottom line is: Logging functions will return a *true* value if the message made it through\nto one or more appenders and a *false* value if it didn't. This allows for constructs like\n\n$logger->fatal(\"@\") or print STDERR \"@\\n\";\n\nwhich will ensure that the fatal message isn't lost if the current level is lower than FATAL or\nprinted twice if the level is acceptable but an appender already points to STDERR.\n"
                },
                {
                    "name": "Pitfalls with Categories",
                    "content": "Be careful with just blindly reusing the system's packages as categories. If you do, you'll get\ninto trouble with inherited methods. Imagine the following class setup:\n\nuse Log::Log4perl;\n\n###########################################\npackage Bar;\n###########################################\nsub new {\nmy($class) = @;\nmy $logger = Log::Log4perl::getlogger(PACKAGE);\n$logger->debug(\"Creating instance\");\nbless {}, $class;\n}\n###########################################\npackage Bar::Twix;\n###########################################\nour @ISA = qw(Bar);\n\n###########################################\npackage main;\n###########################################\nLog::Log4perl->init(\\ qq{\nlog4perl.category.Bar.Twix = DEBUG, Screen\nlog4perl.appender.Screen = Log::Log4perl::Appender::Screen\nlog4perl.appender.Screen.layout = SimpleLayout\n});\n\nmy $bar = Bar::Twix->new();\n\n\"Bar::Twix\" just inherits everything from \"Bar\", including the constructor \"new()\". Contrary to\nwhat you might be thinking at first, this won't log anything. Reason for this is the\n\"getlogger()\" call in package \"Bar\", which will always get a logger of the \"Bar\" category, even\nif we call \"new()\" via the \"Bar::Twix\" package, which will make perl go up the inheritance tree\nto actually execute \"Bar::new()\". Since we've only defined logging behaviour for \"Bar::Twix\" in\nthe configuration file, nothing will happen.\n\nThis can be fixed by changing the \"getlogger()\" method in \"Bar::new()\" to obtain a logger of\nthe category matching the *actual* class of the object, like in\n\n# ... in Bar::new() ...\nmy $logger = Log::Log4perl::getlogger( $class );\n\nIn a method other than the constructor, the class name of the actual object can be obtained by\ncalling \"ref()\" on the object reference, so\n\npackage BaseClass;\nuse Log::Log4perl qw( getlogger );\n\nsub new {\nbless {}, shift;\n}\n\nsub method {\nmy( $self ) = @;\n\ngetlogger( ref $self )->debug( \"message\" );\n}\n\npackage SubClass;\nour @ISA = qw(BaseClass);\n\nis the recommended pattern to make sure that\n\nmy $sub = SubClass->new();\n$sub->meth();\n\nstarts logging if the \"SubClass\" category (and not the \"BaseClass\" category has logging enabled\nat the DEBUG level.\n"
                },
                {
                    "name": "Initialize once and only once",
                    "content": "It's important to realize that Log::Log4perl gets initialized once and only once, typically at\nthe start of a program or system. Calling \"init()\" more than once will cause it to clobber the\nexisting configuration and *replace* it by the new one.\n\nIf you're in a traditional CGI environment, where every request is handled by a new process,\ncalling \"init()\" every time is fine. In persistent environments like \"modperl\", however,\nLog::Log4perl should be initialized either at system startup time (Apache offers startup\nhandlers for that) or via\n\n# Init or skip if already done\nLog::Log4perl->initonce($conffile);\n\n\"initonce()\" is identical to \"init()\", just with the exception that it will leave a potentially\nexisting configuration alone and will only call \"init()\" if Log::Log4perl hasn't been\ninitialized yet.\n\nIf you're just curious if Log::Log4perl has been initialized yet, the check\n\nif(Log::Log4perl->initialized()) {\n# Yes, Log::Log4perl has already been initialized\n} else {\n# No, not initialized yet ...\n}\n\ncan be used.\n\nIf you're afraid that the components of your system are stepping on each other's toes or if you\nare thinking that different components should initialize Log::Log4perl separately, try to\nconsolidate your system to use a centralized Log4perl configuration file and use Log4perl's\n*categories* to separate your components.\n"
                },
                {
                    "name": "Custom Filters",
                    "content": "Log4perl allows the use of customized filters in its appenders to control the output of\nmessages. These filters might grep for certain text chunks in a message, verify that its\npriority matches or exceeds a certain level or that this is the 10th time the same message has\nbeen submitted -- and come to a log/no log decision based upon these circumstantial facts.\n\nCheck out Log::Log4perl::Filter for detailed instructions on how to use them.\n"
                },
                {
                    "name": "Performance",
                    "content": "The performance of Log::Log4perl calls obviously depends on a lot of things. But to give you a\ngeneral idea, here's some rough numbers:\n\nOn a Pentium 4 Linux box at 2.4 GHz, you'll get through\n\n*   500,000 suppressed log statements per second\n\n*   30,000 logged messages per second (using an in-memory appender)\n\n*   initandwatch delay mode: 300,000 suppressed, 30,000 logged. initandwatch signal mode:\n450,000 suppressed, 30,000 logged.\n\nNumbers depend on the complexity of the Log::Log4perl configuration. For a more detailed\nbenchmark test, check the \"docs/benchmark.results.txt\" document in the Log::Log4perl\ndistribution.\n"
                }
            ]
        },
        "Cool Tricks": {
            "content": "Here's a collection of useful tricks for the advanced \"Log::Log4perl\" user. For more, check the\nFAQ, either in the distribution (Log::Log4perl::FAQ) or on <http://log4perl.sourceforge.net>.\n",
            "subsections": [
                {
                    "name": "Shortcuts",
                    "content": "When getting an instance of a logger, instead of saying\n\nuse Log::Log4perl;\nmy $logger = Log::Log4perl->getlogger();\n\nit's often more convenient to import the \"getlogger\" method from \"Log::Log4perl\" into the\ncurrent namespace:\n\nuse Log::Log4perl qw(getlogger);\nmy $logger = getlogger();\n\nPlease note this difference: To obtain the root logger, please use \"getlogger(\"\")\", call it\nwithout parameters (\"getlogger()\"), you'll get the logger of a category named after the current\npackage. \"getlogger()\" is equivalent to \"getlogger(PACKAGE)\".\n"
                },
                {
                    "name": "Alternative initialization",
                    "content": "Instead of having \"init()\" read in a configuration file by specifying a file name or passing it\na reference to an open filehandle (\"Log::Log4perl->init( \\*FILE )\"), you can also pass in a\nreference to a string, containing the content of the file:\n\nLog::Log4perl->init( \\$configtext );\n\nAlso, if you've got the \"name=value\" pairs of the configuration in a hash, you can just as well\ninitialize \"Log::Log4perl\" with a reference to it:\n\nmy %keyvaluepairs = (\n\"log4perl.rootLogger\"       => \"ERROR, LOGFILE\",\n\"log4perl.appender.LOGFILE\" => \"Log::Log4perl::Appender::File\",\n...\n);\n\nLog::Log4perl->init( \\%keyvaluepairs );\n\nOr also you can use a URL, see below:\n"
                },
                {
                    "name": "Using LWP to parse URLs",
                    "content": "(This section borrowed from XML::DOM::Parser by T.J. Mather).\n\nThe init() function now also supports URLs, e.g. *http://www.erols.com/enno/xsa.xml*. It uses\nLWP to download the file and then calls parse() on the resulting string. By default it will use\na LWP::UserAgent that is created as follows:\n\nuse LWP::UserAgent;\n$LWPUSERAGENT = LWP::UserAgent->new;\n$LWPUSERAGENT->envproxy;\n\nNote that envproxy reads proxy settings from environment variables, which is what Log4perl\nneeds to do to get through our firewall. If you want to use a different LWP::UserAgent, you can\nset it with\n\nLog::Log4perl::Config::setLWPUserAgent($myagent);\n\nCurrently, LWP is used when the filename (passed to parsefile) starts with one of the following\nURL schemes: http, https, ftp, wais, gopher, or file (followed by a colon.)\n\nDon't use this feature with initandwatch().\n"
                },
                {
                    "name": "Automatic reloading of changed configuration files",
                    "content": "Instead of just statically initializing Log::Log4perl via\n\nLog::Log4perl->init($conffile);\n\nthere's a way to have Log::Log4perl periodically check for changes in the configuration and\nreload it if necessary:\n\nLog::Log4perl->initandwatch($conffile, $delay);\n\nIn this mode, Log::Log4perl will examine the configuration file $conffile every $delay seconds\nfor changes via the file's last modification timestamp. If the file has been updated, it will be\nreloaded and replace the current Log::Log4perl configuration.\n\nThe way this works is that with every logger function called (debug(), isdebug(), etc.),\nLog::Log4perl will check if the delay interval has expired. If so, it will run a -M file check\non the configuration file. If its timestamp has been modified, the current configuration will be\ndumped and new content of the file will be loaded.\n\nThis convenience comes at a price, though: Calling time() with every logging function call,\nespecially the ones that are \"suppressed\" (!), will slow down these Log4perl calls by about 40%.\n\nTo alleviate this performance hit a bit, \"initandwatch()\" can be configured to listen for a\nUnix signal to reload the configuration instead:\n\nLog::Log4perl->initandwatch($conffile, 'HUP');\n\nThis will set up a signal handler for SIGHUP and reload the configuration if the application\nreceives this signal, e.g. via the \"kill\" command:\n\nkill -HUP pid\n\nwhere \"pid\" is the process ID of the application. This will bring you back to about 85% of\nLog::Log4perl's normal execution speed for suppressed statements. For details, check out\n\"Performance\". For more info on the signal handler, look for \"SIGNAL MODE\" in\nLog::Log4perl::Config::Watch.\n\nIf you have a somewhat long delay set between physical config file checks or don't want to use\nthe signal associated with the config file watcher, you can trigger a configuration reload at\nthe next possible time by calling \"Log::Log4perl::Config->watcher->forcenextcheck()\".\n\nOne thing to watch out for: If the configuration file contains a syntax or other fatal error, a\nrunning application will stop with \"die\" if this damaged configuration will be loaded during\nruntime, triggered either by a signal or if the delay period expired and the change is detected.\nThis behaviour might change in the future.\n\nTo allow the application to intercept and control a configuration reload in initandwatch mode,\na callback can be specified:\n\nLog::Log4perl->initandwatch($conffile, 10, {\npreinitcallback => \\&callback });\n\nIf Log4perl determines that the configuration needs to be reloaded, it will call the\n\"preinitcallback\" function without parameters. If the callback returns a true value, Log4perl\nwill proceed and reload the configuration. If the callback returns a false value, Log4perl will\nkeep the old configuration and skip reloading it until the next time around. Inside the\ncallback, an application can run all kinds of checks, including accessing the configuration\nfile, which is available via \"Log::Log4perl::Config->watcher()->file()\".\n"
                },
                {
                    "name": "Variable Substitution",
                    "content": "To avoid having to retype the same expressions over and over again, Log::Log4perl's\nconfiguration files support simple variable substitution. New variables are defined simply by\nadding\n\nvarname = value\n\nlines to the configuration file before using\n\n${varname}\n\nafterwards to recall the assigned values. Here's an example:\n\nlayoutclass   = Log::Log4perl::Layout::PatternLayout\nlayoutpattern = %d %F{1} %L> %m %n\n\nlog4perl.category.Bar.Twix = WARN, Logfile, Screen\n\nlog4perl.appender.Logfile  = Log::Log4perl::Appender::File\nlog4perl.appender.Logfile.filename = test.log\nlog4perl.appender.Logfile.layout = ${layoutclass}\nlog4perl.appender.Logfile.layout.ConversionPattern = ${layoutpattern}\n\nlog4perl.appender.Screen  = Log::Log4perl::Appender::Screen\nlog4perl.appender.Screen.layout = ${layoutclass}\nlog4perl.appender.Screen.layout.ConversionPattern = ${layoutpattern}\n\nThis is a convenient way to define two appenders with the same layout without having to retype\nthe pattern definitions.\n\nVariable substitution via \"${varname}\" will first try to find an explicitly defined variable. If\nthat fails, it will check your shell's environment for a variable of that name. If that also\nfails, the program will \"die()\".\n"
                },
                {
                    "name": "Perl Hooks in the Configuration File",
                    "content": "If some of the values used in the Log4perl configuration file need to be dynamically modified by\nthe program, use Perl hooks:\n\nlog4perl.appender.File.filename = \\\nsub { return getLogfileName(); }\n\nEach value starting with the string \"sub {...\" is interpreted as Perl code to be executed at the\ntime the application parses the configuration via \"Log::Log4perl::init()\". The return value of\nthe subroutine is used by Log::Log4perl as the configuration value.\n\nThe Perl code is executed in the \"main\" package, functions in other packages have to be called\nin fully-qualified notation.\n\nHere's another example, utilizing an environment variable as a username for a DBI appender:\n\nlog4perl.appender.DB.username = \\\nsub { $ENV{DBUSERNAME } }\n\nHowever, please note the difference between these code snippets and those used for user-defined\nconversion specifiers as discussed in Log::Log4perl::Layout::PatternLayout: While the snippets\nabove are run *once* when \"Log::Log4perl::init()\" is called, the conversion specifier snippets\nare executed *each time* a message is rendered according to the PatternLayout.\n\nSECURITY NOTE: this feature means arbitrary perl code can be embedded in the config file. In the\nrare case where the people who have access to your config file are different from the people who\nwrite your code and shouldn't have execute rights, you might want to set\n\nLog::Log4perl::Config->allowcode(0);\n\nbefore you call init(). Alternatively you can supply a restricted set of Perl opcodes that can\nbe embedded in the config file as described in \"Restricting what Opcodes can be in a Perl Hook\".\n"
                },
                {
                    "name": "Restricting what Opcodes can be in a Perl Hook",
                    "content": "The value you pass to Log::Log4perl::Config->allowcode() determines whether the code that is\nembedded in the config file is eval'd unrestricted, or eval'd in a Safe compartment. By default,\na value of '1' is assumed, which does a normal 'eval' without any restrictions. A value of '0'\nhowever prevents any embedded code from being evaluated.\n\nIf you would like fine-grained control over what can and cannot be included in embedded code,\nthen please utilize the following methods:\n\nLog::Log4perl::Config->allowcode( $allow );\nLog::Log4perl::Config->allowedcodeops($op1, $op2, ... );\nLog::Log4perl::Config->varssharedwithsafecompartment( [ \\%vars | $package, \\@vars ] );\nLog::Log4perl::Config->allowedcodeopsconveniencemap( [ \\%map | $name, \\@mask ] );\n\nLog::Log4perl::Config->allowedcodeops() takes a list of opcode masks that are allowed to run\nin the compartment. The opcode masks must be specified as described in Opcode:\n\nLog::Log4perl::Config->allowedcodeops(':subprocess');\n\nThis example would allow Perl operations like backticks, system, fork, and waitpid to be\nexecuted in the compartment. Of course, you probably don't want to use this mask -- it would\nallow exactly what the Safe compartment is designed to prevent.\n\nLog::Log4perl::Config->varssharedwithsafecompartment() takes the symbols which should be\nexported into the Safe compartment before the code is evaluated. The keys of this hash are the\npackage names that the symbols are in, and the values are array references to the literal symbol\nnames. For convenience, the default settings export the '%ENV' hash from the 'main' package into\nthe compartment:\n\nLog::Log4perl::Config->varssharedwithsafecompartment(\nmain => [ '%ENV' ],\n);\n\nLog::Log4perl::Config->allowedcodeopsconveniencemap() is an accessor method to a map of\nconvenience names to opcode masks. At present, the following convenience names are defined:\n\nsafe        = [ ':browse' ]\nrestrictive = [ ':default' ]\n\nFor convenience, if Log::Log4perl::Config->allowcode() is called with a value which is a key of\nthe map previously defined with Log::Log4perl::Config->allowedcodeopsconveniencemap(), then\nthe allowed opcodes are set according to the value defined in the map. If this is confusing,\nconsider the following:\n\nuse Log::Log4perl;\n\nmy $config = <<'END';\nlog4perl.logger = INFO, Main\nlog4perl.appender.Main = Log::Log4perl::Appender::File\nlog4perl.appender.Main.filename = \\\nsub { \"example\" . getpwuid($<) . \".log\" }\nlog4perl.appender.Main.layout = Log::Log4perl::Layout::SimpleLayout\nEND\n\n$Log::Log4perl::Config->allowcode('restrictive');\nLog::Log4perl->init( \\$config );       # will fail\n$Log::Log4perl::Config->allowcode('safe');\nLog::Log4perl->init( \\$config );       # will succeed\n\nThe reason that the first call to ->init() fails is because the 'restrictive' name maps to an\nopcode mask of ':default'. getpwuid() is not part of ':default', so ->init() fails. The 'safe'\nname maps to an opcode mask of ':browse', which allows getpwuid() to run, so ->init() succeeds.\n"
                },
                {
                    "name": "allowed_code_ops_convenience_map",
                    "content": ""
                },
                {
                    "name": "allowed_code_ops_convenience_map",
                    "content": "Returns the entire convenience name map as a hash reference in scalar context or a hash in\nlist context.\n"
                },
                {
                    "name": "allowed_code_ops_convenience_map",
                    "content": "Replaces the entire convenience name map with the supplied hash reference.\n"
                },
                {
                    "name": "allowed_code_ops_convenience_map",
                    "content": "Returns the opcode mask for the given convenience name, or undef if no such name is defined\nin the map.\n"
                },
                {
                    "name": "allowed_code_ops_convenience_map",
                    "content": "Adds the given name/mask pair to the convenience name map. If the name already exists in the\nmap, it's value is replaced with the new mask.\n\nas can varssharedwithsafecompartment():\n"
                },
                {
                    "name": "vars_shared_with_safe_compartment",
                    "content": "Return the entire map of packages to variables as a hash reference in scalar context or a\nhash in list context.\n"
                },
                {
                    "name": "vars_shared_with_safe_compartment",
                    "content": "Replaces the entire map of packages to variables with the supplied hash reference.\n"
                },
                {
                    "name": "vars_shared_with_safe_compartment",
                    "content": "Returns the arrayref of variables to be shared for a specific package.\n"
                },
                {
                    "name": "vars_shared_with_safe_compartment",
                    "content": "Adds the given package / varlist pair to the map. If the package already exists in the map,\nit's value is replaced with the new arrayref of variable names.\n\nFor more information on opcodes and Safe Compartments, see Opcode and Safe.\n"
                },
                {
                    "name": "Changing the Log Level on a Logger",
                    "content": "Log4perl provides some internal functions for quickly adjusting the log level from within a\nrunning Perl program.\n\nNow, some people might argue that you should adjust your levels from within an external Log4perl\nconfiguration file, but Log4perl is everybody's darling.\n\nTypically run-time adjusting of levels is done at the beginning, or in response to some external\ninput (like a \"more logging\" runtime command for diagnostics).\n\nYou get the log level from a logger object with:\n\n$currentlevel = $logger->level();\n\nand you may set it with the same method, provided you first imported the log level constants,\nwith:\n\nuse Log::Log4perl::Level;\n\nThen you can set the level on a logger to one of the constants,\n\n$logger->level($ERROR); # one of DEBUG, INFO, WARN, ERROR, FATAL\n\nTo increase the level of logging currently being done, use:\n\n$logger->morelogging($delta);\n\nand to decrease it, use:\n\n$logger->lesslogging($delta);\n\n$delta must be a positive integer (for now, we may fix this later ;).\n\nThere are also two equivalent functions:\n\n$logger->inclevel($delta);\n$logger->declevel($delta);\n\nThey're included to allow you a choice in readability. Some folks will prefer more/lesslogging,\nas they're fairly clear in what they do, and allow the programmer not to worry too much about\nwhat a Level is and whether a higher level means more or less logging. However, other folks who\ndo understand and have lots of code that deals with levels will probably prefer the inclevel()\nand declevel() methods as they want to work with Levels and not worry about whether that means\nmore or less logging. :)\n\nThat diatribe aside, typically you'll use morelogging() or inclevel() as such:\n\nmy $v = 0; # default level of verbosity.\n\nGetOptions(\"v+\" => \\$v, ...);\n\nif( $v ) {\n$logger->morelogging($v); # inc logging level once for each -v in ARGV\n}\n"
                },
                {
                    "name": "Custom Log Levels",
                    "content": "First off, let me tell you that creating custom levels is heavily deprecated by the log4j folks.\nIndeed, instead of creating additional levels on top of the predefined DEBUG, INFO, WARN, ERROR\nand FATAL, you should use categories to control the amount of logging smartly, based on the\nlocation of the log-active code in the system.\n\nNevertheless, Log4perl provides a nice way to create custom levels via the createcustomlevel()\nroutine function. However, this must be done before the first call to init() or getlogger().\nSay you want to create a NOTIFY logging level that comes after WARN (and thus before INFO).\nYou'd do such as follows:\n\nuse Log::Log4perl;\nuse Log::Log4perl::Level;\n\nLog::Log4perl::Logger::createcustomlevel(\"NOTIFY\", \"WARN\");\n\nAnd that's it! \"createcustomlevel()\" creates the following functions / variables for level\nFOO:\n\n$FOOINT        # integer to use in L4p::Level::tolevel()\n$logger->foo()  # log function to log if level = FOO\n$logger->isfoo()   # true if current level is >= FOO\n\nThese levels can also be used in your config file, but note that your config file probably won't\nbe portable to another log4perl or log4j environment unless you've made the appropriate mods\nthere too.\n\nSince Log4perl translates log levels to syslog and Log::Dispatch if their appenders are used,\nyou may add mappings for custom levels as well:\n\nLog::Log4perl::Level::addpriority(\"NOTIFY\", \"WARN\",\n$syslogequiv, $logdispatchlevel);\n\nFor example, if your new custom \"NOTIFY\" level is supposed to map to syslog level 2\n(\"LOGNOTICE\") and Log::Dispatch level 2 (\"notice\"), use:\n\nLog::Log4perl::Logger::createcustomlevel(\"NOTIFY\", \"WARN\", 2, 2);\n"
                },
                {
                    "name": "System-wide log levels",
                    "content": "As a fairly drastic measure to decrease (or increase) the logging level all over the system with\none single configuration option, use the \"threshold\" keyword in the Log4perl configuration file:\n\nlog4perl.threshold = ERROR\n\nsets the system-wide (or hierarchy-wide according to the log4j documentation) to ERROR and\ntherefore deprives every logger in the system of the right to log lower-prio messages.\n"
                },
                {
                    "name": "Easy Mode",
                    "content": "For teaching purposes (especially for [1]), I've put \":easy\" mode into \"Log::Log4perl\", which\njust initializes a single root logger with a defined priority and a screen appender including\nsome nice standard layout:\n\n### Initialization Section\nuse Log::Log4perl qw(:easy);\nLog::Log4perl->easyinit($ERROR);  # Set priority of root logger to ERROR\n\n### Application Section\nmy $logger = getlogger();\n$logger->fatal(\"This will get logged.\");\n$logger->debug(\"This won't.\");\n\nThis will dump something like\n\n2002/08/04 11:43:09 ERROR> script.pl:16 main::function - This will get logged.\n\nto the screen. While this has been proven to work well familiarizing people with \"Log::Logperl\"\nslowly, effectively avoiding to clobber them over the head with a plethora of different knobs to\nfiddle with (categories, appenders, levels, layout), the overall mission of \"Log::Log4perl\" is\nto let people use categories right from the start to get used to the concept. So, let's keep\nthis one fairly hidden in the man page (congrats on reading this far :).\n"
                },
                {
                    "name": "Stealth loggers",
                    "content": "Sometimes, people are lazy. If you're whipping up a 50-line script and want the comfort of\nLog::Log4perl without having the burden of carrying a separate log4perl.conf file or a 5-liner\ndefining that you want to append your log statements to a file, you can use the following\nfeatures:\n\nuse Log::Log4perl qw(:easy);\n\nLog::Log4perl->easyinit( { level   => $DEBUG,\nfile    => \">>test.log\" } );\n\n# Logs to test.log via stealth logger\nDEBUG(\"Debug this!\");\nINFO(\"Info this!\");\nWARN(\"Warn this!\");\nERROR(\"Error this!\");\n\nsomefunction();\n\nsub somefunction {\n# Same here\nFATAL(\"Fatal this!\");\n}\n\nIn \":easy\" mode, \"Log::Log4perl\" will instantiate a *stealth logger* and introduce the\nconvenience functions \"TRACE\", \"DEBUG()\", \"INFO()\", \"WARN()\", \"ERROR()\", \"FATAL()\", and \"ALWAYS\"\ninto the package namespace. These functions simply take messages as arguments and forward them\nto the stealth loggers methods (\"debug()\", \"info()\", and so on).\n\nIf a message should never be blocked, regardless of the log level, use the \"ALWAYS\" function\nwhich corresponds to a log level of \"OFF\":\n\nALWAYS \"This will be printed regardless of the log level\";\n\nThe \"easyinit\" method can be called with a single level value to create a STDERR appender and a\nroot logger as in\n\nLog::Log4perl->easyinit($DEBUG);\n\nor, as shown below (and in the example above) with a reference to a hash, specifying values for\n\"level\" (the logger's priority), \"file\" (the appender's data sink), \"category\" (the logger's\ncategory and \"layout\" for the appender's pattern layout specification. All key-value pairs are\noptional, they default to $DEBUG for \"level\", \"STDERR\" for \"file\", \"\" (root category) for\n\"category\" and \"%d %m%n\" for \"layout\":\n\nLog::Log4perl->easyinit( { level    => $DEBUG,\nfile     => \">test.log\",\nutf8     => 1,\ncategory => \"Bar::Twix\",\nlayout   => '%F{1}-%L-%M: %m%n' } );\n\nThe \"file\" parameter takes file names preceded by \">\" (overwrite) and \">>\" (append) as\narguments. This will cause \"Log::Log4perl::Appender::File\" appenders to be created behind the\nscenes. Also the keywords \"STDOUT\" and \"STDERR\" (no \">\" or \">>\") are recognized, which will\nutilize and configure \"Log::Log4perl::Appender::Screen\" appropriately. The \"utf8\" flag, if set\nto a true value, runs a \"binmode\" command on the file handle to establish a utf8 line discipline\non the file, otherwise you'll get a 'wide character in print' warning message and probably not\nwhat you'd expect as output.\n\nThe stealth loggers can be used in different packages, you just need to make sure you're calling\nthe \"use\" function in every package you're using \"Log::Log4perl\"'s easy services:\n\npackage Bar::Twix;\nuse Log::Log4perl qw(:easy);\nsub eat { DEBUG(\"Twix mjam\"); }\n\npackage Bar::Mars;\nuse Log::Log4perl qw(:easy);\nsub eat { INFO(\"Mars mjam\"); }\n\npackage main;\n\nuse Log::Log4perl qw(:easy);\n\nLog::Log4perl->easyinit( { level    => $DEBUG,\nfile     => \">>test.log\",\ncategory => \"Bar::Twix\",\nlayout   => '%F{1}-%L-%M: %m%n' },\n{ level    => $DEBUG,\nfile     => \"STDOUT\",\ncategory => \"Bar::Mars\",\nlayout   => '%m%n' },\n);\nBar::Twix::eat();\nBar::Mars::eat();\n\nAs shown above, \"easyinit()\" will take any number of different logger definitions as hash\nreferences.\n\nAlso, stealth loggers feature the functions \"LOGWARN()\", \"LOGDIE()\", and \"LOGEXIT()\", combining\na logging request with a subsequent Perl warn() or die() or exit() statement. So, for example\n\nif($allislost) {\nLOGDIE(\"Terrible Problem\");\n}\n\nwill log the message if the package's logger is at least \"FATAL\" but \"die()\" (including the\ntraditional output to STDERR) in any case afterwards.\n\nSee \"Log and die or warn\" for the similar \"logdie()\" and \"logwarn()\" functions of regular (i.e\nnon-stealth) loggers.\n\nSimilarly, \"LOGCARP()\", \"LOGCLUCK()\", \"LOGCROAK()\", and \"LOGCONFESS()\" are provided in \":easy\"\nmode, facilitating the use of \"logcarp()\", \"logcluck()\", \"logcroak()\", and \"logconfess()\" with\nstealth loggers.\n\nWhen using Log::Log4perl in easy mode, please make sure you understand the implications of\n\"Pitfalls with Categories\".\n\nBy the way, these convenience functions perform exactly as fast as the standard Log::Log4perl\nlogger methods, there's *no* performance penalty whatsoever.\n\nNested Diagnostic Context (NDC)\nIf you find that your application could use a global (thread-specific) data stack which your\nloggers throughout the system have easy access to, use Nested Diagnostic Contexts (NDCs). Also\ncheck out \"Mapped Diagnostic Context (MDC)\", this might turn out to be even more useful.\n\nFor example, when handling a request of a web client, it's probably useful to have the user's IP\naddress available in all log statements within code dealing with this particular request.\nInstead of passing this piece of data around between your application functions, you can just\nuse the global (but thread-specific) NDC mechanism. It allows you to push data pieces (scalars\nusually) onto its stack via\n\nLog::Log4perl::NDC->push(\"San\");\nLog::Log4perl::NDC->push(\"Francisco\");\n\nand have your loggers retrieve them again via the \"%x\" placeholder in the PatternLayout. With\nthe stack values above and a PatternLayout format like \"%x %m%n\", the call\n\n$logger->debug(\"rocks\");\n\nwill end up as\n\nSan Francisco rocks\n\nin the log appender.\n\nThe stack mechanism allows for nested structures. Just make sure that at the end of the request,\nyou either decrease the stack one by one by calling\n\nLog::Log4perl::NDC->pop();\nLog::Log4perl::NDC->pop();\n\nor clear out the entire NDC stack by calling\n\nLog::Log4perl::NDC->remove();\n\nEven if you should forget to do that, \"Log::Log4perl\" won't grow the stack indefinitely, but\nlimit it to a maximum, defined in \"Log::Log4perl::NDC\" (currently 5). A call to \"push()\" on a\nfull stack will just replace the topmost element by the new value.\n\nAgain, the stack is always available via the \"%x\" placeholder in the\nLog::Log4perl::Layout::PatternLayout class whenever a logger fires. It will replace \"%x\" by the\nblank-separated list of the values on the stack. It does that by just calling\n\nLog::Log4perl::NDC->get();\n\ninternally. See details on how this standard log4j feature is implemented in Log::Log4perl::NDC.\n\nMapped Diagnostic Context (MDC)\nJust like the previously discussed NDC stores thread-specific information in a stack structure,\nthe MDC implements a hash table to store key/value pairs in.\n\nThe static method\n\nLog::Log4perl::MDC->put($key, $value);\n\nstores $value under a key $key, with which it can be retrieved later (possibly in a totally\ndifferent part of the system) by calling the \"get\" method:\n\nmy $value = Log::Log4perl::MDC->get($key);\n\nIf no value has been stored previously under $key, the \"get\" method will return \"undef\".\n\nTypically, MDC values are retrieved later on via the \"%X{...}\" placeholder in\n\"Log::Log4perl::Layout::PatternLayout\". If the \"get()\" method returns \"undef\", the placeholder\nwill expand to the string \"[undef]\".\n\nAn application taking a web request might store the remote host like\n\nLog::Log4perl::MDC->put(\"remotehost\", $r->headers(\"HOST\"));\n\nat its beginning and if the appender's layout looks something like\n\nlog4perl.appender.Logfile.layout.ConversionPattern = %X{remotehost}: %m%n\n\nthen a log statement like\n\nDEBUG(\"Content delivered\");\n\nwill log something like\n\nadsl-63.dsl.snf.pacbell.net: Content delivered\n\nlater on in the program.\n\nFor details, please check Log::Log4perl::MDC.\n"
                },
                {
                    "name": "Resurrecting hidden Log4perl Statements",
                    "content": "Sometimes scripts need to be deployed in environments without having Log::Log4perl installed\nyet. On the other hand, you don't want to live without your Log4perl statements -- they're gonna\ncome in handy later.\n\nSo, just deploy your script with Log4perl statements commented out with the pattern \"###l4p\",\nlike in\n\n###l4p DEBUG \"It works!\";\n# ...\n###l4p INFO \"Really!\";\n\nIf Log::Log4perl is available, use the \":resurrect\" tag to have Log4perl resurrect those buried\nstatements before the script starts running:\n\nuse Log::Log4perl qw(:resurrect :easy);\n\n###l4p Log::Log4perl->easyinit($DEBUG);\n###l4p DEBUG \"It works!\";\n# ...\n###l4p INFO \"Really!\";\n\nThis will have a source filter kick in and indeed print\n\n2004/11/18 22:08:46 It works!\n2004/11/18 22:08:46 Really!\n\nIn environments lacking Log::Log4perl, just comment out the first line and the script will run\nnevertheless (but of course without logging):\n\n# use Log::Log4perl qw(:resurrect :easy);\n\n###l4p Log::Log4perl->easyinit($DEBUG);\n###l4p DEBUG \"It works!\";\n# ...\n###l4p INFO \"Really!\";\n\nbecause everything's a regular comment now. Alternatively, put the magic Log::Log4perl comment\nresurrection line into your shell's PERL5OPT environment variable, e.g. for bash:\n\nset PERL5OPT=-MLog::Log4perl=:resurrect,:easy\nexport PERL5OPT\n\nThis will awaken the giant within an otherwise silent script like the following:\n\n#!/usr/bin/perl\n\n###l4p Log::Log4perl->easyinit($DEBUG);\n###l4p DEBUG \"It works!\";\n\nAs of \"Log::Log4perl\" 1.12, you can even force *all* modules loaded by a script to have their\nhidden Log4perl statements resurrected. For this to happen, load \"Log::Log4perl::Resurrector\"\n*before* loading any modules:\n\nuse Log::Log4perl qw(:easy);\nuse Log::Log4perl::Resurrector;\n\nuse Foobar; # All hidden Log4perl statements in here will\n# be uncommented before Foobar gets loaded.\n\nLog::Log4perl->easyinit($DEBUG);\n...\n\nCheck the \"Log::Log4perl::Resurrector\" manpage for more details.\n"
                },
                {
                    "name": "Access defined appenders",
                    "content": "All appenders defined in the configuration file or via Perl code can be retrieved by the\n\"appenderbyname()\" class method. This comes in handy if you want to manipulate or query\nappender properties after the Log4perl configuration has been loaded via \"init()\".\n\nNote that internally, Log::Log4perl uses the \"Log::Log4perl::Appender\" wrapper class to control\nthe real appenders (like \"Log::Log4perl::Appender::File\" or \"Log::Dispatch::FileRotate\"). The\n\"Log::Log4perl::Appender\" class has an \"appender\" attribute, pointing to the real appender.\n\nThe reason for this is that external appenders like \"Log::Dispatch::FileRotate\" don't support\nall of Log::Log4perl's appender control mechanisms (like appender thresholds).\n\nThe previously mentioned method \"appenderbyname()\" returns a reference to the *real* appender\nobject. If you want access to the wrapper class (e.g. if you want to modify the appender's\nthreshold), use the hash $Log::Log4perl::Logger::APPENDERBYNAME{...} instead, which holds\nreferences to all appender wrapper objects.\n"
                },
                {
                    "name": "Modify appender thresholds",
                    "content": "To set an appender's threshold, use its \"threshold()\" method:\n\n$app->threshold( $FATAL );\n\nTo conveniently adjust *all* appender thresholds (e.g. because a script uses morelogging()),\nuse\n\n# decrease thresholds of all appenders\nLog::Log4perl->appenderthresholdsadjust(-1);\n\nThis will decrease the thresholds of all appenders in the system by one level, i.e. WARN becomes\nINFO, INFO becomes DEBUG, etc. To only modify selected ones, use\n\n# decrease thresholds of selected appenders\nLog::Log4perl->appenderthresholdsadjust(-1, ['AppName1', ...]);\n\nand pass the names of affected appenders in a ref to an array.\n"
                }
            ]
        },
        "Advanced configuration within Perl": {
            "content": "Initializing Log::Log4perl can certainly also be done from within Perl. At last, this is what\n\"Log::Log4perl::Config\" does behind the scenes. Log::Log4perl's configuration file parsers are\nusing a publically available API to set up Log::Log4perl's categories, appenders and layouts.\n\nHere's an example on how to configure two appenders with the same layout in Perl, without using\na configuration file at all:\n\n########################\n# Initialization section\n########################\nuse Log::Log4perl;\nuse Log::Log4perl::Layout;\nuse Log::Log4perl::Level;\n\n# Define a category logger\nmy $log = Log::Log4perl->getlogger(\"Foo::Bar\");\n\n# Define a layout\nmy $layout = Log::Log4perl::Layout::PatternLayout->new(\"[%r] %F %L %m%n\");\n\n# Define a file appender\nmy $fileappender = Log::Log4perl::Appender->new(\n\"Log::Log4perl::Appender::File\",\nname      => \"filelog\",\nfilename  => \"/tmp/my.log\");\n\n# Define a stdout appender\nmy $stdoutappender =  Log::Log4perl::Appender->new(\n\"Log::Log4perl::Appender::Screen\",\nname      => \"screenlog\",\nstderr    => 0);\n\n# Have both appenders use the same layout (could be different)\n$stdoutappender->layout($layout);\n$fileappender->layout($layout);\n\n$log->addappender($stdoutappender);\n$log->addappender($fileappender);\n$log->level($INFO);\n\nPlease note the class of the appender object is passed as a *string* to\n\"Log::Log4perl::Appender\" in the *first* argument. Behind the scenes, \"Log::Log4perl::Appender\"\nwill create the necessary \"Log::Log4perl::Appender::*\" (or \"Log::Dispatch::*\") object and pass\nalong the name value pairs we provided to \"Log::Log4perl::Appender->new()\" after the first\nargument.\n\nThe \"name\" value is optional and if you don't provide one, \"Log::Log4perl::Appender->new()\" will\ncreate a unique one for you. The names and values of additional parameters are dependent on the\nrequirements of the particular appender class and can be looked up in their manual pages.\n\nA side note: In case you're wondering if \"Log::Log4perl::Appender->new()\" will also take care of\nthe \"minlevel\" argument to the \"Log::Dispatch::*\" constructors called behind the scenes -- yes,\nit does. This is because we want the \"Log::Dispatch\" objects to blindly log everything we send\nthem (\"debug\" is their lowest setting) because *we* in \"Log::Log4perl\" want to call the shots\nand decide on when and what to log.\n\nThe call to the appender's *layout()* method specifies the format (as a previously created\n\"Log::Log4perl::Layout::PatternLayout\" object) in which the message is being logged in the\nspecified appender. If you don't specify a layout, the logger will fall back to\n\"Log::Log4perl::SimpleLayout\", which logs the debug level, a hyphen (-) and the log message.\n\nLayouts are objects, here's how you create them:\n\n# Create a simple layout\nmy $simple = Log::Log4perl::SimpleLayout();\n\n# create a flexible layout:\n# (\"yyyy/MM/dd hh:mm:ss (file:lineno)> message\\n\")\nmy $pattern = Log::Log4perl::Layout::PatternLayout(\"%d (%F:%L)> %m%n\");\n\nEvery appender has exactly one layout assigned to it. You assign the layout to the appender\nusing the appender's \"layout()\" object:\n\nmy $app =  Log::Log4perl::Appender->new(\n\"Log::Log4perl::Appender::Screen\",\nname      => \"screenlog\",\nstderr    => 0);\n\n# Assign the previously defined flexible layout\n$app->layout($pattern);\n\n# Add the appender to a previously defined logger\n$logger->addappender($app);\n\n# ... and you're good to go!\n$logger->debug(\"Blah\");\n# => \"2002/07/10 23:55:35 (test.pl:207)> Blah\\n\"\n\nIt's also possible to remove appenders from a logger:\n\n$logger->removeappender($appendername);\n\nwill remove an appender, specified by name, from a given logger. Please note that this does\n*not* remove an appender from the system.\n\nTo eradicate an appender from the system, you need to call\n\"Log::Log4perl->eradicateappender($appendername)\" which will first remove the appender from\nevery logger in the system and then will delete all references Log4perl holds to it.\n\nTo remove a logger from the system, use \"Log::Log4perl->removelogger($logger)\". After the\nremaining reference $logger goes away, the logger will self-destruct. If the logger in question\nis a stealth logger, all of its convenience shortcuts (DEBUG, INFO, etc) will turn into no-ops.\n\nHow about Log::Dispatch::Config?\nTatsuhiko Miyagawa's \"Log::Dispatch::Config\" is a very clever simplified logger implementation,\ncovering some of the *log4j* functionality. Among the things that \"Log::Log4perl\" can but\n\"Log::Dispatch::Config\" can't are:\n\n*   You can't assign categories to loggers. For small systems that's fine, but if you can't turn\noff and on detailed logging in only a tiny subsystem of your environment, you're missing out\non a majorly useful log4j feature.\n\n*   Defining appender thresholds. Important if you want to solve problems like \"log all messages\nof level FATAL to STDERR, plus log all DEBUG messages in \"Foo::Bar\" to a log file\". If you\ndon't have appenders thresholds, there's no way to prevent cluttering STDERR with DEBUG\nmessages.\n\n*   PatternLayout specifications in accordance with the standard (e.g. \"%d{HH:mm}\").\n\nBottom line: Log::Dispatch::Config is fine for small systems with simple logging requirements.\nHowever, if you're designing a system with lots of subsystems which you need to control\nindependently, you'll love the features of \"Log::Log4perl\", which is equally easy to use.\n",
            "subsections": []
        },
        "Using Log::Log4perl with wrapper functions and classes": {
            "content": "If you don't use \"Log::Log4perl\" as described above, but from a wrapper function, the pattern\nlayout will generate wrong data for %F, %C, %L, and the like. Reason for this is that\n\"Log::Log4perl\"'s loggers assume a static caller depth to the application that's using them.\n\nIf you're using one (or more) wrapper functions, \"Log::Log4perl\" will indicate where your logger\nfunction called the loggers, not where your application called your wrapper:\n\nuse Log::Log4perl qw(:easy);\nLog::Log4perl->easyinit({ level => $DEBUG,\nlayout => \"%M %m%n\" });\n\nsub mylog {\nmy($message) = @;\n\nDEBUG $message;\n}\n\nsub func {\nmylog \"Hello\";\n}\n\nfunc();\n\nprints\n\nmain::mylog Hello\n\nbut that's probably not what your application expects. Rather, you'd want\n\nmain::func Hello\n\nbecause the \"func\" function called your logging function.\n\nBut don't despair, there's a solution: Just register your wrapper package with Log4perl\nbeforehand. If Log4perl then finds that it's being called from a registered wrapper, it will\nautomatically step up to the next call frame.\n\nLog::Log4perl->wrapperregister(PACKAGE);\n\nsub mylog {\nmy($message) = @;\n\nDEBUG $message;\n}\n\nAlternatively, you can increase the value of the global variable $Log::Log4perl::callerdepth\n(defaults to 0) by one for every wrapper that's in between your application and \"Log::Log4perl\",\nthen \"Log::Log4perl\" will compensate for the difference:\n\nsub mylog {\nmy($message) = @;\n\nlocal $Log::Log4perl::callerdepth =\n$Log::Log4perl::callerdepth + 1;\nDEBUG $message;\n}\n\nAlso, note that if you're writing a subclass of Log4perl, like\n\npackage MyL4pWrapper;\nuse Log::Log4perl;\nour @ISA = qw(Log::Log4perl);\n\nand you want to call getlogger() in your code, like\n\nuse MyL4pWrapper;\n\nsub getlogger {\nmy $logger = Log::Log4perl->getlogger();\n}\n\nthen the getlogger() call will get a logger for the \"MyL4pWrapper\" category, not for the\npackage calling the wrapper class as in\n\npackage UserPackage;\nmy $logger = MyL4pWrapper->getlogger();\n\nTo have the above call to getlogger return a logger for the \"UserPackage\" category, you need to\ntell Log4perl that \"MyL4pWrapper\" is a Log4perl wrapper class:\n\nuse MyL4pWrapper;\nLog::Log4perl->wrapperregister(PACKAGE);\n\nsub getlogger {\n# Now gets a logger for the category of the calling package\nmy $logger = Log::Log4perl->getlogger();\n}\n\nThis feature works both for Log4perl-relaying classes like the wrapper described above, and for\nwrappers that inherit from Log4perl use Log4perl's getlogger function via inheritance, alike.\n",
            "subsections": []
        },
        "Access to Internals": {
            "content": "The following methods are only of use if you want to peek/poke in the internals of\nLog::Log4perl. Be careful not to disrupt its inner workings.\n\n\"Log::Log4perl->appenders()\"\nTo find out which appenders are currently defined (not only for a particular logger, but\noverall), a \"appenders()\" method is available to return a reference to a hash mapping\nappender names to their Log::Log4perl::Appender object references.\n",
            "subsections": []
        },
        "Dirty Tricks": {
            "content": "",
            "subsections": [
                {
                    "name": "infiltrate_lwp",
                    "content": "The famous LWP::UserAgent module isn't Log::Log4perl-enabled. Often, though, especially when\ntracing Web-related problems, it would be helpful to get some insight on what's happening\ninside LWP::UserAgent. Ideally, LWP::UserAgent would even play along in the Log::Log4perl\nframework.\n\nA call to \"Log::Log4perl->infiltratelwp()\" does exactly this. In a very rude way, it pulls\nthe rug from under LWP::UserAgent and transforms its \"debug/conn\" messages into \"debug()\"\ncalls of loggers of the category \"LWP::UserAgent\". Similarly, \"LWP::UserAgent\"'s \"trace\"\nmessages are turned into \"Log::Log4perl\"'s \"info()\" method calls. Note that this only works\nfor LWP::UserAgent versions < 5.822, because this (and probably later) versions miss\ndebugging functions entirely.\n\nSuppressing 'duplicate' LOGDIE messages\nIf a script with a simple Log4perl configuration uses logdie() to catch errors and stop\nprocessing, as in\n\nuse Log::Log4perl qw(:easy) ;\nLog::Log4perl->easyinit($DEBUG);\n\nshakyfunction() or LOGDIE \"It failed!\";\n\nthere's a cosmetic problem: The message gets printed twice:\n\n2005/07/10 18:37:14 It failed!\nIt failed! at ./t line 12\n\nThe obvious solution is to use LOGEXIT() instead of LOGDIE(), but there's also a special tag\nfor Log4perl that suppresses the second message:\n\nuse Log::Log4perl qw(:noextralogdiemessage);\n\nThis causes logdie() and logcroak() to call exit() instead of die(). To modify the script\nexit code in these occasions, set the variable $Log::Log4perl::LOGEXITCODE to the desired\nvalue, the default is 1.\n\nRedefine values without causing errors\nLog4perl's configuration file parser has a few basic safety mechanisms to make sure\nconfigurations are more or less sane.\n\nOne of these safety measures is catching redefined values. For example, if you first write\n\nlog4perl.category = WARN, Logfile\n\nand then a couple of lines later\n\nlog4perl.category = TRACE, Logfile\n\nthen you might have unintentionally overwritten the first value and Log4perl will die on\nthis with an error (suspicious configurations always throw an error). Now, there's a chance\nthat this is intentional, for example when you're lumping together several configuration\nfiles and actually *want* the first value to overwrite the second. In this case use\n\nuse Log::Log4perl qw(:nostrict);\n\nto put Log4perl in a more permissive mode.\n\nPrevent croak/confess from stringifying\nThe logcroak/logconfess functions stringify their arguments before they pass them to Carp's\ncroak/confess functions. This can get in the way if you want to throw an object or a hashref\nas an exception, in this case use:\n\n$Log::Log4perl::STRINGIFYDIEMESSAGE = 0;\n\neval {\n# throws { foo => \"bar\" }\n# without stringification\n$logger->logcroak( { foo => \"bar\" } );\n};\n"
                }
            ]
        },
        "EXAMPLE": {
            "content": "A simple example to cut-and-paste and get started:\n\nuse Log::Log4perl qw(getlogger);\n\nmy $conf = q(\nlog4perl.category.Bar.Twix         = WARN, Logfile\nlog4perl.appender.Logfile          = Log::Log4perl::Appender::File\nlog4perl.appender.Logfile.filename = test.log\nlog4perl.appender.Logfile.layout = \\\nLog::Log4perl::Layout::PatternLayout\nlog4perl.appender.Logfile.layout.ConversionPattern = %d %F{1} %L> %m %n\n);\n\nLog::Log4perl::init(\\$conf);\n\nmy $logger = getlogger(\"Bar::Twix\");\n$logger->error(\"Blah\");\n\nThis will log something like\n\n2002/09/19 23:48:15 t1 25> Blah\n\nto the log file \"test.log\", which Log4perl will append to or create it if it doesn't exist\nalready.\n",
            "subsections": []
        },
        "INSTALLATION": {
            "content": "If you want to use external appenders provided with \"Log::Dispatch\", you need to install\n\"Log::Dispatch\" (2.00 or better) from CPAN, which itself depends on \"Attribute-Handlers\" and\n\"Params-Validate\". And a lot of other modules, that's the reason why we're now shipping\nLog::Log4perl with its own standard appenders and only if you wish to use additional ones,\nyou'll have to go through the \"Log::Dispatch\" installation process.\n\nLog::Log4perl needs \"Test::More\", \"Test::Harness\" and \"File::Spec\", but they already come with\nfairly recent versions of perl. If not, everything's automatically fetched from CPAN if you're\nusing the CPAN shell (CPAN.pm), because they're listed as dependencies.\n\n\"Time::HiRes\" (1.20 or better) is required only if you need the fine-grained time stamps of the\n%r parameter in \"Log::Log4perl::Layout::PatternLayout\".\n\nManual installation works as usual with\n\nperl Makefile.PL\nmake\nmake test\nmake install\n",
            "subsections": []
        },
        "DEVELOPMENT": {
            "content": "Log::Log4perl is still being actively developed. We will always make sure the test suite\n(approx. 500 cases) will pass, but there might still be bugs. please check\n<http://github.com/mschilli/log4perl> for the latest release. The api has reached a mature\nstate, we will not change it unless for a good reason.\n\nBug reports and feedback are always welcome, just email them to our mailing list shown in the\nAUTHORS section. We're usually addressing them immediately.\n",
            "subsections": []
        },
        "REFERENCES": {
            "content": "[1] Michael Schilli, \"Retire your debugger, log smartly with Log::Log4perl!\", Tutorial on\nperl.com, 09/2002, <http://www.perl.com/pub/a/2002/09/11/log4perl.html>\n\n[2] Ceki Gülcü, \"Short introduction to log4j\", <http://logging.apache.org/log4j/1.2/manual.html>\n\n[3] Vipan Singla, \"Don't Use System.out.println! Use Log4j.\",\n<http://www.vipan.com/htdocs/log4jhelp.html>\n\n[4] The Log::Log4perl project home page: <http://log4perl.com>\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "Log::Log4perl::Config, Log::Log4perl::Appender, Log::Log4perl::Layout::PatternLayout,\nLog::Log4perl::Layout::SimpleLayout, Log::Log4perl::Level, Log::Log4perl::JavaMap\nLog::Log4perl::NDC,\n",
            "subsections": []
        },
        "AUTHORS": {
            "content": "Please contribute patches to the project on Github:\n\nhttp://github.com/mschilli/log4perl\n\nSend bug reports or requests for enhancements to the authors via our\n\nMAILING LIST (questions, bug reports, suggestions/patches): log4perl-devel@lists.sourceforge.net\n\nAuthors (please contact them via the list above, not directly): Mike Schilli\n<m@perlmeister.com>, Kevin Goess <cpan@goess.org>\n\nContributors (in alphabetical order): Ateeq Altaf, Cory Bennett, Jens Berthold, Jeremy Bopp,\nHutton Davidson, Chris R. Donnelly, Matisse Enzer, Hugh Esco, Anthony Foiani, James FitzGibbon,\nCarl Franks, Dennis Gregorovic, Andy Grundman, Paul Harrington, Alexander Hartmaier, David Hull,\nRobert Jacobson, Jason Kohles, Jeff Macdonald, Markus Peter, Brett Rann, Peter Rabbitson, Erik\nSelberg, Aaron Straup Cope, Lars Thegler, David Viner, Mac Yang.\n",
            "subsections": []
        },
        "LICENSE": {
            "content": "Copyright 2002-2013 by Mike Schilli <m@perlmeister.com> and Kevin Goess <cpan@goess.org>.\n\nThis library is free software; you can redistribute it and/or modify it under the same terms as\nPerl itself.\n",
            "subsections": []
        }
    },
    "summary": "Log::Log4perl - Log4j implementation for Perl",
    "flags": [],
    "examples": [
        "A simple example to cut-and-paste and get started:",
        "use Log::Log4perl qw(getlogger);",
        "my $conf = q(",
        "log4perl.category.Bar.Twix         = WARN, Logfile",
        "log4perl.appender.Logfile          = Log::Log4perl::Appender::File",
        "log4perl.appender.Logfile.filename = test.log",
        "log4perl.appender.Logfile.layout = \\",
        "Log::Log4perl::Layout::PatternLayout",
        "log4perl.appender.Logfile.layout.ConversionPattern = %d %F{1} %L> %m %n",
        ");",
        "Log::Log4perl::init(\\$conf);",
        "my $logger = getlogger(\"Bar::Twix\");",
        "$logger->error(\"Blah\");",
        "This will log something like",
        "2002/09/19 23:48:15 t1 25> Blah",
        "to the log file \"test.log\", which Log4perl will append to or create it if it doesn't exist",
        "already."
    ],
    "see_also": []
}