log4php and timezone - php

Does anyone know if it is possible to set timezone in the log4php library configuration?
I did not see any information regarding this in the official docs, but log4j has this implemented.
Right now, I am relying on php's *date_default_timezone_set* function to do the trick, but I wanted to leave log4php to handle this on its own... I wonder if there is a to-do list for this or we are supposed to rely on the built-in function by ourselves.
Here is the code I have:
date_default_timezone_set("America/New_York");
require_once (dirname(__FILE__) . '/lib/log4php/Logger.php');
Logger::configure(
array(
'appenders' => array(
'default' => array(
'class' => 'LoggerAppenderRollingFile',
'layout' => array(
'class' => 'LoggerLayoutPattern',
'params' => array(
'conversionPattern' => '%d{Y-m-d H:i:s.u} [%t] %-5p - %m%n'
)
),
'params' => array(
'file' => '/var/log/myapp/myapp.' . date('Y-m-d') . '.log',
'maxFileSize' => '1MB',
'maxBackupIndex' => 10,
),
),
),
'rootLogger' => array(
'appenders' => array('default'),
),
)
);
$logger = Logger::getLogger('myapp');
for( $i=0; $i<5000; $i++ ) {
$logger->info("This is a test [${i}].");
}
In case this code serves someone else with similar issue.
Be safe,

A defined default timezone belongs to a fully working php application.
Apart from that, you are not very clear in stating what you expect log4php to do. The project has everything from mailing list to issue tracker - you are welcome to send your wishes.

I had a similar problem. You can log the date and time for UTC/GMT in the log4php by changing one line of code in the module.
Here is how I did. Go to the module and find the file LoggerPatternConverterDate.php.
cd log4php/pattern/
vim LoggerPatternConverterDate.php
Find the private function date($format, $utimestamp) (Line 84 for me) and change the line of code that returns.
This:
return date(preg_replace('`(?<!\\\\)u`', $ms, $format), $timestamp);
Becomes:
return gmdate(preg_replace('`(?<!\\\\)u`', $ms, $format), $timestamp);
Also, find the file: log4php/appenders/LoggerAppenderDailyFile.php and change the following line:
This:
return date($this->datePattern, $timestamp);
Becomes:
return gmdate($this->datePattern, $timestamp);
NOTE: The only thing changed is the function used to format the date string. date() depends on timezone that you set using date_default_timezone_set whereas gmdate() formats the date and time in UTC/GMT irrespective of default timezone.

Related

Users' timezone issue onYii2 with PostgreSQL

I would like to ask for a better approach. I am using Yii2 with PostgreSQL, and set all timestamp fields for all table to timestamp with timezone data type.
timestamp with time zone NOT NULL DEFAULT now()
I have created setting which will be called for every response,
Yii::$app->setTimezone(MallSettings::getSetting('timezone', Yii::$app->session['mall_id']));
which will return something like Asia/Makassar or Asia/Jakarta (it depends on user's setting).
I extend the \yii\18n\Formatter, using a class named ZeedFormatter below, and make a new function to display the datetime value in user's preferred timezone.
class ZeedFormatter extends \yii\i18n\Formatter
{
/**
* Format timestamp with timezone value to user's preferred timezone.
* (extends the asDatetime() functionality)
*
* #param [type] $value [description]
* #param [type] $format [description]
* #return [type] [description]
*/
public function asLocaldatetime($value, $format = null)
{
$originalDateTime = \DateTime::createFromFormat('Y-m-d H:i:s.uO', $value);
$originalDateTime->setTimezone(new \DateTimeZone(date_default_timezone_get()));
if ($format === null)
$format = 'Y-m-d H:i:s.uO';
$localDateTime = $originalDateTime->format($format);
return $localDateTime;
}
}
The idea is that whenever I need a 'local' datetime format, I can call it like so:
Yii::$app->formatter->asLocaldatetime('2019-08-29 19:52:21.02886+07');
// will return 2019-08-29 20:52:21.02886+08 for Asia/Makassar timezone
Or, if used inside a GridView,
'position',
'created_at:localdatetime',
['class' => 'backend\widgets\ActionColumn'],
Can I get this functionality only using Yii2's feature? Or (another option) is calling created_at AT TIME ZONE 'Asia/Makassar' from the Psql query? I hope I can get an enlightment. Thank you.
My (another) approach is to keep using the asDatetime() function.
I just realized that I need to remove / comment the timezone from config file. If the value is set there, no matter how I set the timezone at other place, Yii always gets the value from the config file (common/config/main.php) if we are using the asDatetime formatter.
'components' => [
'formatter' => [
// 'class' => '\common\modules\ZeedFormatter',
'locale' => 'id-ID',
// 'timeZone' => 'Asia/Jakarta',
'defaultTimeZone' => 'Asia/Jakarta',
'dateFormat' => 'php:j M Y',
'decimalSeparator' => ',',
'thousandSeparator' => '.',
'currencyCode' => 'Rp ',
'nullDisplay' => '<em style="color:#d8d8d8">null</em>',
'numberFormatterOptions' => [
NumberFormatter::MIN_FRACTION_DIGITS => 0,
NumberFormatter::MAX_FRACTION_DIGITS => 0,
],
],
]
If we need another (or customized) format, we can still use the ZeedFormatter as above and add some desired functions. For example :
public function asMyformat($value)
{
$timestamp = strtotime($value);
$fmt = new \IntlDateFormatter('id-ID', \IntlDateFormatter::NONE, \IntlDateFormatter::LONG);
$fmt->setPattern('hh:mm z');// will return something like '09:47 WITA'
return $fmt->format($timestamp);
}

Change order of Zend Framework 2 DateSelect drop downs

I have a form element in a ZF2 application that uses DateSelect to allow a user to enter their date of birth. Currently the fields are shown in the order d-m-y. I would like to reverse this order so it is displayed as y-m-d. I have come across posts on SO that recommend changing the locale in PHP to change the order but that is not an option for me. I have also tried
$this->add(array(
'type' => 'Zend\Form\Element\DateSelect',
'name' => 'dob',
'options' => array(
'label' => 'Date of Birth',
'create_empty_option' => true,
'pattern' => $this->options['isMobile'] ? 'd MMM y' : 'd MMM y',
'empty_options' => array(
'day' => 'DD',
'month' => 'MM',
'year' => 'YYYY',
),
'allowLabelHTML' => TRUE,
'required' => true,
)
));
$this->get('dob')->setFormat('Y-m-d');
Which was an accepted answer to another SO question but that produces an internal server error for me. I would be surprised if this is not possible, maybe using an helper file but I cannot find anything on the web to suggest how, apart from the above and changing the locale. Can anyone help with this?
You get fatal error because method setFormat() does not exist in Zend\Form\Element\DateSelect.
I don't think it is possible to achieve this without writing own view helper.
Zend\Form\Element\DateSelect is based on locale settings, so you can pass locale short code as parameter to view helper, so order of elements will be proper for provided region.
This view helper takes 3 parameters $this->formDateSelect($element, $intlFormat, $locale), so you use it like this:
echo $this->formDateSelect($form->get('dob'), \IntlDateFormatter::LONG, 'en_Gb');
or...
echo $this->formDateSelect()->setLocale('en_Gb')->render($form->get('dob'));
or... you can change locale settings in your php.ini file
intl.default_locale = en_Gb

Cache query cakephp

I have a site developed in cakephp. I want to cache a query. I have read the documentation and I have in my bootstrap.php this:
Cache::config('default', array('engine' => 'File'));
Cache::config('short', array(
'engine' => 'File',
'duration' => '+1 hours',
'path' => CACHE,
'prefix' => 'cake_short_'
));
// long
Cache::config('long', array(
'engine' => 'File',
'duration' => '+1 week',
'probability' => 100,
'path' => CACHE . 'long' . DS,
));
My controller to store the query is this:
public function test_view () {
$product_general = Cache::read('product_general_query', 'longterm');
if (!$product_general) {
echo("test");
$product_general = $this->Product->query('SELECT DISTINCT * FROM products');
Cache::write('product_general_query', $product_general, 'longterm');
}
$this->set('product_general', $product_general);
}
Everytime that I enter into the page it print me "test" because doesn't find the query into the cache. Where is the problem? Have I miss something?
You named your cache configuration 'long' inside your core.php but using configuration 'longterm' inside your action
Also, If you have enabled debugging (e.g. debug set to 1 or 2 in your core.conf), the cache duration may be set to 10 seconds automatically. Not sure if this will apply to your own cache definitions as well though

CakePHP 1.3.10 element caching

I'm trying to get element caching setup for certain elements but no matter what I do I can't get the cache files to write to tmp/cache/view/
Here is the code for the element
echo $this->element('carinfo',
array(
'car_id' => $car['Car']['id'],
'show_user_info_box' => true,
'car_display_size' => 'medium'
),
array('cache' => '+1 day')
);
I've got all the following settings in my core.php
Configure::write('debug', 0);
Configure::write('Cache.check', true);
I'm really at a loose end here and the speed of the site is really suffering because of it.
I've also tried all variations of 'cache' => '35000' and 'cache' => '1 day' etc.
Put the cache key/value in to the second argument - elements take a boolean as the third argument, not an array.

batch put_item with DynamoDB in PHP

I'm running into issues sending data to my DynamoDB. I have no idea what the issue is because it appears the program runs correctly, however I don't seem to have any data in my DB. I was able to create tables using Amazons tutorial, but when I follow this tutorial, I get a failed response if I try and put ALL the items, and a false success when it's only one item, as nothing is updated in the db.
Here's the code, I'm curious specifically if anyone knows a means to debug these kinds of issues.
<?php
// If necessary, reference the sdk.class.php file.
// For example, the following line assumes the sdk.class.php file is
// in an sdk sub-directory relative to this file
require_once('includes/backend.php');
// Instantiate the class
$dynamodb = new AmazonDynamoDB();
####################################################################
# Setup some local variables for dates
$one_day_ago = date('Y-m-d H:i:s', strtotime("-1 days"));
$seven_days_ago = date('Y-m-d H:i:s', strtotime("-7 days"));
$fourteen_days_ago = date('Y-m-d H:i:s', strtotime("-14 days"));
$twenty_one_days_ago = date('Y-m-d H:i:s', strtotime("-21 days"));
####################################################################
# Adding data to the table
echo PHP_EOL . PHP_EOL;
echo "# Adding data to the table..." . PHP_EOL;
// Set up batch requests
$queue = new CFBatchRequest();
$queue->use_credentials($dynamodb->credentials);
// Add items to the batch
$dynamodb->batch($queue)->put_item(array(
'TableName' => 'ProductCatalog',
'Item' => array(
'Id' => array( AmazonDynamoDB::TYPE_NUMBER => '101' ), // Hash Key
'Title' => array( AmazonDynamoDB::TYPE_STRING => 'Book 101 Title' ),
'ISBN' => array( AmazonDynamoDB::TYPE_STRING => '111-1111111111' ),
'Authors' => array( AmazonDynamoDB::TYPE_ARRAY_OF_STRINGS => array('Author1') ),
'Price' => array( AmazonDynamoDB::TYPE_NUMBER => '2' ),
'Dimensions' => array( AmazonDynamoDB::TYPE_STRING => '8.5 x 11.0 x 0.5' ),
'PageCount' => array( AmazonDynamoDB::TYPE_NUMBER => '500' ),
'InPublication' => array( AmazonDynamoDB::TYPE_NUMBER => '1' ),
'ProductCategory' => array( AmazonDynamoDB::TYPE_STRING => 'Book' )
)
));
echo "Item put in <b>Reply</b>" . "<br/>";
// Execute the batch of requests in parallel
$responses = $dynamodb->batch($queue)->send();
// Check for success...
if ($responses->areOK())
{
echo "The data has been added to the table." . PHP_EOL;
}
else
{
utdump($responses);
}
Thank you for your time
Try setting your region explicitly, e.g. for EU you need to call:
$myDynamoDbObject->set_region('dynamodb.eu-west-1.amazonaws.com');
It might also be that you have two tables in different regions, your application work with one of them and you trying to read (or track with web console) another one because of different default regions applied.
If you're tracking number of items in the table, keep in mind that it is not a real time figure, it is only updated every 6 hours or so. So the way use can ensure your item is indeed written by trying to read it back immediately after you receive the "OK" response for your put request.

Categories