TimeBasedRollingPolicy with no date appended - logback

I want to use a TimeBasedRollingPolicy; however, for legacy reasons (c to java port) the log file name already has a date appended, like so: "log.20130813". Other downstream processes depend on the date already being on the filename. When it rolls I want it to be compressed but with no further date appended to it. Is this possible?
I have tried this:
def date = timestamp("yyyyMMdd")
def logFileName = "log.${date}"
appender("LOG", RollingFileAppender) {
file = logFileName
append = true
rollingPolicy(TimeBasedRollingPolicy) {
fileNamePattern = "${logFileName}.%d{}.gz"
}
encoder(PatternLayoutEncoder) {
pattern = "%msg%n"
}
}
However, the empty date string just causes it to use its default so it ends up like this:
log.20130805.2013-08-05.gz
I really would like it to end up like:
log.20130805.gz

In Curly braces. Add format like %d{yyyy-MM-dd}.
You can also do in this manner :
${filename}.%d{yyyy-MM-dd}.%i.log.gz
Then the output would be : filename.2013-03-15.0.log.gz

Related

Why does Coldfusion add an extra quote to each existing quote in cflog?

Trying to save info to the logs using cflog, and save in JSON format. But for some reason, an extra dbl-quote is getting added next to each already existing dbl-quote.
Example: I do something like this, turning a simple struct into a JSON string:
<cfset local.fname = "Max">
<cfset local.lname = "Smith">
<cfset local.id = "QA-123">
<cflog text="#serializeJSON(local)#">
And in the logs, it gets saved to look like:
"INFO","http-apr-8888-exec-6","10/04/2021","19:24:46","","{""fname"":""Max"",""lname"":""Smith"",""id"":""QA-123""}"
Then if I try to save it this way, I get no quotes, and thus invalid JSON.
<cflog text='{fname:Max,lname:smith,id:QA-123}'>
results in:
"INFO","http-apr-8888-exec-6","10/04/2021","19:24:46","","{fname:Max,lname:Smith,id:QA-123}"
And
<cflog text='{"fname":"Max","lname":"smith","id":"QA-123"}'>
results in the same as the first example:
"INFO","http-apr-8888-exec-6","10/04/2021","19:24:46","","{""fname"":""Max"",""lname"":""Smith"",""id"":""QA-123""}"
Why is it doing this, and how do I end up with the log entry I want, without any extra quotes?:
"INFO","http-apr-8888-exec-6","10/04/2021","19:24:46","","{"fname":"Max","lname":"Smith","id":"QA-123"}"
We're running CF10 (older version because we're phasing out of CF), and viewing the logs through Splunk. Not sure if Splunk is a CSV parser, but figured out a way to get the logs written as desired.
Created a function named writeLog(), using Java sys.out.println instead of the cflog tag:
<cfscript>
function writeLog(required message) {
var logString = serializeJSON(arguments);
sys.out.println('{"timestamp":"#dateTimeFormat(now(), "yyyy-mm-dd'T'hh:mm:ss:ssssssZ")#",#Right(logString, Len(logString) - 1)#');
}
</cfscript>
And then call it like so:
<cfscript>
var emailData = structNew();
emailData.toAddress = ARGUMENTS.to;
emailData.fromAddress = ARGUMENTS.from;
emailData.subject = ARGUMENTS.subject;
APPLICATION.general.writeLog(message="Sending email", argumentCollection=emailData);
</cfscript>
And (with some adjustments to Splunk) the resulting log looks like:
{
FROMADDRESS: no-reply#blah.com
SUBJECT: Welcome to the team
TOADDRESS: someone#example.com
message: Sending email
timestamp: 2021-10-05T11:10:21:000021-0400
}
I've go through your issue. Yes we have this from Coldfusion 11, Coldfusion 2016. But not in Coldfusion 2018 ( Update 12 ). May be they fixed this case in recent updates about Coldfusion 2018.
Please try to update your version up to date then check with these issue.
But for now, I can give you some solution by using replace() method.
Sample Code :
<cfset myStr = {} >
<cfset myStr.fname = "Kannan">
<cfset myStr.lname = "Pasumpon">
<cfset myStr.id = "CF-123">
<cfset jsonData = replace(serializeJSON( myStr ), '"',"'","All")>
<cflog text="#jsonData#" file="testingWorks">
Here I just replace all my double quotes value with single quotes. And logged it in testingWorks.log file. The new result will be like below,
Result In Log File :
"Information","http-nio-8501-exec-6","10/05/21","12:21:04","","{'LNAME':'Pasumpon','ID':'CF-123','FNAME':'Kannan'}"
Likewise, You can achieve the this things as per your needs.
Note : The update version resolved this case by default. So I would suggest that update your version first instead of changed / replace the notations.

Fetch records with query Args in Go

I Need help for fetch records from table using Go.
My Problem is that i'm writing MySQL query and add another where clause i.e HPhone number, Here HPhone number inserted in data base with format like 999-999-9999.And i passed this HPhone Number in format like 9999999999. which is not matching with correct data base field value. And i used SUBSTRING for add hyphen between numbers but it does not get records but when i passed like 999-999-9999 without SUBSTRING it return records.
Here i demonstrate how i used this.
strQry = `SELECT * from table WHERE Depot = ?`
if HPhone != "" {
strQry += ` AND HPhone = ?`
}
queryArgs := []interface{}{RouteAvailability.Depot}
if HPhone != "" {
queryArgs = append(queryArgs, "SUBSTRING("+HPhone+",1,3)"+"-"+"SUBSTRING("+HPhone+",4,3)"+"-"+"SUBSTRING("+HPhone+",7,4)")
}
Help would be appreciated.
Thanks in advance.
Instead of SUBSTRING you can use REPLACE like so:
queryArgs := []interface{}{RouteAvailability.Depot}
if HPhone != "" {
strQry += ` AND REPLACE(HPhone, '-', '') = ?`
queryArgs = append(queryArgs, HPhone)
}
If possible I would suggest you normalize your data, i.e. decide on a canonical format for a particular data type and everytime your program receives some input that contains that data type you format it into its canonical form, that way you can avoid having to deal with SUBSTRING, or REPLACE, or multiple inconsistent formats etc.
This won't work as you are using prepared statements, and the argument you are building when HPhone is not empty will be used in escaped form - so when executing the query, it won't compare the HPhone values with the computed result of some substring, but with a string containing SUBSTRING(9999...

Rails: "Mysql2::Error: Incorrect string value:" when trying to save "params.inspect"

I am trying to save to database the output of params (I am saving this: params.inspect) - here's an example of the string that's supposed to be saved:
> {\"utf8\"=>\"✓\", \"_method\"=>\"patch\", \"authenticity_token\"=>\"fpQC8FY8+qztD41jjcFSJRars539KRshw/vczmmJd9Q=\",
> \"car\"=>{\"role_type\"=>\"1\", \"admin_id\"=>\"67\",
> \"branch_id\"=>\"1\", \"template_id\"=>\"21\", \"cost\"=>\"0.00\",
> \"carrier_additional_cost\"=>\"0.00\", ...
First, I tried to save the params like this:
all_params = params.except(:controller, :action).inspect
but it didn't work out. So:
all_params = params.except(:controller, :action).inspect.encode("iso-8859-1")
Also this:
all_params = params.except(:controller, :action).inspect.encode("iso-8859-1").force_encoding("utf-8")
returns the same error.
How to properly save the output from params.inspect?
The column where I try to save this data is text, not string.
Thank you
Try using params instead of params.inspect.
A sample output of params is
{"controller"=>"users", "action"=>"show", "id"=>"1"}
which is a hash which I think is what you want to save in your database.

PHP force a var to have a certain type

This may be a stupid question but I might aswell as it :)
is there away to force
$tel1 = '05';// string
settype($tel1,'string');
$tel1 = 06;//either throw error, or convert it to string automatically.
var_dump($tel1);//(string [2]) 05
The above code is of the top of my head so might not be accurate but I need to keep a variable as a string not numeric, because of some silly thing I have done, now my phone numbers lose the leading 0s :-(
n I cn't rewrite it because it will mess up with other numeric types,b4 u ask it was an automated service for db to check if it was a numeric value or not,
UPDATE
This is the problem
function escape($str){
if(is_numeric($str)){
return $str;
}else{
return "'".mysql_real_escape_string($str).'\'';
}
}
$tel1 = "06";
$sql = 'SELECT * FROM blabla WHERE id = '.escape($tel1).'';
//above is same as below
$sql = 'SELECT * FROM blabla WHERE id = 06 ';
I can't change anything inside the scape function because other inputes thruout the website are using this function, I dont wanna mess their validations.
Your use of is_numeric tests for numeric content, not an integer type. But then you take a variable called $str which implies you want it to be a string.
Perhaps use:
function escape($val) {
if (is_numeric($val) && !is_string($val)) {
return $val;
}
else{
return "'" . mysql_real_escape_string($val) . '\'';
}
}
Now strings will be escaped and quoted, but not if they contain only numeric content.
you can do something like:
$string = (string) $int;
or use a function
$string = strval($int);
You can't force a variable to a specific type in the global scope.
You can force Arrays and Objects in a function.
function getElementsByClassName(DOMNode $parentElement, Array $classNames) {
...
}
If you pass an object that is not an instantiation of DOMNode (or a subclass), or if you don't pass an Array as the second argument, you'll get an error.
You can of course cast any variable, e.g. (string) $tel1.
You shouldn't be treating phone numbers as Ints anyway, because of leading zeroes and possible parenthesis and dashes. Also, once your telephone number is an Int, it won't know its 0 padding anymore because it will be discarded, so casting it back won't give you the original String.
To cast a variable you can use something like:
$i = 1;
$s = (string) $i;
Depending on the db adaptor you might not be able to detect the type being returned from the database. I believe it's PDO that returns everything (even INT values) as strings.
The number_format() function may be of use to you too.
If you declare a variable as:
$var = 06;
it immediately becomes 6 without leading zero because leading zero when it comes to integers is meaningless and therefore it's cut out.
In other words, your variable has to be created as string, which is what you probably deduced yourself.
Quick fix would be the following: you can add another parameter to your escape() function.
For example:
function escape($str, $force_str = false)
{
if($force_str)
{
// do your conversion, the rest of the site will by default pass false so nothing will be broken
}
}
As alex said, start by making sure the phone number is never converted from string to int in your own code. Then, you need to make sure it will not be converted when sent to your SQL DB.
It ought to work if you do it this way:
$sql = "SELECT * FROM blabla WHERE id = '" . mysql_real_escape_string($tel1) . "'";
This is the same as
$sql = "SELECT * FROM blabla WHERE id = '06'";

Grails: can I make a validator apply to create only (not update/edit)

I have a domain class that needs to have a date after the day it is created in one of its fields.
class myClass {
Date startDate
String iAmGonnaChangeThisInSeveralDays
static constraints = {
iAmGonnaChangeThisInSeveralDays(nullable:true)
startDate(validator:{
def now = new Date()
def roundedDay = DateUtils.round(now, Calendar.DATE)
def checkAgainst
if(roundedDay>now){
Calendar cal = Calendar.getInstance();
cal.setTime(roundedDay);
cal.add(Calendar.DAY_OF_YEAR, -1); // <--
checkAgainst = cal.getTime();
}
else checkAgainst = roundedDay
return (it >= checkAgainst)
})
}
}
So several days later when I change only the string and call save the save fails because the validator is rechecking the date and it is now in the past. Can I set the validator to fire only on create, or is there some way I can change it to detect if we are creating or editing/updating?
#Rob H
I am not entirely sure how to use your answer. I have the following code causing this error:
myInstance.iAmGonnaChangeThisInSeveralDays = "nachos"
myInstance.save()
if(myInstance.hasErrors()){
println "This keeps happening because of the stupid date problem"
}
You can check if the id is set as an indicator of whether it's a new non-persistent instance or an existing persistent instance:
startDate(validator:{ date, obj ->
if (obj.id) {
// don't check existing instances
return
}
def now = new Date()
...
}
One option might be to specify which properties you want to be validated. From the documentation:
The validate method accepts an
optional List argument which may
contain the names of the properties
that should be validated. When a List
is passed to the validate method, only
the properties defined in the List
will be validated.
Example:
// when saving for the first time:
myInstance.startDate = new Date()
if(myInstance.validate() && myInstance.save()) { ... }
// when updating later
myInstance.iAmGonnaChangeThisInSeveralDays = 'New Value'
myInstance.validate(['iAmGonnaChangeThisInSeveralDays'])
if(myInstance.hasErrors() || !myInstance.save(validate: false)) {
// handle errors
} else {
// handle success
}
This feels a bit hacky, since you're bypassing some built-in Grails goodness. You'll want to be cautious that you aren't bypassing any necessary validation on the domain that would normally happen if you were to just call save(). I'd be interested in seeing others' solutions if there are more elegant ones.
Note: I really don't recommend using save(validate: false) if you can avoid it. It's bound to cause some unforeseen negative consequence down the road unless you're very careful about how you use it. If you can find an alternative, by all means use it instead.