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


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

我有一个Laravel控制器:

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

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

php artisan serve

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

啊哈!

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

error_log('Some message here.');

在这里找到答案:在PHP内置web服务器中打印一些东西

这个问题涉及到通过artisan服务,所以Jrop的答案在这种情况下是理想的。例如,error_log记录到apache日志。

然而,如果你的服务是通过一个标准的web服务器,那么只需使用Laravel特定的日志功能:

'Log::info('This is some useful information.');
'Log::warning('Something could be going wrong.');
'Log::error('Something is really going wrong.');

或者在当前版本的Laravel中,像这样:

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

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

  • Laravel 5.0 http://laravel.com/docs/5.0/errors
  • Laravel 4.2: http://laravel.com/docs/4.2/errors

我自己没有尝试过,但是通过库的快速挖掘建议您可以这样做:

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

我找不到一个快捷方式,所以你可能想要创建一个facade来避免重复。

很简单。

你可以在APP的任何地方调用它。

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

在Laravel 6中有一个叫做'stderr'的通道。参见config/logging.php:

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

在你的控制器中:

use Illuminate'Support'Facades'Log;
Log::channel('stderr')->info('Something happened!');

为了更好地解释Dave Morrissey的回答,我在laravel facade中使用Console Output类包装了这些步骤。

1)在你的首选文件夹中创建一个Facade(在我的例子中是app'Facades):

class ConsoleOutput extends Facade {
 protected static function getFacadeAccessor() { 
     return 'consoleOutput';
 }
}

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

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

}

3)将所有这些东西添加到config'app.php文件中,注册提供商和别名。

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

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

ConsoleOutput::writeln('hello');

希望这对你有帮助。

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

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

然后我简单地添加'stdout'作为堆栈日志通道中的一个通道:

    'default' => env('LOG_CHANNEL', 'stack'),
    'stack' => [
        'driver' => 'stack',
        'channels' => ['stdout', 'daily'],
    ],

通过这种方式,我仍然可以在本地开发文件中获取日志(如果您可以访问它,甚至可以在实例中获取日志),但更重要的是,它们被发送到保存在CloudWatch logs中的标准输出。

如果你想从Laravel获得花哨的命令IO(如样式,请求和表),那么我在

下面创建了这个类

指令

我还没有完全验证它是最干净的解决方案等,但它工作得很好(但我只从单元测试用例中测试了它,在Laravel 5.5下)。

所以很可能你可以随意使用

$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%

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

类本身

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;
    }
}

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

Log::info('This is some useful information.');
STDOUT魔术可以通过以下方式完成(您正在设置info消息所在的文件):
Log::useFiles('php://stdout', 'info');

注意事项:这严格用于调试。不要在生产环境中使用任何你不完全理解的

有点晚…我很惊讶,没有人提到Symfony的VarDumper组件,Laravel包含的dd()(以及鲜为人知的dump())实用功能。

$dumpMe = new App'User([ 'name' => 'Cy Rossignol' ]);
(new Symfony'Component'VarDumper'Dumper'CliDumper())->dump( 
    (new Symfony'Component'VarDumper'Cloner'VarCloner())->cloneVar($dumpMe)
);

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

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 ...
}

更进一步,我们甚至可以的输出着色!将这个辅助函数添加到项目中以节省一些输入:

function toConsole($var) 
{
    $dumper = new Symfony'Component'VarDumper'Dumper'CliDumper();
    $dumper->setColors(true);
    $dumper->dump((new Symfony'Component'VarDumper'Cloner'VarCloner())->cloneVar($var));
}

如果我们在一个完整的web服务器(如Apache或Nginx—而不是artisan serve)后面运行应用程序,我们可以稍微修改这个函数,将转储器的美化输出发送到日志(通常是storage/logs/laravele .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));
}

…当然,还可以使用:

查看日志
$ tail -f storage/logs/laravel.log

PHP的error_log()可以很好地快速、一次性地检查简单的值,但是上面显示的函数使调试Laravel中一些更复杂的类的工作变得困难。

还有另一种方法:

$stdout = fopen('php://stdout', 'w');
fwrite($stdout, 'Hello, World!' . PHP_EOL);

PHP_EOL添加新行。

命令类在上课前

use Symfony'Component'Console'Output'ConsoleOutput;

在类方法中

 $output = new ConsoleOutput();
 $output->writeln('my text that appears in command line ');

您可以使用echo和前缀"'033",简单:

Artisan::command('mycommand', function () {
   echo "'033======== Start ========'n";
});

并更改颜色文本:

if (App::environment() === 'production') {
    echo "'033[0;33m======== WARNING ========'033[0m'n";
}

从用药水平6.0 +

$this->info('This will appear in console');
$this->error('This error will appear in console');
$this->line('This line will appear in console);

文档https://laravel.com/docs/6.x/artisan writing-output