How to Log object?

LaravelLaravel 5.2

Laravel Problem Overview


I can see that Log facade is very useful. In the docs of laravel:

> The logger provides the eight logging levels defined in RFC 5424: > emergency, alert, critical, error, warning, notice, info and debug.

But, how would I log an instance of a model? like for example:

$user= User::find($user_id);

then, would it be possible to log the $user object?

Laravel Solutions


Solution 1 - Laravel

This will work, although logging the entire model will grow your log rather quickly.

Log::info(print_r($user, true));

The true in the second parameter of the print_r() method returns the information instead of printing it, which allows the Log facade to print it like a string.

Solution 2 - Laravel

You can log either by print_r or json_encode. json_encode is more readable.

For example:

use Illuminate\Support\Facades\Log;

Log::info(json_encode($user)); 

Solution 3 - Laravel

I've recently started using Laravel, so this certainly works in 5.3 and 5.4, not sure for earlier versions.

The quickest way I can think of (suits smaller objects) would be to cast object to array:

Log::debug((array) $object);

Yo may wonder how's this possible, first param of debug method (as well as error, notice and other logging methods in Log class) accepts string as first param, and we are passing the array.

So, the answer lays down deep in the log writer class. There is a method that gets called every time to support formatting the messages, and it looks like this:

/**
 * Format the parameters for the logger.
 *
 * @param  mixed  $message
 * @return mixed
 */
protected function formatMessage($message)
{
    if (is_array($message)) {
        return var_export($message, true);
    } elseif ($message instanceof Jsonable) {
        return $message->toJson();
    } elseif ($message instanceof Arrayable) {
        return var_export($message->toArray(), true);
    }

    return $message;
}

Also to clarify things little bit more, you can take a look into: https://github.com/laravel/framework/blob/5.4/src/Illuminate/Log/Writer.php#L199 and you'll see that formateMessage method is formatting the message every time.

Solution 4 - Laravel

No.

The first parameter must be a string (or a string object representation). If you wish to pass any other type of (raw) data or objects, you can always JSON encode them, and push them in the context settings, like so:

<?php 

$user = User::find($user_id);

\Log::error("Something happened to User {$user_id}.", ['object' => $user->toJson()]);

Or:

<?php

// User.php
[...]

class User 
{
    [...]

    public function __toString()
    {
        return "{$this->id}";
    }
}

// [...]
$user = User::find($user_id);

\Log::error("Something happened to User {$user}.", ['object' => $user->toJson()]);

You can find more information about the method signatures here.

Solution 5 - Laravel

At least in Laravel 8 there is no need to use print_r() nor json_encode() in your log statements.

Use the second parameter to pass an array. For example:


Log::info('My message', ['user' => $user]);

// The Output will be

[2021-08-17 09:23:13] local.INFO: test {"user":{"App\\Models\\User":{"name":"Rosalia Mraz Jr.","email":"[email protected]","email_verified_at":"2021-08-17T07:23:13.604361Z","updated_at":"2021-08-17T07:23:13.000000Z","created_at":"2021-08-17T07:23:13.000000Z","id":29,"tax_rate":25}}} 

Solution 6 - Laravel

This causes "allocated memory size exhausted" exception in some cases. (e.g native exception class) – Gokigooooks

Had same problem.

Log::info(print_r($request->user()->with('groups'), true ) );

Add ->get()

Log::info(print_r($request->user()->with('groups')->get(), true ) );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsimoView Question on Stackoverflow
Solution 1 - LaravelRob FonsecaView Answer on Stackoverflow
Solution 2 - Laraveluser3785966View Answer on Stackoverflow
Solution 3 - LaravelvkovicView Answer on Stackoverflow
Solution 4 - LaravelGiamPyView Answer on Stackoverflow
Solution 5 - LaraveljannejView Answer on Stackoverflow
Solution 6 - LaravelDanbass07View Answer on Stackoverflow