How to Log object?

后端 未结 5 2182
渐次进展
渐次进展 2021-02-01 13:21

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, cr

5条回答
  •  我在风中等你
    2021-02-01 13:40

    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.

提交回复
热议问题