使用Groovy初始化Jenkins Audit Trail插件时遇实例化错误
Looks like the error pops up because LogFileAuditLogger doesn't have a no-argument constructor—Jenkins tries to use this empty constructor when deserializing your JSONObject, which fails. Instead of relying on reflective instantiation via JSON, you should directly build the logger instance with its required parameters, then pass it to the plugin's configuration properly.
Root Cause Breakdown
The error stack trace points to java.lang.NoSuchMethodException: hudson.plugins.audit_trail.LogFileAuditLogger.<init>(), meaning Jenkins can't create a logger instance using an empty constructor. Checking the Audit Trail plugin's code reveals that LogFileAuditLogger requires explicit parameters (log path, rotation limit, count, etc.) for its constructor and doesn't support no-arg instantiation.
Corrected Groovy Script
Here's the fixed version of your script that properly constructs the logger and configures the plugin:
import hudson.plugins.audit_trail.AuditTrailPlugin import hudson.plugins.audit_trail.LogFileAuditLogger import jenkins.model.Jenkins // Fetch the Audit Trail plugin instance def auditTrailPlugin = Jenkins.getInstance().getPlugin(AuditTrailPlugin.class) println("Starting Audit Trail plugin configuration...") // Directly create LogFileAuditLogger with correct parameter types // Important: limit and count are integers, not strings! def logger = new LogFileAuditLogger( "Vibin", // Path to the audit log file 1, // Max log size in MB (rotation limit) 2, // Number of rotated log files to keep true // Enable logging build causes ) // Access and update the plugin's configuration def pluginConfig = auditTrailPlugin.getDescriptor().getConfig() pluginConfig.setLoggers([logger]) pluginConfig.setLogBuildCause(true) pluginConfig.setPattern("") // Keep your empty pattern setting // Save the updated configuration to Jenkins auditTrailPlugin.getDescriptor().setConfig(pluginConfig) Jenkins.getInstance().save() println("Audit Trail plugin configured successfully!")
Key Improvements:
- Explicit Instance Creation: We skip the JSONObject approach and directly initialize
LogFileAuditLoggerwith its required constructor parameters. Note thatlimitandcountare integers (your original script passed them as strings, which would have caused another error even if the constructor worked). - Descriptor-Based Configuration: We use the plugin's descriptor to fetch and modify the configuration, then persist changes by saving the Jenkins instance.
- Type Safety: Ensures all parameters match the types expected by the logger class.
Verification
To confirm the configuration worked, you can add this line at the end of the script to print the plugin's config XML:
println(auditTrailPlugin.getConfigXml().asString())
Or check the Audit Trail plugin settings directly in the Jenkins UI.
内容的提问来源于stack exchange,提问作者Ciado

