Utilizing log4j for logging in my application has been beneficial. I am now exploring the option to automatically delete compressed files when the filesystem reaches 80 percent usage. While log4j lacks a built-in appender for this task, it does offer the ScriptCondition feature as a workaround. Although the official log4j documentation suggests using Groovy scripts (which we currently do not have installed), it also mentions that JavaScript and Nashorn can be viable alternatives. To experiment, I created a simple test script.
<configuration status="trace" name="REST Servlet Logging Configuration">
<Properties>
<Property name="xx">xx</Property>
</Properties>
<appenders>
<RollingFile name="xx"
fileName="xx"
filePattern="xx.log.%i.gz" append="true"
bufferedIO="true" immediateFlush="false" fileOwner="xx"
fileGroup="xx" filePermissions="rw-r-----">
<Policies>
<SizeBasedTriggeringPolicy size="4 MB" />
</Policies>
<DefaultRolloverStrategy max="100" fileIndex="min">
<Delete basePath="${xx}" maxDepth="1">
<ScriptCondition>
<Script name="superstitious" language="javascript"><![CDATA[
var exec = require('child_process');
exec("df -h / | tail -1 | tr -s ' ' | cut -d' ' -f4", (error, stdout, stderr) => {
if(error) {
console.log('error: ${error.message}');
return;
}
if(stderr) {
console.log('stderr: ${stderr}');
return;
}
console.log('stdout: ${stdout}');
statusLogger.trace("stdout in trace :${stdout}");
});
statusLogger.trace("running javascript");
result;
]]>
</Script>
</ScriptCondition>
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
While the logs confirm the mention of JavaScript, an error occurs relating to Nashorn instead.
05:58:46 UTC 2021 DEBUG createScript(name="superstitious", language="javascript", scriptText="var exec = require('child_process');
2021-11-02T05:58:47.197Z exec("df -h / | tail -1 | tr -s ' ' | cut -d' ' -f4", (error, stdout, stderr) => {
...
...
The issue persists with the compilation of Nashorn scripts despite specifying JavaScript. The difference between both scripting languages perplexes me as a beginner.
In response to suggestions, changing => to function triggers another exception.
2021-12-02T06:56:30.192Z 2021-02-12 06:56:30,185 Log4j2-TF-1-RollingFileManager-2 ERROR Error running script superstitious javax.script.ScriptException: ReferenceError: "require" is not defined in <eval> at line number 1
...
...