Groovy Script - Logback configuration unawaited behaviour - grails

I want to use Logback as my logging framework within Grails. therefore I set up everything in place to work but my implementation fails on the configuration file itself. the reason is, as I guess, somewhere whithin the scoping of Groovy Script but I'm not able to figure it out...
if I define my String properties without any identifier which I want to use later I get a warning that it may not be accessed. For example:
LOG_DIR = 'c:/temp/myproject/logs/'
BACKUP_DIR = LOG_DIR + 'backup/'
appender('F_MAIN', RollingFileAppender) {
file = LOG_DIR + 'test.log'
rollingPolicy(FixedWindowRollingPolicy) {
fileNamePattern = BACKUP_DIR + 'test.%d{yyyy-MM-dd}.%i.log.zip'
// .... and so on
}
}
I get the following error message from Logback, which I'm pretty sure is indicating that both LOG_DIR and BACKUP_DIR can not be reached:
13:33:32,036 |-ERROR in ch.qos.logback.classic.gaffer.AppenderDelegate#6fd00b - Appender [F_MAIN] of type [ch.qos.logback.core.rolling.RollingFileAppender] has no appplicable [LOG_DIR] property
13:33:32,068 |-ERROR in ch.qos.logback.classic.gaffer.ComponentDelegate#788ac3 - Component of type [ch.qos.logback.core.rolling.FixedWindowRollingPolicy] has no appplicable [BACKUP_DIR] property
I also tried the following approach by declaring both variables with the #Field tag, but it still does not work:
#Field String LOG_DIR = 'c:/temp/myproject/logs/'
#Field String BACKUP_DIR = LOG_DIR + 'backup/'
appender('F_MAIN', RollingFileAppender) {
file = LOG_DIR + 'test.log'
rollingPolicy(FixedWindowRollingPolicy) {
fileNamePattern = BACKUP_DIR + 'test.%d{yyyy-MM-dd}.%i.log.zip'
// .... and so on
}
}
what am I doing wrong here?

oh my!
after searching and a lot of trial/error I found the solution and it was so close and definitely seems obvious now: I had to declare both variables with def, so now they are visible throughout the whole script ;)
For example, this is working code:
def LOG_DIR = 'c:/temp/myproject/logs/'
def BACKUP_DIR = LOG_DIR + 'backup/'
appender('F_MAIN', RollingFileAppender) {
file = LOG_DIR + 'test.log'
rollingPolicy(FixedWindowRollingPolicy) {
fileNamePattern = BACKUP_DIR + 'test.%d{yyyy-MM-dd}.%i.log.zip'
// .... and so on
}
}
now, I'm also able to use a function like this within my script:
def createFilename(String directory, String name, boolean isBackupFile) {
String filename = ''
if(isBackupFile) {
filename = "${directory}backup/MyProject-${name}.%d{yyyy-MM-dd}.%i.log.zip"
} else {
filename = "${directory}MyProject-${name}.log"
}
return filename
}
def fileAppenderLog = createFilename(LOG_DIR, 'output', false)
def fileAppenderLogBackup = createFilename(LOG_DIR, 'output', true)
appender('F_MAIN', RollingFileAppender) {
file = fileAppenderLog
rollingPoliciy(FixedWindowRollingPolicy) {
fileNamePattern = fileAppenderLogBackup
// .... and so on
}
}
which is pretty useful, I think :), especially if you want to declare a bunch of different logfiles and even if you want to declare temporary logfiles which are created when Logback is rescanning this file ...

Related

Unable to split the list of files

I am having list of files in a directory.
For Ex:
sample1.properties
sample2.properties
sample3.properties
I am trying to use the groovy code to push these values in the Jenkins Active Choices parameter. How can I populate this list without ".properties" at the end. My list of Active choices parameters needs to be like this:
sample1
sample2
sample3
Code I am using is:
def reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))
def results = new JsonSlurper().parseText(reader.getText());
reader.close()
data= results.tree.path
data.each {
it -> if(it.endsWith(".properties"))
choices.push(it.replace("/","") )
}
choices=choices.sort()
choices.add(0,"SELECT")
return choices
Simply replacing the .properties part will not work?
choices.push(it.replace("/","").replace(".properties", ""))
If my assumption regarding your results.tree.path content is correct, then you should probably use something like that:
def data = [
'some/complex/path/sample1.properties',
'some/complex/path/some_irrelevant_file.txt',
'some/complex/path/sample2.properties',
'some/complex/path/sample3.properties'
]
data.findAll { it.endsWith('.properties') }
.collect { it.split('/').last().replace('.properties', '') }
.each { println it }
so, in your case, you need to do:
results.tree.path.findAll { it.endsWith('.properties') }
.collect { it.split('/').last().replace('.properties', '') }
.each { choices.push(it) }

How to get the file extension in grails?

I recently started working on grails and i want to know how to get the
extension of a file. Ex: test.txt. I want to check extension(txt)?
any clue?
Here's another way. Using a regular expression.
def fileName = 'something.ext'
def matcher = (fileName =~ /.*\.(.*)$/)
if(matcher.matches()) {
def extension = matcher[0][1]
if(extension in ['jpg', 'jpeg', 'png']) {
// Good to go
println 'ok'
} else {
println 'not ok'
}
} else {
println 'No file extension found'
}
The question asks how to get the file extension.
With groovy, the following operation will give you the file extension of any file name:
def fileName = ...
def fileExt = fileName - ~/.*(?<=\.)/
The accepted answer goes a bit further and tries to check for specific file extensions. You can use the match operator ==~ to do this as well:
assert fileName ==~ ~/.*(?<=\.)(txt|jpe?g|png)/
This assertion will work provided the file name ends with one of the supplied extensions.
Also noticed that groovy can do positive lookbehind using (<?\.)
Hope i found the answer of my Question. How to find the extension
of a file.
String fileName = "something.ext";
int a = fileName.lastIndexOf(".");
String extName = fileName.substring(a);
System.out.println(fileName.substring(a));
ArrayList<String> extList = new ArrayList<String>();
extList.add("jpg");
extList.add("jpeg");
extList.add("png");
if(extList.contains(extName))
{
System.out.println("proceed");
}
else{
System.out.println("throw exception");
}
Lsat comment at this post

Grails config file returning empty object instead of string

I am trying to read a string in from an external config file, but am for some reason only getting an empty object. Here is the config file (DirectoryConfig.groovy)
directory {
logDirectory = "c:\\opt\\tomcat\\logs\\"
}
And the code that retrieves the directory (from a controller):
String dirName = grailsApplication.config.directory.logDirectory
File directory = new File(dirName)
For some reason, dirName always ends up being "{}", and as a result the file cannot be read. What am I doing wrong here?
Creating DirectoryConfig.groovy in your grails-app/conf/ directory will not work by convention.
You should consider implementing solution that is recommended for externalizing Grails configuration - delivering .groovy or .properties files from classpath or filesystem. Take a look at commented code in Config.groovy:
// grails.config.locations = [ "classpath:${appName}-config.properties",
// "classpath:${appName}-config.groovy",
// "file:${userHome}/.grails/${appName}-config.properties",
// "file:${userHome}/.grails/${appName}-config.groovy"]
It's very common way to provide configuration files that depend on runtime property:
// if (System.properties["${appName}.config.location"]) {
// grails.config.locations << "file:" + System.properties["${appName}.config.location"]
// }
I often use something like this (it's part of the Config.groovy file):
grails.config.locations = []
grails.project.config.type = "classpath"
grails.project.config.extension = "groovy"
environments {
development {
grails.project.config.file = "development-config.${grails.project.config.extension}"
}
test {
grails.project.config.file = "test-config.${grails.project.config.extension}"
}
}
if (System.properties["grails.config.type"]) {
grails.project.config.type = System.properties["grails.config.type"]
}
if (System.properties["grails.config.file"]) {
grails.project.config.file = System.properties["grails.config.file"]
}
grails.config.locations << "${grails.project.config.type}:${grails.project.config.file}"
By default it assumes that there is e.g. development-config.groovy file in the classpath, but I can simply change it by setting -Dgrails.config.file=/etc/development.properties -Dgrails.config.type=file in Java runtime so it uses /etc/development.properties file instead of the default one.
If you would like to run your example in the simplest way, you will have to do:
1) put your DirectoryConfig.groovy in the classpath source e.g. src/java (attention: it wont work if you put your file in src/groovy)
2) define in your Config.groovy:
grails.config.locations = [
"classpath:DirectoryConfig.groovy"
]
3) re-run your application. grailsApplication.config.directory.logDirectory should now return the value you expect.
For more information about externalizing configuration go to http://grails.org/doc/latest/guide/conf.html#configExternalized

create grails custom ResourceMapper

I created the following resource mapper using the instructions from the resources plugin:
import org.grails.plugin.resource.mapper.MapperPhase
import org.apache.commons.logging.LogFactory
class VersionResourceMapper {
def phase = MapperPhase.MUTATION
def log = LogFactory.getLog(this.class)
static defaultIncludes = [ '/js/**' ]
def map(resource, config) {
def query = [v:'1.01']
resource.actualUrl = resource.actualUrl + '?' + query.collect { it }.join('&')
//resource.updateActualUrlFromProcessedFile()
if (log.debugEnabled) log.debug "Modified URL: ${resource.actualUrl}"
log.info "Modified URL: ${resource.actualUrl}"
}
}
The file is located in grails-app/resourceMappers
My class never even gets called. I have a debug breakpoint set which is never hit. Is there some other configuration that has to be set?
remove this line
static defaultIncludes = [ '/js/**' ]
and check if your breakpoint is hit. It looks like it is just not finding the js directory.
If that works change the above line to
static defaultIncludes = [ 'js/**' ]
I'm pretty sure that you need to change
def phase = MapperPhase.MUTATION
to
static phase = MapperPhase.MUTATION

Grails External Configuration. Can't access to external variable. Getting always [:]

I can't have my 'folder' external variable working. Always I'm getting [:].
I'm developing on Grails under Windows (this is why the external configuration file looks like file:C:\path\to/file).
I'm using external configuration in another project without problems, in the same way that I'm showing below.
I have this:
Config.groovy:
environments {
development {
grails.config.locations = [ "file:${userHome}/.grails/${appName}-config.groovy" ]
}
}
myApp-config.groovy:
stats.feed.wsdl.folder = '/static'
Controller and Service:
class WsdlController {
def wsdlService
def index = {
wsdlService.getEventsSchedule()
}
}
class WsdlService {
def grailsApplication
def getEventsSchedule = {
println "Locations: ${grailsApplication.config.grails.config.locations}"
println "Folder: ${grailsApplication.config.stats.feed.wsdl.folder}"
}
}
Console:
Locations: [file:C:\Users\myUser/.grails/myApp-config.groovy]
Folder: [:]
Any clue?
Thanks!
Updated!
This is the whole myApp-config.groovy:
println 'Start'
stats.feed.wsdl.folder = "/stats"
println 1
stats.feed.wsdl.folder.events = "${stats.feed.wsdl.folder}/events"
println 2
stats.feed.wsdl.folder.teams = "${stats.feed.wsdl.folder}/teams"
println 'End'
This is not working, the console shows:
Start
1
But if I change the variable names, it works.
println 'Start'
stats.feed.wsdl.folder = "${playcall.static.resources.folder}/stats"
println 1
stats.feed.wsdl.events.folder = "${stats.feed.wsdl.folder}/events"
println 2
stats.feed.wsdl.teams.folder = "${stats.feed.wsdl.folder}/teams"
println 'End'
Console:
Start
1
2
End
You create a property and declared this as a string:
stats.feed.wsdl.folder = "/stats"
In that way you isnt't able to add subproperties. So, to keep something close to what you want, you can do this:
stats.feed.wsdl.folder.base = "/stats"
stats.feed.wsdl.folder.events = "${stats.feed.wsdl.folder.base}/events"
stats.feed.wsdl.folder.teams = "${stats.feed.wsdl.folder.base}/teams"

Resources