001/*
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v2.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014
015package ch.qos.logback.classic.model.processor;
016
017import static ch.qos.logback.core.joran.JoranConstants.INHERITED;
018import static ch.qos.logback.core.joran.JoranConstants.NULL;
019
020import ch.qos.logback.classic.Level;
021import ch.qos.logback.classic.Logger;
022import ch.qos.logback.classic.model.LevelModel;
023import ch.qos.logback.core.Context;
024import ch.qos.logback.core.model.Model;
025import ch.qos.logback.core.model.processor.ModelHandlerBase;
026import ch.qos.logback.core.model.processor.ModelHandlerException;
027import ch.qos.logback.core.model.processor.ModelInterpretationContext;
028import ch.qos.logback.core.spi.ErrorCodes;
029
030public class LevelModelHandler extends ModelHandlerBase {
031
032    boolean inError = false;
033
034    public LevelModelHandler(Context context) {
035        super(context);
036    }
037
038    static public ModelHandlerBase makeInstance(Context context, ModelInterpretationContext ic) {
039        return new LevelModelHandler(context);
040    }
041
042    @Override
043    protected Class<? extends LevelModel> getSupportedModelClass() {
044        return LevelModel.class;
045    }
046
047    @Override
048    public void handle(ModelInterpretationContext mic, Model model) throws ModelHandlerException {
049
050        Object o = mic.peekObject();
051
052        if (!(o instanceof Logger)) {
053            inError = true;
054            addError("For element <level>, could not find a logger at the top of execution stack.");
055            return;
056        }
057
058        Logger l = (Logger) o;
059        String loggerName = l.getName();
060
061        LevelModel levelModel = (LevelModel) model;
062        String levelStr = mic.subst(levelModel.getValue());
063        if (INHERITED.equalsIgnoreCase(levelStr) || NULL.equalsIgnoreCase(levelStr)) {
064            if(Logger.ROOT_LOGGER_NAME.equalsIgnoreCase(loggerName))
065                addError(ErrorCodes.ROOT_LEVEL_CANNOT_BE_SET_TO_NULL);
066            else
067               l.setLevel(null);
068        } else {
069            l.setLevel(Level.toLevel(levelStr, Level.DEBUG));
070        }
071
072        addInfo(loggerName + " level set to " + l.getLevel());
073
074    }
075
076}