import android.os.Environment;
import com.emh.simplepdacall.constant.Constants;
import org.apache.log4j.Level;
import java.io.File;
import de.mindpipe.android.logging.log4j.LogConfigurator;
public class Log4JUtil {
private static final String APP_NAME = "com.compnayName.appName";
private static final String LOG_DIR = Environment.getExternalStorageDirectory().getPath()
+ File.separator + APP_NAME + File.separator + "Log" + File.separator;
private static final String LOG_FILE_PATH = LOG_DIR + "log" + ".txt";
private static final String LOG_FILE_PATTERN = "[%-d{yyyy-MM-dd HH:mm:ss}][Class: %c.%M(%F:%L)] %n[Level: %-5p] - Msg: %m%n";
private static final Level LOG_LEVEL_DEBUG = Level.ALL;
private static final Level LOG_LEVEL_RELEASE = Level.INFO;
public static void configuration() {
LogConfigurator configurator = new LogConfigurator();
if (Constants.IS_DEBUG) {
setLogToDebug(configurator);
} else {
setLogToRelease(configurator);
}
configurator.setFileName(LOG_FILE_PATH);
configurator.setLevel("org.apache", Level.ERROR);
configurator.setFilePattern(LOG_FILE_PATTERN);
configurator.setMaxFileSize(1024 * 1024 * 5);
configurator.setImmediateFlush(true);
configurator.configure();
}
public static void createDir(String path) {
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
}
private static void setLogToDebug(LogConfigurator config) {
config.setRootLevel(LOG_LEVEL_DEBUG);
}
private static void setLogToRelease(LogConfigurator config) {
config.setRootLevel(LOG_LEVEL_RELEASE);
}
}
使用
public class App extends Application {
private static final String TAG = App.class.getSimpleName();
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "application created...");
Log4JUtil.configuration();
}
}
public class MainActivity extends AppCompatActivity {
private Logger logger = Logger.getLogger(MainActivity.class);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG, "MainActivity created...");
setContentView(R.layout.activity_main);
logger.info("onCreate");
}
}
来源:oschina
链接:https://my.oschina.net/yuewawa/blog/4293636