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 edu.wpi.first.cscore.CameraServerJNI;
021import java.nio.file.Path;
022
023/** Redirect cscore logs to our logger */
024public class PvCSCoreLogger {
025    private static PvCSCoreLogger INSTANCE;
026
027    public static PvCSCoreLogger getInstance() {
028        if (INSTANCE == null) {
029            INSTANCE = new PvCSCoreLogger();
030        }
031        return INSTANCE;
032    }
033
034    private Logger logger;
035
036    private PvCSCoreLogger() {
037        CameraServerJNI.setLogger(this::logMsg, 7);
038        this.logger = new Logger(getClass(), LogGroup.CSCore);
039    }
040
041    private void logMsg(int level, String file, int line, String msg) {
042        if (level == 20) {
043            logger.info(msg);
044            return;
045        }
046
047        file = Path.of(file).getFileName().toString();
048
049        String levelmsg;
050        LogLevel pvlevel;
051        if (level >= 50) {
052            levelmsg = "CRITICAL";
053            pvlevel = LogLevel.ERROR;
054        } else if (level >= 40) {
055            levelmsg = "ERROR";
056            pvlevel = LogLevel.ERROR;
057        } else if (level >= 30) {
058            levelmsg = "WARNING";
059            pvlevel = LogLevel.WARN;
060        } else if (level >= 20) {
061            levelmsg = "INFO";
062            pvlevel = LogLevel.INFO;
063        } else {
064            levelmsg = "DEBUG";
065            pvlevel = LogLevel.DEBUG;
066        }
067        logger.log(
068                "CS: " + levelmsg + " " + level + ": " + msg + " (" + file + ":" + line + ")", pvlevel);
069    }
070}