php 如何从 Laravel 控制器写入控制台?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25148662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:41:31  来源:igfitidea点击:

How do I write to the console from a Laravel Controller?

phplaravelloggingconsole

提问by Jrop

So I have a Laravel controller:

所以我有一个 Laravel 控制器:

class YeahMyController extends BaseController {
    public function getSomething() {
        Console::info('mymessage'); // <-- what do I put here?
        return 'yeahoutputthistotheresponse';
    }
}

Currently, I'm running the application using artisan (which runs PHP's built-in development web server under the hood):

目前,我正在使用 artisan 运行应用程序(它在后台运行 PHP 的内置开发 Web 服务器):

php artisan serve

I would like to log console messages to the STDOUTpipe for the artisan process.

我想将控制台消息记录到STDOUT工匠进程的管道中。

回答by Jrop

Aha!

啊哈!

This can be done with the following PHP function:

这可以通过以下 PHP 函数来完成:

error_log('Some message here.');

Found the answer here: Print something in PHP built-in web server

在这里找到答案:Print something in PHP built-in web server

回答by wired00

The question relates to serving via artisan and so Jrop's answer is ideal in that case. I.e, error_loglogging to the apache log.

这个问题与通过工匠服务有关,因此在这种情况下 Jrop 的回答是理想的。即,error_log登录到 apache 日志。

However, if your serving via a standard web server then simply use the Laravel specific logging functions:

但是,如果您通过标准 Web 服务器提供服务,则只需使用 Laravel 特定的日志记录功能:

\Log::info('This is some useful information.');

\Log::warning('Something could be going wrong.');

\Log::error('Something is really going wrong.');

With current versions of laravel like this for info:

使用当前版本的 laravel 获取信息:

info('This is some useful information.');

This logs to Laravel's log file located at /laravel/storage/logs/laravel-<date>.log(laravel 5.0). Monitor the log - linux/osx: tail -f /laravel/storage/logs/laravel-<date>.log

这会记录到位于/laravel/storage/logs/laravel-<date>.log(laravel 5.0) 的Laravel 日志文件。监控日志 - linux/osx:tail -f /laravel/storage/logs/laravel-<date>.log

回答by Dave Morrissey

I haven't tried this myself, but a quick dig through the library suggests you can do this:

我自己还没有尝试过这个,但是快速浏览图书馆表明你可以这样做:

$output = new Symfony\Component\Console\Output\ConsoleOutput();
$output->writeln("<info>my message</info>");

I couldn't find a shortcut for this, so you would probably want to create a facade to avoid duplication.

我找不到为此的快捷方式,因此您可能希望创建一个外观以避免重复。

回答by Googlian

It's very simple.

这很简单。

You can call it from anywhere in APP.

您可以在 APP 中的任何位置调用它。

$out = new \Symfony\Component\Console\Output\ConsoleOutput();
$out->writeln("Hello from Terminal");

回答by Tudor

For better explain Dave Morrissey's answer I have made these steps for wrap with Console Output class in a laravel facade.

为了更好地解释 Dave Morrissey 的回答,我已经在 laravel 外观中使用控制台输出类进行了这些步骤。

1) Create a Facade in your prefer folder (in my case app\Facades):

1) 在您喜欢的文件夹中创建一个 Facade(在我的例子中是 app\Facades):

class ConsoleOutput extends Facade {

 protected static function getFacadeAccessor() { 
     return 'consoleOutput';
 }

}

2) Register a new Service Provider in app\Providers as follow:

2) 在 app\Providers 中注册一个新的 Service Provider,如下所示:

class ConsoleOutputServiceProvider extends ServiceProvider
{

 public function register(){
    App::bind('consoleOutput', function(){
        return new \Symfony\Component\Console\Output\ConsoleOutput();
     });
 }

}

}

3) Add all this stuffs in config\app.php file, registering the provider and alias.

3) 在 config\app.php 文件中添加所有这些东西,注册提供者和别名。

 'providers' => [
   //other providers
    App\Providers\ConsoleOutputServiceProvider::class
 ],
 'aliases' => [
  //other aliases
   'ConsoleOutput' => App\Facades\ConsoleOutput::class,
 ],

That's it, now in any place of your Laravel application, just call your method in this way:

就是这样,现在在你的 Laravel 应用程序的任何地方,只需以这种方式调用你的方法:

ConsoleOutput::writeln('hello');

Hope this help you.

希望这对你有帮助。

回答by vbence

If you want to log to STDOUT you can use any of the ways Laravel provides; for example (from wired00's answer):

如果你想登录 STDOUT,你可以使用 Laravel 提供的任何方式;例如(来自wired00的回答):

Log::info('This is some useful information.');

The STDOUT magic can be done with the following (you are setting the filewhere infomessages go):

STDOUT 魔术可以通过以下方式完成(您正在设置消息所在的文件info):

Log::useFiles('php://stdout', 'info');

Word of caution: this is strictly for debugging. Do no use anythingin production you don't fully understand.

注意事项:这仅用于调试。不要在生产中使用任何你不完全理解的东西。

回答by alexkb

I wanted my logging information to be sent to stdout because it's easy to tell Amazon's Container service (ECS) to collect stdout and send it to CloudWatch Logs. So to get this working, I added a new stdout entry to my config/logging.phpfile like so:

我希望将我的日志信息发送到标准输出,因为告诉 Amazon 的容器服务 (ECS) 收集标准输出并将其发送到 CloudWatch Logs 很容易。所以为了让它工作,我在我的config/logging.php文件中添加了一个新的标准输出条目,如下所示:

    'stdout' => [
        'driver' => 'monolog',
        'handler' => StreamHandler::class,
        'with' => [
            'stream' => 'php://stdout',
        ],
        'level' => 'info',
    ],

Then I simply added 'stdout' as one of the channels in the stack log channel:

然后我简单地添加了“stdout”作为堆栈日志通道中的通道之一:

    'default' => env('LOG_CHANNEL', 'stack'),

    'stack' => [
        'driver' => 'stack',
        'channels' => ['stdout', 'daily'],
    ],

This way, I still get logs in a file for local development (or even on the instance if you can access it), but more importantly they get sent to the stdout which is saved in CloudWatch Logs.

这样,我仍然会在文件中获取日志以用于本地开发(或者甚至在实例上,如果您可以访问它),但更重要的是,它们会被发送到保存在 CloudWatch Logs 中的 stdout。

回答by Tomeg

If you want the fancy command IO from Laravel(like styling, asking and table) then I created this class below

如果您想要来自 Laravel精美命令 IO(如样式、询问和表格),那么我在下面创建了这个类

Instructions

指示

I have not fully verified everywhere that it is THE cleanest solution etc, but it works nice (but I only tested it from within a unit test case, under Laravel 5.5).

我还没有在任何地方完全验证它是最干净的解决方案等,但它运行良好(但我只在 Laravel 5.5 下的单元测试用例中对其进行了测试)。

So most probably you can use it however you like:

所以很可能你可以随心所欲地使用它:

$cmd = new ConsoleCommand;

$cmd->error("Aw snap!");
$cmd->table($headers, $rows);
$answer = $cmd->ask("Tell me, what do you need?");

//even Symfony's progress bar
$cmd->outputStyle->progressStart(5);  //set n = 100% (here 100% is 5 steps)
$cmd->outputStyle->progressAdvance(); //you can call it n times
$cmd->outputStyle->progressFinish();  //set to 100%

Or course you can also wrap in your own facade, or some static singleton etc, or anyway you wish.

或者当然你也可以包装在你自己的外观中,或者一些静态的单例等等,或者你想要的任何方式。

The class itself

班级本身

class ConsoleCommand extends \Illuminate\Console\Command
{
    protected $name = 'NONEXISTENT';
    protected $hidden = true;

    public $outputSymfony;
    public $outputStyle;

    public function __construct($argInput = null)
    {
        parent::__construct();

        $this->input = new \Symfony\Component\Console\Input\StringInput($argInput);

        $this->outputSymfony = new \Symfony\Component\Console\Output\ConsoleOutput();
        $this->outputStyle = new \Illuminate\Console\OutputStyle($this->input, $this->outputSymfony);

        $this->output = $this->outputStyle;
    }

}

回答by Kyle Ridolfo

In Laravel 6 there is a channel called 'stderr'. See config/logging.php:

在 Laravel 6 中有一个名为“stderr”的通道。见config/logging.php

'stderr' => [
    'driver' => 'monolog',
    'handler' => StreamHandler::class,
    'formatter' => env('LOG_STDERR_FORMATTER'),
    'with' => [
        'stream' => 'php://stderr',
    ],
],

In your controller:

在您的控制器中:

use Illuminate\Support\Facades\Log;

Log::channel('stderr')->info('Something happened!');

回答by Cy Rossignol

Bit late to this...I'm surprised that no one mentioned Symfony's VarDumpercomponentthat Laravel includes, in part, for its dd()(and lesser-known, dump()) utility functions.

有点晚了......我很惊讶没有人提到Laravel 包含的SymfonyVarDumper组件,部分原因是它的dd()(和鲜为人知的dump())实用函数。

$dumpMe = new App\User([ 'name' => 'Cy Rossignol' ]);

(new Symfony\Component\VarDumper\Dumper\CliDumper())->dump( 
    (new Symfony\Component\VarDumper\Cloner\VarCloner())->cloneVar($dumpMe)
);

There's a bit more code needed, but, in return, we get nice formatted, readableoutput in the console—especially useful for debugging complex objects or arrays:

需要更多的代码,但是,作为回报,我们在控制台中获得了格式良好、可读的输出——对于调试复杂的对象或数组尤其有用:

App\User {#17
  #attributes: array:1 [
    "name" => "Cy Rossignol"
  ]
  #fillable: array:3 [
    0 => "name"
    1 => "email"
    2 => "password"
  ]
  #guarded: array:1 [
    0 => "*"
  ]
  #primaryKey: "id"
  #casts: []
  #dates: []
  #relations: []
  ... etc ...
}
App\User {#17
  #attributes: array:1 [
    "name" => "Cy Rossignol"
  ]
  #fillable: array:3 [
    0 => "name"
    1 => "email"
    2 => "password"
  ]
  #guarded: array:1 [
    0 => "*"
  ]
  #primaryKey: "id"
  #casts: []
  #dates: []
  #relations: []
  ... etc ...
}


To take this a step further, we can even colorizethe output! Add this helper functionto the project to save some typing:

为了更进一步,我们甚至可以为输出着色将此辅助函数添加到项目以保存一些输入:

function toConsole($var) 
{
    $dumper = new Symfony\Component\VarDumper\Dumper\CliDumper();
    $dumper->setColors(true);

    $dumper->dump((new Symfony\Component\VarDumper\Cloner\VarCloner())->cloneVar($var));
}

If we're running the app behind a full webserver (like Apache or Nginx—not artisan serve), we can modify this function slightly to send the dumper's prettified output to the log (typically storage/logs/laravel.log):

如果我们在完整的网络服务器(如 Apache 或 Nginx 而非artisan serve)后面运行应用程序,我们可以稍微修改此函数以将转储程序的美化输出发送到日志(通常是storage/logs/laravel.log):

function toLog($var) 
{
    $lines = [ 'Dump:' ];
    $dumper = new Symfony\Component\VarDumper\Dumper\CliDumper();
    $dumper->setColors(true);
    $dumper->setOutput(function ($line) use (&$lines) { 
        $lines[] = $line;
    });

    $dumper->dump((new Symfony\Component\VarDumper\Cloner\VarCloner())->cloneVar($var));

    Log::debug(implode(PHP_EOL, $lines));
}

...and, of course, watch the log using:

...当然,使用以下方法查看日志:

$ tail -f storage/logs/laravel.log

PHP's error_log()works fine for quick, one-off inspection of simple values, but the functions shown above take the hard work out of debugging some of Laravel's more complicated classes.

PHPerror_log()可以很好地快速、一次性地检查简单的值,但是上面显示的函数消除了调试 Laravel 一些更复杂的类的繁重工作。