How to log error message in drupal - php

How to log our own error messages(for ex: error due to invalid user date entry) which is generated in php program to drupal error log.

You can use the watchdog function :
watchdog($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL)
Quoting the manual, the parameters are :
$type The category to which this message belongs.
$message The message to store in the log.
$variables Array of variables to replace in the message on display or NULL if message is already translated or not possible to translate.
$severity The severity of the message, as per RFC 3164
$link A link to associate with the message.
And the error levels can be found on the page of watchdog_severity_levels. For an error, you'll most probably use WATCHDOG_ERROR, or maybe even something more "critical", depending on the kind of error.

Drupal 8+
// Logs a notice
\Drupal::logger('my_module')->notice($message);
// Logs an error
\Drupal::logger('my_module')->error($message);
See more examples at How to Log Messages in Drupal 8.

1) Indeed, watchdog is a standard way to record own PHP errors.
2) Alternatively, if you need to immediately see error messages while debugging your Drupal pages, you may want to see them logged/printed right at the related page - in FireBug console.
Sometimes is this very convenient when you can see page-related just-in-time logs.
This requires - Devel module, Firebug extension to FireFox and possibly Firephp.
You can use the dfb() function to write log messages directly to the general Firebug console.
dfb($input, $label = NULL)
If you want to keep your Drupal-related log messages out of the normal Firebug console, you can write messages to the Drupal for Firebug log with the firep() function:
firep($item, $optional_title)

Watchdog is the way to go for a production system no doubt but during debugging I find the drupal_set_message function useful.
It outputs the message to the screen where the 'Operation Successful'-type messages are normally displayed (so make sure you remove them before making the site Live).
http://api.drupal.org/api/function/drupal_set_message/6

In drupal 7 we can log message by following method:
drupal watchdog function we can use to log message in database , make sure we have enabled optional core module for Database Logging at /admin/build/modules.
watchdog($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL)
$type:
The category to which this message belongs , Example: PHP,cron.., we can filter message by type.
$message :
The message to store in the log,Example: 'The following module is missing from the file system: security_review'
$variables :
Array of variables to replace in the message on display or NULL if message is already translated or not possible to translate.
to make message translated , do not pass dynamic value pass variables in the message should be added by using placeholder strings.
Example:
watchdog('cg_volunteer', 'cg in form_alter %formly', array('%formly' => $form['#id']), WATCHDOG_NOTICE, $link = NULL);
$severity
The severity of the message,logs can be filter by severity as per RFC 3164. Possible values are WATCHDOG_ERROR, WATCHDOG_WARNING, etc.
For more example see https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/watchdog/7.x
$link:
A link to associate with the message.
Example
// for logs notices
watchdog('my_module', $message, array());
// for Loging Error
watchdog('my_module', $message, array(), WATCHDOG_ERROR);
In drupal 8 we used following method:
// For Logs a notice.
\Drupal::logger('my_module')->notice($message);
// For Logs an error.
\Drupal::logger('my_module')->error($message);
// For Alert, action must be taken immediately.
\Drupal::logger('my_module')->alert($message);
// For Critical message.
\Drupal::logger('my_module')->critical($message);
// For Debug-level messages.
\Drupal::logger('my_module')->debug($message);
//For Emergency, system is unusable.
\Drupal::logger('my_module')->emergency($message);
//For Warning
\Drupal::logger('my_module')->warning($message);
//For Informational messages.
\Drupal::logger('my_module')->info($message);
Also for translate we should not use t() function.
\Drupal::logger('my_module')->alert('Message from #module: #message.', [
'#module' => $module,
'#message' => $message,
]);
this will be translated on run time.
Example :
\Drupal::logger('content_entity_example')->notice('#type: deleted %title.',
array(
'#type' => $this->entity->bundle(),
'%title' => $this->entity->label(),
));

Both watchdog for D7 & \Drupal::logger for D8 will write log in watchdog table (in your database), and with HUGE data logged, you can imagine performance impact.
You can use error_log php function to do it (see PHP manual).
error_log("Your message", 3, "/path/to/your/log/file.log");
You need to have permission to write in your log file (/path/to/your/log/file.log)
drupal-8drupalphplog

// Get logger factory.
$logger = \Drupal::service('logger.factory');
// Log a message with dynamic variables.
$nodeType = 'Article';
$userName = 'Admin';
$logger->get($moduleName)->notice('A new "#nodeType" created by %userName.', [
'#nodeType' => $nodeType,
'%userName' => $userName,
]);
Source

Related

How i can check drupal logs

The problem is that mailing on my site didt work.
There is code to sending mail
....
$params['subject'] = $mail_subject;
$params['body'] = $mail_body;
$to = 'dmitriikotow#gmail.com'
$from = 'mail#ckeverest.ru';
$lang = language_default();
drupal_mail('everest_mail', 'html_mail', $to, $lang, $params, $from, false);
....
There is custom mail-module code
<?php
class EverestMailSystem extends DefaultMailSystem {
public function format(array $message) {
$message['body'] = implode("\n\n", $message['body']);
$message['body'] = drupal_wrap_mail($message['body']);
return $message;
}
}
function everest_mail_mail($key, &$message, $params) {
switch ($key) {
case 'html_mail':
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8;';
$message['subject'] = $params['subject'];
$message['body'][] = $params['body'];
break;
}
}
?>
At first glance, everything should work. There is a suspicion that the problem is outside of the module, as sending messages to work until the last update the appearance of the site (I have not participated in the update). As the module was not written by me, so I need the opinion of a more experienced programmer than I am.
In any case, I would like to know. Where can I find useful in my case the logs site? And with their help to catch a mistake?
Thank you so much.
Drupal uses a module called watchdog to handle logging (D8 and earlier). There are a few ways to access these logs:
If you are using Drush, you can simply type drush ws to see a list of the most recent 10(ish) log entries. (pro tip: each log entry has an id and if you type drush ws [ID] you can see more details)
There is a module that ships with Drupal called "Database logs" or "DB Logs". If you enable this module you will get a "view recent log messages" page under the "report" menu item. DO NOT enable this module on a production site except as an absolute last resort.
I'm 99% sure that Drupal's watchdog logs are piped into you system log so you should be able to get them in there as well. In OSX (ahem) MacOS you can use the Console Application to view logs, or just use tail on the command line to tail your system logs
hope that helps

Moodle display moodle_exception Error on form post

I am new to moodle and trying to customize my course creation in moodle.
I validated by moodle_form data in a function and from there I need to throw an error which will be displayed after the form (course/edit_form.php) is submitted. I tried the moodle way, as they have done:
throw new moodle_exception('refresher_value_less_than_one', '', '', $data->refresh_value);
I expected it to receive the error at the form page. It showed be the error string but not inside the form, but on a blank page.
Any idea, how to catch this exception in form.?
If you want to show an error within the form, then you need to create a function within your form class called 'validation($data, $files)'. Within this form, you need to check the values in the array $data, then return an array of error messages, indexed by the form field that the error should display beside.
For example, if you had a field called 'myfield', you could check the contents of $Data['myfield'] and, if there was a problem, return array('myfield' => get_string('myfielderror', 'myplugin')).
Throwing an exception will immediately halt the execution of the page and output only that error message.

Drupal email variables not appearing

Whenever a user registers an account, the automated emails (which I can set in admin/config/people/accounts) are not carrying over the defined variables for username, email, etc.
For example. Here's what I have set for one email:
[user:name],
Thank you for registering at [site:name]. Your application for an account is currently pending approval. Once it has been approved, you will receive another e-mail containing information about how to log in, set your password, and other details.
-- [site:name] team
Those variables in brackets just aren't appearing. The email sends as usual, but where those variables are, nothing gets inserted. Is there something I have to enable first?
The token replacement in mails happen in line 2815 of user.module (modules/user/user.module). You can add the following line of code
drupal_set_message("Text: $text, Variables: " . print_r($variables, TRUE) . ", Language: $language);
before the line that says
return token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
That will tell you as messages what is happening with the token replacement issue. If you can post the messages that you see back here I can help solve the issue.
It seems that you have misconfiguration issues or losing sth .for seeing configs with html mail in here ,
see here
also try updating it using update.php!
-- READ FROM PHP.NET SPECIFICATIONS --,
I THINK THAT BY DEFAULT, SOME HOST PROVIDERS DO NOT SUPPORT FEW PHP FILTERS (OR LIKEWISE), SO (ITS JUST AN ASSUMPTION !) MAY BE, FILTER_SANITIZE_EMAIL THAT IS USED TO REMOVE ALL CHARACTERS EXCEPT LETTERS, DIGITS AND !#$%&'*+-/=?^_`{|}~#.[], IS TURNED ON.
SO JUST CHECK IT OUT !

Drupal simplenews succuess message doesn't display

In my drupal site when a user enter a email address to the newsletter on the right side block. The success message doesn't display therefore, I checked the simplenews_subscriptions_page_form_submit() function and it's actually setting the message like
if (simplenews_confirmation_send_combined()) {
drupal_set_message(t('You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription.'));
}
And after I've debug the drupal_get_messages() function to see is any value any values returns for it and Yes it is as
Array ( [status] => Array ( [0] => You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription. )
But in the font-theme doesn't display anything I also checked theme_status_messages() function it actually initially checked for $display = $variables['display']; then when I debug this value it's printing always empty but $variables['display'] value is set.
Could any please let me know how to fix this ?
FYI: I'm using Drupal v7
Are you sure that $messages variable is mentioned in the theme getting called ?
If not, mention in the page.tpl.php

Kohana Validation _external messages

I have 3 models using validation messages. 2 of them work perfectly for all messages, including _external messages. The third never returns the custom _external message. The folder structure and way in which I get the errors are identical for each model.
Folder Structure
messages\models\verify
Catching the Errors
catch (ORM_Validation_Exception $e)
{
return $e->errors('models/verify');
}
Errors Passed to View
array(1) { ["_external"]=> array(1) { ["activation_hash"]=> string(33) "activation hash must not be empty" } }
Output External Error
<?= Arr::path($errors, '_external.activation_hash'); ?>
messages\models\verify_external.php
return array(
'activation_hash' => array(
'not_empty' => 'The email fields did not match'
),
);
Validation
$extra_rules = Validation::factory($values)
->rule('activation_hash', 'not_empty');
$email->check($extra_rules);
There that should be everything. Again, everything is exactly the same amongst 3 models so I assume its a typo or a bug. Either way I pasted everything here from the code, do you see something I missed? In a debug attempt I put the _external.php file in every directory along the path to the verify folder but got no where so I dont think its my folder structure.
My solution was to include the validation messages in an existing message file. The purpose of the verify action in my example above was to verify a users email address. I added the external verify messages to the external email array and it worked as intended.

Categories