AppendLogs.php 2.13 KB
Newer Older
Dominik Hebeler's avatar
Dominik Hebeler committed
1
2
3
4
5
6
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
7
use Monospice\LaravelRedisSentinel\RedisSentinel;
Dominik Hebeler's avatar
Dominik Hebeler committed
8
9
10
11
12
13
14
15
16

class AppendLogs extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'logs:gather';
17
    const LOGKEY = "metager.logs.2021";
Dominik Hebeler's avatar
Dominik Hebeler committed
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Retrieves all Log Entries from Redis and writes them to file';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
43
44
        $this->handleMGLogs();
    }
45

46
47
48
49
    private function handleMGLogs()
    {
        $redis = null;
        
50
        if (config("database.redis.cache.driver", "redis") === "redis") {
51
            $redis = Redis::connection(config('cache.stores.redis.connection'));
52
        } elseif (config("database.redis.cache.driver", "redis") === "redis-sentinel") {
53
            $redis = RedisSentinel::connection(config('cache.stores.redis.connection'));
54
55
        }
        if ($redis === null) {
56
            $this->error("No valid Redis Connection specified");
57
58
            return;
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
59
60
61
62
63
64
65
66
67
68
69

        $elements = [];
        $reply = $redis->pipeline(function ($pipe) use ($elements) {
            $pipe->lrange(\App\Console\Commands\AppendLogs::LOGKEY, 0, -1);
            $pipe->del(\App\Console\Commands\AppendLogs::LOGKEY);
        });
        $elements = $reply[0];
        if (!is_array($elements) || sizeof($elements) <= 0) {
            return;
        }
        if (file_put_contents(\App\MetaGer::getMGLogFile(), implode(PHP_EOL, $elements) . PHP_EOL, FILE_APPEND) === false) {
70
            $this->error("Konnte Log Zeile(n) nicht schreiben");
71
            $redis->lpush(\App\Console\Commands\AppendLogs::LOGKEY, array_reverse($elements));
Dominik Hebeler's avatar
Dominik Hebeler committed
72
        } else {
73
            $this->info("Added " . sizeof($elements) . " lines to todays log!");
Dominik Hebeler's avatar
Dominik Hebeler committed
74
75
76
        }
    }
}