Log4perl category as log file name - log4perl

I'm sure I'm being dim and missing the obvious but is there a simple way of using the current category as the filename in a config file without resorting to a subroutine call?
So that in the following one could use ${category}.log instead of repeating bin.nh.tpp in the filename line
log4perl.logger.**bin.nh.tpp**=INFO, BIN_NH_TPP_LOGFILE
log4perl.appender.BIN_NH_TPP_LOGFILE=Log::Log4perl::Appender::File
log4perl.appender.BIN_NH_TPP_LOGFILE.filename=${LOGS}/nh/**bin.nh.tpp**.log
log4perl.appender.BIN_NH_TPP_LOGFILE.mode=append
log4perl.appender.BIN_NH_TPP_LOGFILE.layout=PatternLayout
log4perl.appender.BIN_NH_TPP_LOGFILE.layout.ConversionPattern=[%d] %F{1} %L %c - %m%n

It's somewhat more involved than a subroutine, I'm afraid. Subroutines in l4p conf files allow for including variables known at conf file parsing time, e.g. the time/date or a user id. You can't modify log time behavior that way.
The easiest way I can think of right now to accomplish what you want is a custom appender like
package FileByCategoryAppender;
use warnings;
use strict;
use base qw( Log::Log4perl::Appender::File );
sub new {
my( $class, %options ) = #_;
$options{filename } = "no-category.log";
my $self = $class->SUPER::new( %options );
bless $self, $class;
}
sub log {
my( $self, %params ) = #_;
my $category = $params{ log4p_category };
$self->SUPER::file_switch( $category . ".log" );
$self->SUPER::log( %params );
}
1;
and then use it in your script like
use strict;
use warnings;
use Log::Log4perl qw( get_logger );
my $conf = q(
log4perl.category = WARN, Logfile
log4perl.appender.Logfile = FileByCategoryAppender
log4perl.appender.Logfile.create_at_logtime = 1
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 = get_logger("Bar::Twix");
$logger->error("twix error");
$logger = get_logger("Bar::Mars");
$logger->error("mars error");
which will result in two log files being created at log time:
# Bar.Mars.log
2012/11/18 11:12:12 t 21> mars error
and
# Bar.Twix.log
2012/11/18 11:12:12 t 21> twix error

Related

Convert a string into date in AIX unix

I need to extract the date part from a file in unix and add +1 day to the date and rename the file with the new date in it.
for ex:
sample file name: sample_file_name_01_31_2022_14_01_45_loadid.csv
I tried to extract the timestamp using substr which gives 01_31_2022_14_01_45. Now, the new date should be 02_01_2022_14_01_45 and the new file name should be sample_file_name_02_01_2022_14_01_45_loadid.csv
Given the AIX operating environment, which doesn't have GNU date installed by default (for the handy date -d ... functionality), I'd approach this problem with a perl script. The script below uses fairly common modules that should be available on an AIX system.
The basic idea behind the script is to loop over every given argument (one or more filenames) and:
extract the date/time fields from the filename
convert those fields into seconds-since-the epoch
add one day's worth of seconds
convert that new timestamp into the desired string format
rename the file
I encountered a slight complication while adding error-checking: the timelocal() function will croak (exit the script) if any of the given date/time fields are out of range. Because I wanted to be able to loop over any remaining arguments, I had to wrap that call in a Try-Catch block.
#!/usr/bin/perl -w
use strict;
use POSIX qw(strftime);
use Time::Local qw(timelocal);
use Try::Tiny;
sub rename_a_file {
my $filename = shift;
# extract date from filename
my ($prefix, $month, $day, $year, $hour, $minute, $second, $suffix);
unless (
($prefix, $month, $day, $year, $hour, $minute, $second, $suffix) =
$filename =~ /^(.*)_(\d{2})_(\d{2})_(\d{4})_(\d{2})_(\d{2})_(\d{2})_(.*)$/
) {
warn "Could not determine a timestamp from ${filename}; skipping\n";
return undef;
}
# local time in seconds-since-the-epoch
my $t;
# timelocal will die if any inputs are out of range; catch it
my $flag = 0;
try {
$t = timelocal($second, $minute, $hour, $day, $month - 1, $year - 1900);
} catch {
warn "Unable to convert time specification: $_";
$flag = 1;
};
return undef if $flag;
# add one day's worth of seconds
$t += 24 * 60 * 60;
# new timestamp in string format
my $newdate;
unless ($newdate = strftime("%m_%d_%Y_%H_%M_%S", localtime $t)) {
warn "Unable to convert new date to a string format: $!";
return undef;
}
# rename file using new date
unless (rename $filename, "${prefix}_${newdate}_${suffix}") {
warn "Unable to rename $filename: $!";
return undef;
}
return 1;
}
my $errors = 0;
for (#ARGV) {
unless (rename_a_file($_)) {
warn "Unable to rename: $_\n";
++$errors;
}
}
$errors = 255 if $errors > 255;
exit $errors;

ORA-6502, from WEB

I have a problem with Oracle DB.
<?php
require_once 'includes/conn.php';
function connect_db()
{
if ($c=oci_pconnect(uname,pwd, host,'AL32UTF8'))
return $c;
else
die( "ERROR");
}
$conn=connect_db();
$query = "BEGIN :ds_id :=DS.REG_DS1(:F_NAME);END;";
$stmt=oci_parse($conn,$query);
$f_name='John Doe';
$ds_id=-1;
oci_bind_by_name($stmt, ":ds_id", $ds_id);
oci_bind_by_name($stmt, ":F_NAME", $f_name);
if(oci_execute($stmt))
{
echo 'good';
}
else
print_r(oci_error($stmt));
?>
Here is function REG_DS1
FUNCTION REG_DS1(F_NAME IN VARCHAR) RETURN NUMBER AS
DS_ID NUMBER(8,0):=9988;
BEGIN
-- INSERT INTO TEST VALUES(F_NAME,SYSDATE);
RETURN DS_ID;
END REG_DS1;
When I try to execute this function from Sql Developer, it runs with no problem.
But if I execute from PHP script above, it gives me error:
ORA-06502: PL/SQL: numeric or value error: character string buffer too small ORA-06512: at line 1 [offset] => 0 [sqltext] => BEGIN :ds_id :=DS.REG_DS1(:F_NAME);END; )
If i change DS_ID variable to another number less than 100, it works great from both. but if i set it to a number more than 99, it gets me error from php script.
What can be a problem?
--jst idea and this is not solutioN
variable decleration or some defination problem
oci_connect($ODBuser,$ODBpass,$ODBhost,$db_charset);
should try like this
not like
oci_pconnect(uname,pwd, host,'AL32UTF8')
sample code :
-- just idea
<?php
$file = "../script/param.CML";
$encryptObj = new cast128;
$encryptObj->setkey("SABBIllustrateKey");
$fp=fopen($file,'r');
$strContent = fread($fp, filesize($file));
fclose($fp);
$strContent=$encryptObj->decrypt($strContent);
$ArConnect=split(" ",$strContent);
$OraService=$ArConnect[8];
$OraUser=$ArConnect[9];
$OraDBpass=$ArConnect[10];
$db_charset = 'AL32UTF8';
$cursor=oci_connect($OraUser,$OraDBpass,$OraService,$db_charset);
if(!$cursor)
{
echo "<br>Error In connection:- reason<BR>";
$e = oci_error(); // For oci_connect errors pass no handle
}
?>
<?php
$file = "../script/param.CML";
$encryptObj = new cast128;
$encryptObj->setkey("SABBIllustrateKey");
$fp=fopen($file,'r');
$strContent = fread($fp, filesize($file));
fclose($fp);
$strContent=$encryptObj->decrypt($strContent);
$con=split(" ",$strContent);
$OraService=$con[8];
$OraUser=$con[9];
$OraDBpass=$con[10];
$db_charset = 'AL32UTF8';
$cursor=oci_connect($OraUser,$OraDBpass,$OraService,$db_charset);
if(!$cursor)
{
echo "<br>Error In connection:- reason<BR>";
$e = oci_error(); // For oci_connect errors pass no handle
}
?>
Thx guys, finally I solved problem myself.
The problem was in variable size of returning value
By changing
oci_bind_by_name($stmt, ":ds_id", $ds_id);
to
oci_bind_by_name($stmt, ":ds_id", $ds_id,10,SQLT_INT );
the problem was solved.

How can I read Excel files with symfony2?

I installed Excelbundle with PhpExcel library. I want to read excel files I found this function.
How can I use it? Any suggestion?
public function xlsAction()
{
$filenames = "your-file-name";
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($filenames);
foreach ($phpExcelObject ->getWorksheetIterator() as $worksheet) {
echo 'Worksheet - ' , $worksheet->getTitle();
foreach ($worksheet->getRowIterator() as $row) {
echo ' Row number - ' , $row->getRowIndex();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
foreach ($cellIterator as $cell) {
if (!is_null($cell)) {
echo ' Cell - ' , $cell->getCoordinate() , ' - ' , $cell->getCalculatedValue();
}
}
}
}
}
My suggestion is "Read the documentation" and start hacking at it. Working with excel is, in my experience, quite complex and time consuming so don't expect other people to solve your problem online.
It seems like you're talking about this bundle:
https://github.com/liuggio/ExcelBundle
It has great documentation, even full examples (see "Fake Controller").
With PHPExcel it is quite easy to read a Excel document.
See my example :
$dir = $this->getContainer()->getParameter("kernel.root_dir") . "/../../data/import/";
$file_name = "my_excel_file.xlsx";
$excel = $this->getContainer()->get('phpexcel')->createPHPExcelObject($dir . DIRECTORY_SEPARATOR . $file_name);
$sheet = $excel->getActiveSheet();
$row = 0;
while ($sheet->getCellByColumnAndRow(1, $row)->getValue()) {
$data = $sheet->getCellByColumnAndRow(2, $row)->getValue(); // get value from nth line and 2nf column
//do stuff -- see doc for functions on $sheet
}

Convert encryption/decryption function from Python to PHP

I have this Python script to encrypt/decrypt URLs:
# -*- coding: utf-8 -*-
import base64
from operator import itemgetter
class cryptUrl:
def __init__(self):
self.key = 'secret'
def encode(self, str):
enc = []
for i in range(len(str)):
key_c = self.key[i % len(self.key)]
enc_c = chr((ord(str[i]) + ord(key_c)) % 256)
enc.append(enc_c)
return base64.urlsafe_b64encode("".join(enc))
def decode(self, str):
dec = []
str = base64.urlsafe_b64decode(str)
for i in range(len(str)):
key_c = self.key[i % len(self.key)]
dec_c = chr((256 + ord(str[i]) - ord(key_c)) % 256)
dec.append(dec_c)
return "".join(dec)
url = "http://google.com";
print cryptUrl().encode(url.decode('utf-8'))
This works fine. For example the above url is converted to 29nX4p-joszS4czg2JPG4dI= and the decryption brings it back to the URL.
Now i want to convert this to a PHP function. So far encryption is working fine....but decryption is not....and i dont know why.....so far i got this:
function base64_url_encode($input) {
return strtr(base64_encode($input), '+/=', '-_');
}
function base64_url_decode($input) {
return strtr(base64_decode($input), '-_', '+/=');
}
function encode ($str)
{
$key = 'secret';
$enc = array();
for ($i;$i<strlen($str);$i++){
$key_c = $key[$i % strlen($key)];
$enc_c = chr((ord($str[$i]) + ord($key_c)) % 256);
$enc[] = $enc_c;
}
return base64_url_encode(implode($enc));
}
function decode ($str)
{
$key = 'secret';
$dec = array();
$str = base64_url_decode($str);
for ($i;$i<strlen($str);$i++){
$key_c = $key[$i % strlen($key)];
$dec_c = chr((256 + ord($str[$i]) + ord($key_c)) % 256);
$dec[] = $dec_c;
}
return implode($dec);
}
$str = '29nX4p-joszS4czg2JPG4dI=';
echo decode($str);
Now the above decoding prints out : N>:Tý\&™åª—Væ which is not http://google.com :p
Like i said encoding function works though.
Why isnt the decoding working ? What am i missing ?
Btw i cant use any other encoding/decoding function. I have a list of URLs encoded with python and i want to move the whole system to a PHP based site....so i need to decode those URLs with a PHP function instead of python.
(Use this page to execute Python: http://www.compileonline.com/execute_python_online.php)
Double check the syntax of strtr().
I'd suggest you using in in the following way:
strtr(
base64_encode($input),
array(
'+' => '-',
'/' => '_',
'=' => YOUR_REPLACE_CHARACTER
)
)
Make sure you have YOUR_REPLACE_CHARACTER!
Also, I'm sure you'll handle the reverse function, where you need to simply flip the values of the replace array.

Rename files during upload within Wordpress

I am trying to rename upload filenames match the Post Title.
This other thread shows how to rename to hash:
Rename files during upload within Wordpress backend
Using this code:
function make_filename_hash($filename) {
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$name = basename($filename, $ext);
return md5($name) . $ext;
}
add_filter('sanitize_file_name', 'make_filename_hash', 10);
Does anyone know the code to rename the file to match Post Title.extension?
barakadam's answer is almost correct, just a little correction based on the comment I left below his answer.
function new_filename($filename, $filename_raw) {
global $post;
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$new = $post->post_title . $ext;
// the if is to make sure the script goes into an indefinate loop
if( $new != $filename_raw ) {
$new = sanitize_file_name( $new );
}
return $new;
}
add_filter('sanitize_file_name', 'new_filename', 10, 2);
Explanation of code:
Lets assume you upload a file with the original filename called picture one.jpg to a post called "My Holiday in Paris/London".
When you upload a file, WordPress removes special characters from the original filename using the sanitize_file_name() function.
Right at the bottom of the function is where the filter is.
// line 854 of wp-includes/formatting.php
return apply_filters('sanitize_file_name', $filename, $filename_raw);
At this point, $filename would be picture-one.jpg. Because we used add_filter(), our new_filename() function will be called with $filename as picture-one.jpg and $filename_raw as picture one.jpg.
Our new_filename() function then replaces the filename with the post title with the original extension appended. If we stop here, the new filename $new would end up being My Holiday in Paris/London.jpg which all of us know is an invalid filename.
Here is when we call the sanitize_file_name function again. Note the conditional statement there. Since $new != $filename_raw at this point, it tries to sanitize the filename again.
sanitize_file_name() will be called and at the end of the function, $filename would be My-Holiday-in-Paris-London.jpg while $filename_raw would still be My Holiday in Paris/London.jpg. Because of the apply_filters(), our new_filename() function runs again. But this time, because $new == $filename_raw, thats where it ends.
And My-Holiday-in-Paris-London.jpg is finally returned.
Something like this? (considering $post is your post variable, make it global):
function new_filename($filename) {
global $post;
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
return $post->post_title . $ext;
}
add_filter('sanitize_file_name', 'new_filename', 10);
Did I understand you?

Resources