001/*
002 * Copyright (C) Photon Vision.
003 *
004 * This program is free software: you can redistribute it and/or modify
005 * it under the terms of the GNU General Public License as published by
006 * the Free Software Foundation, either version 3 of the License, or
007 * (at your option) any later version.
008 *
009 * This program is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
012 * GNU General Public License for more details.
013 *
014 * You should have received a copy of the GNU General Public License
015 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
016 */
017
018package org.photonvision.common.logging;
019
020import org.photonvision.common.hardware.Platform;
021import org.photonvision.common.util.TimedTaskManager;
022import org.photonvision.jni.QueuedFileLogger;
023
024/**
025 * Listens for and reproduces Linux kernel logs, from /var/log/kern.log, into the Photon logger
026 * ecosystem
027 */
028public class KernelLogLogger {
029    private static KernelLogLogger INSTANCE;
030
031    public static KernelLogLogger getInstance() {
032        if (INSTANCE == null) {
033            INSTANCE = new KernelLogLogger();
034        }
035        return INSTANCE;
036    }
037
038    QueuedFileLogger listener = null;
039    Logger logger = new Logger(KernelLogLogger.class, LogGroup.General);
040
041    public KernelLogLogger() {
042        if (Platform.isLinux()) {
043            listener = new QueuedFileLogger("/var/log/kern.log");
044        } else {
045            System.out.println("NOT for klogs");
046        }
047
048        // arbitrary frequency to grab logs. The underlying native buffer will grow unbounded without
049        // this, lol
050        TimedTaskManager.getInstance().addTask("outputPrintk", this::outputNewPrintks, 1000);
051    }
052
053    public void outputNewPrintks() {
054        if (listener == null) {
055            return;
056        }
057
058        for (var msg : listener.getNewlines()) {
059            // We currently set all logs to debug regardless of their actual level
060            logger.log(msg, LogLevel.DEBUG);
061        }
062    }
063}