All Downloads are FREE. Search and download functionalities are using the official Maven repository.

br.com.objectos.way.base.log.AbstractLogBuilder Maven / Gradle / Ivy

/*
 * Copyright 2014 Objectos, Fábrica de Software LTDA.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package br.com.objectos.way.base.log;

import java.lang.reflect.Method;
import java.util.List;

import org.aopalliance.intercept.MethodInvocation;

import com.google.common.collect.ImmutableList;

/**
 * @author [email protected] (Marcio Endo)
 */
abstract class AbstractLogBuilder implements LogBuilder {

  private final StringBuilder messageBuilder = new StringBuilder();

  private final LogLevel level;
  private final Object self;
  private final Method method;
  private final List args;

  public AbstractLogBuilder(LogLevel level, MethodInvocation invocation) {
    this.level = level;

    self = invocation.getThis();
    method = invocation.getMethod();

    Object[] arguments = invocation.getArguments();
    args = ImmutableList.copyOf(arguments);
  }

  @Override
  public Log build() {
    return new Log(this);
  }

  @Override
  public T add(String text) {
    messageBuilder.append(text);
    return self();
  }
  @Override
  public T add(String template, Object... args) {
    String text = String.format(template, args);
    return add(text);
  }

  public T addArg(int index) {
    Object arg = args.get(index);
    String text = arg.toString();
    return add(text);
  }

  public T addArgs() {
    String text = args.toString();
    return add(text);
  }

  @Override
  public T addClassName() {
    Class type = self.getClass();
    String className = type.getSimpleName();
    String text = WayLog.cleanClassName(className);
    return add(text);
  }

  @Override
  public T addMethodName() {
    String text = method.getName();
    return add(text);
  }

  abstract T self();

  LogLevel getLevel() {
    return level;
  }

  Class getType() {
    return self.getClass();
  }

  Method getMethod() {
    return method;
  }

  String getMessage() {
    return messageBuilder.toString();
  }

}