下面列出了org.apache.log4j.spi.ErrorCode#org.apache.log4j.helpers.LogLog 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public
void setDestination(String host, int port, String encoding) {
if (host==null) {
LogLog.error("setDestination: host is null");
host = DEFAULT_HOST;
}
this.host = host;
this.port = port;
this.encoding = encoding;
this.qw = new QuietWriter(
new DatagramStringWriter(host, port, encoding),
errorHandler);
this.stp = new SingleLineTracerPrintWriter(qw);
}
/**
* Sets initial conditions including date/time roll over information, first check,
* scheduledFilename, and calls <code>existingInit</code> to initialize
* the current # of backups.
*/
public void activateOptions() {
//REMOVE removed rollDate from boolean to enable Alex's change
if(datePattern != null) {
now.setTime(System.currentTimeMillis());
sdf = new SimpleDateFormat(datePattern);
int type = computeCheckPeriod();
//printPeriodicity(type);
rc.setType(type);
//next line added as this removes the name check in rollOver
nextCheck = rc.getNextCheckMillis(now);
} else {
if (rollDate)
LogLog.error("Either DatePattern or rollingStyle options are not set for ["+
name+"].");
}
existingInit();
super.activateOptions();
if (rollDate && fileName != null && scheduledFilename == null)
scheduledFilename = fileName + sdf.format(now);
}
/**
* When system exit,this method will be called to close resources
*/
public synchronized void close() {
// The synchronized modifier avoids concurrent append and close operations
if (this.closed)
return;
LogLog.debug("Closing RocketmqLog4jAppender [" + name + "].");
this.closed = true;
try {
ProducerInstance.getProducerInstance().removeAndClose(this.nameServerAddress, this.producerGroup);
} catch (Exception e) {
LogLog.error("Closing RocketmqLog4jAppender [" + name + "] nameServerAddress:" + nameServerAddress + " group:" + producerGroup + " " + e.getMessage());
}
// Help garbage collection
producer = null;
}
/**
* When system exit,this method will be called to close resources 当系统退出时,将调用此方法来关闭资源
*/
public synchronized void close() {
// The synchronized modifier avoids concurrent append and close operations
if (this.closed)
return;
LogLog.debug("Closing RocketmqLog4jAppender [" + name + "].");
this.closed = true;
try {
ProducerInstance.getProducerInstance().removeAndClose(this.nameServerAddress, this.producerGroup);
} catch (Exception e) {
LogLog.error("Closing RocketmqLog4jAppender [" + name + "] nameServerAddress:" + nameServerAddress + " group:" + producerGroup + " " + e.getMessage());
}
// Help garbage collection
producer = null;
}
public void activateOptions()
{
super.activateOptions();
LogLog.debug("Max backup file kept: "+ maxBackupIndex + ".");
if(datePattern != null && fileName != null)
{
now.setTime(System.currentTimeMillis());
sdf = new SimpleDateFormat(datePattern);
int type = computeCheckPeriod();
printPeriodicity(type);
rpc.setType(type);
File file = new File(fileName);
scheduledFilename = fileName+sdf.format(new Date(file.lastModified()));
}
else
{
LogLog.error("Either File or DatePattern options are not set for appender ["
+name+"].");
}
}
/**
* This method differentiates DailyRollingFileAppender from its
* super class.
*
* <p>Before actually logging, this method will check whether it is
* time to do a rollover. If it is, it will schedule the next
* rollover time and then rollover.
* */
protected void subAppend(LoggingEvent event)
{
long n = System.currentTimeMillis();
if (n >= nextCheck)
{
now.setTime(n);
nextCheck = rpc.getNextCheckMillis(now);
try
{
rollOver();
}
catch(IOException ioe)
{
LogLog.error("rollOver() failed.", ioe);
}
}
super.subAppend(event);
}
public void activateOptions()
{
super.activateOptions();
LogLog.debug("Max backup file kept: "+ maxBackupIndex + ".");
if(datePattern != null && fileName != null)
{
now.setTime(System.currentTimeMillis());
sdf = new SimpleDateFormat(datePattern);
int type = computeCheckPeriod();
printPeriodicity(type);
rpc.setType(type);
File file = new File(fileName);
scheduledFilename = fileName+sdf.format(new Date(file.lastModified()));
}
else
{
LogLog.error("Either File or DatePattern options are not set for appender ["
+name+"].");
}
}
/**
* This method differentiates DailyRollingFileAppender from its
* super class.
*
* <p>Before actually logging, this method will check whether it is
* time to do a rollover. If it is, it will schedule the next
* rollover time and then rollover.
* */
protected void subAppend(LoggingEvent event)
{
long n = System.currentTimeMillis();
if (n >= nextCheck)
{
now.setTime(n);
nextCheck = rpc.getNextCheckMillis(now);
try
{
rollOver();
}
catch(IOException ioe)
{
LogLog.error("rollOver() failed.", ioe);
}
}
super.subAppend(event);
}
/**
* When system exit,this method will be called to close resources
*/
public synchronized void close() {
// The synchronized modifier avoids concurrent append and close operations
if (this.closed)
return;
LogLog.debug("Closing RocketmqLog4jAppender [" + name + "].");
this.closed = true;
try {
ProducerInstance.getProducerInstance().removeAndClose(this.nameServerAddress, this.producerGroup);
} catch (Exception e) {
LogLog.error("Closing RocketmqLog4jAppender [" + name + "] nameServerAddress:" + nameServerAddress + " group:" + producerGroup + " " + e.getMessage());
}
// Help garbage collection
producer = null;
}
/**
* This method differentiates DailyRollingFileAppender from its super class.
*
* <p>
* Before actually logging, this method will check whether it is time to do
* a rollover. If it is, it will schedule the next rollover time and then
* rollover.
*/
@Override
protected void subAppend(LoggingEvent event) {
long n = System.currentTimeMillis();
if (n >= nextCheck) {
now.setTime(n);
nextCheck = rpc.getNextCheckMillis(now);
try {
rollOver();
} catch (IOException ioe) {
LogLog.error("rollOver() failed.", ioe);
}
}
super.subAppend(event);
}
void printPeriodicity(int type) {
switch (type) {
case TOP_OF_MINUTE:
LogLog.debug("Appender [" + name + "] to be rolled every minute.");
break;
case TOP_OF_HOUR:
LogLog.debug("Appender [" + name + "] to be rolled on top of every hour.");
break;
case HALF_DAY:
LogLog.debug("Appender [" + name + "] to be rolled at midday and midnight.");
break;
case TOP_OF_DAY:
LogLog.debug("Appender [" + name + "] to be rolled at midnight.");
break;
case TOP_OF_WEEK:
LogLog.debug("Appender [" + name + "] to be rolled at start of week.");
break;
case TOP_OF_MONTH:
LogLog.debug("Appender [" + name + "] to be rolled at start of every month.");
break;
default:
LogLog.warn("Unknown periodicity for appender [" + name + "].");
}
}
/**
* This method differentiates DailyRollingFileAppender from its
* super class.
*
* <p>Before actually logging, this method will check whether it is
* time to do a rollover. If it is, it will schedule the next
* rollover time and then rollover.
* */
@Override
protected void subAppend(LoggingEvent event) {
long n = System.currentTimeMillis();
if (n >= nextCheck) {
now.setTime(n);
nextCheck = rc.getNextCheckMillis(now);
try {
rollOver();
} catch (IOException ioe) {
if (ioe instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
LogLog.error("rollOver() failed.", ioe);
}
}
super.subAppend(event);
}
/**
* Close this JMSQueueAppender. Closing releases all resources used by the
* appender. A closed appender cannot be re-opened.
*/
public synchronized // avoid concurrent append and close operations
void close() {
if(this.closed)
return;
LogLog.debug("Closing appender ["+name+"].");
this.closed = true;
try {
if(queueSession != null)
queueSession.close();
if(queueConnection != null)
queueConnection.close();
} catch(Exception e) {
LogLog.error("Error while closing JMSQueueAppender ["+name+"].", e);
}
// Help garbage collection
queueSender = null;
queueSession = null;
queueConnection = null;
}
/**
* Activate the options set using <tt>setPort()</tt>
* and <tt>setHostname()</tt>
*
* @throws FlumeException if the <tt>hostname</tt> and
* <tt>port</tt> combination is invalid.
*/
@Override
public void activateOptions() throws FlumeException {
Properties props = new Properties();
props.setProperty(RpcClientConfigurationConstants.CONFIG_HOSTS, "h1");
props.setProperty(RpcClientConfigurationConstants.CONFIG_HOSTS_PREFIX + "h1",
hostname + ":" + port);
props.setProperty(RpcClientConfigurationConstants.CONFIG_CONNECT_TIMEOUT,
String.valueOf(timeout));
props.setProperty(RpcClientConfigurationConstants.CONFIG_REQUEST_TIMEOUT,
String.valueOf(timeout));
try {
rpcClient = RpcClientFactory.getInstance(props);
if (layout != null) {
layout.activateOptions();
}
} catch (FlumeException e) {
String errormsg = "RPC client creation failed! " +
e.getMessage();
LogLog.error(errormsg);
if (unsafeMode) {
return;
}
throw e;
}
}
void printPeriodicity(int type) {
switch (type) {
case TOP_OF_MINUTE:
LogLog.debug("Appender [[+name+]] to be rolled every minute.");
break;
case TOP_OF_HOUR:
LogLog.debug("Appender [" + name + "] to be rolled on top of every hour.");
break;
case HALF_DAY:
LogLog.debug("Appender [" + name + "] to be rolled at midday and midnight.");
break;
case TOP_OF_DAY:
LogLog.debug("Appender [" + name + "] to be rolled at midnight.");
break;
case TOP_OF_WEEK:
LogLog.debug("Appender [" + name + "] to be rolled at start of week.");
break;
case TOP_OF_MONTH:
LogLog.debug("Appender [" + name + "] to be rolled at start of every month.");
break;
default:
LogLog.warn("Unknown periodicity for appender [[+name+]].");
}
}
@Override
public void activateOptions() {
super.activateOptions();
formatter = DateTimeFormat.forPattern(timeFormat).withZone(DateTimeZone.forID(timeZone));
producer = createProducer();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
doClose();
} catch (Exception e) {
LogLog.error("Failed to close LoghubAppender.", e);
}
}
});
}
/**
* 向kafka send
* @param value
*/
private void send(String value) {
// 对value的大小进行判定,当大于某个值认为该日志太大直接丢弃(防止影响到kafka)
if (value.length() > 10000) {
return;
}
final ProducerRecord<byte[], String> record = new ProducerRecord<>(this.topic, this.key, value);
LazySingletonProducer.getInstance(this.config).send(record, new Callback() {
@Override
public void onCompletion(RecordMetadata recordMetadata, Exception e) {
// TODO: 异常发生如何处理(直接停掉appender)
if (null != e) {
closed = true;
LogLog.error("kafka send error in appender", e);
// 发生异常,kafkaAppender 停止收集,向节点写入数据(监控系统会感知进行报警)
if (flag.get() == true) {
KafkaAppender.this.heartbeatStart();
zkRegister.write(Constants.SLASH + app + Constants.SLASH + host, NodeMode.EPHEMERAL,
String.valueOf(Constants.APP_APPENDER_STOP_KEY + Constants.SEMICOLON + System.currentTimeMillis()) + Constants.SEMICOLON + SysUtil.userDir);
flag.compareAndSet(true, false);
}
}
}
});
}
/**
* When system exit,this method will be called to close resources
*/
public synchronized void close() {
// The synchronized modifier avoids concurrent append and close operations
if (this.closed)
return;
LogLog.debug("Closing RocketmqLog4jAppender [" + name + "].");
this.closed = true;
try {
ProducerInstance.getProducerInstance().removeAndClose(this.nameServerAddress, this.producerGroup);
} catch (Exception e) {
LogLog.error("Closing RocketmqLog4jAppender [" + name + "] nameServerAddress:" + nameServerAddress + " group:" + producerGroup + " " + e.getMessage());
}
// Help garbage collection
producer = null;
}
/**
* Override FileAppender.setFile to avoid creating an empty log file before
* the code has a chance to customize the file name.
*/
public synchronized void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)
throws IOException {
LogLog.debug("setFile called: " + fileName + ", " + append);
if (this.qw != null) {
return;
}
// set a stdout writer just in case
reset();
Writer fw = createWriter(System.out);
this.setQWForFiles(fw);
this.fileName = fileName;
this.fileAppend = append;
this.bufferedIO = bufferedIO;
this.bufferSize = bufferSize;
LogLog.debug("setFile ended");
}
private Logger createLog4jLogger(TaskId taskId) {
LogLog.setQuietMode(true); // error about log should not be logged
Logger tempLogger = Logger.getLogger(Log4JTaskLogs.JOB_LOGGER_PREFIX + taskId.getJobId() + "." +
taskId.value());
tempLogger.setLevel(Log4JTaskLogs.STDOUT_LEVEL);
tempLogger.setAdditivity(false);
resetLogContextForImmediateService();
tempLogger.removeAllAppenders();
taskLogAppender = new AsyncAppenderWithStorage(getLogMaxSize(taskId));
tempLogger.addAppender(taskLogAppender);
return tempLogger;
}
/**
* Activate the options set using <tt>setPort()</tt>
* and <tt>setHostname()</tt>
* @throws FlumeException if the <tt>hostname</tt> and
* <tt>port</tt> combination is invalid.
*/
@Override
public void activateOptions() throws FlumeException {
Properties props = new Properties();
props.setProperty(RpcClientConfigurationConstants.CONFIG_HOSTS, "h1");
props.setProperty(RpcClientConfigurationConstants.CONFIG_HOSTS_PREFIX + "h1",
hostname + ":" + port);
props.setProperty(RpcClientConfigurationConstants.CONFIG_CONNECT_TIMEOUT,
String.valueOf(timeout));
props.setProperty(RpcClientConfigurationConstants.CONFIG_REQUEST_TIMEOUT,
String.valueOf(timeout));
try {
rpcClient = RpcClientFactory.getInstance(props);
if (layout != null) {
layout.activateOptions();
}
} catch (FlumeException e) {
String errormsg = "RPC client creation failed! " +
e.getMessage();
LogLog.error(errormsg);
throw e;
}
}
/**
* Close this IMAppender. Closing all resources used by the appender. A closed appender cannot be re-opened.
*/
@Override
public synchronized void close() {// o_clusterOK by:fj
if (this.closed) {
return;
}
LogLog.debug("Closing appender [" + name + "]");
this.closed = true;
// Closes the connection by setting presence to unavailable
// then closing the stream to the XMPP server.
if (con != null) {
con.disconnect();
}
// Help GC
con = null;
chats.clear();
chats = null;
groupchat = null;
}
/**
* This method performs threshold checks and invokes filters before
* delegating actual logging to the subclasses specific {@link
* AppenderSkeleton#append} method.
* */
public
synchronized
void doAppend(LoggingEvent event) {
if(closed) {
LogLog.error("Attempted to append to closed appender named ["+name+"].");
return;
}
if(!isAsSevereAsThreshold(event.getLevel())) {
return;
}
Filter f = this.headFilter;
FILTER_LOOP:
while(f != null) {
switch(f.decide(event)) {
case Filter.DENY: return;
case Filter.ACCEPT: break FILTER_LOOP;
case Filter.NEUTRAL: f = f.getNext();
}
}
this.append(event);
}
/**
Prints the message and the stack trace of the exception on
<code>System.err</code>.
*/
public
void error(String message, Exception e, int errorCode, LoggingEvent event) {
LogLog.debug("FB: The following error reported: " + message, e);
LogLog.debug("FB: INITIATING FALLBACK PROCEDURE.");
if (loggers != null) {
for(int i = 0; i < loggers.size(); i++) {
Logger l = (Logger) loggers.elementAt(i);
LogLog.debug("FB: Searching for ["+primary.getName()+"] in logger ["
+l.getName() + "].");
LogLog.debug("FB: Replacing ["+primary.getName()+"] by ["
+ backup.getName() + "] in logger ["+ l.getName() +"].");
l.removeAppender(primary);
LogLog.debug("FB: Adding appender ["+backup.getName()+"] to logger "
+ l.getName());
l.addAppender(backup);
}
}
}
public Saros() {
try {
InputStream sarosProperties =
Saros.class.getClassLoader().getResourceAsStream("saros.properties"); // $NON-NLS-1$
if (sarosProperties == null) {
LogLog.warn(
"could not initialize Saros properties because the 'saros.properties'"
+ " file could not be found on the current JAVA class path");
} else {
System.getProperties().load(sarosProperties);
sarosProperties.close();
}
} catch (Exception e) {
LogLog.error("could not load saros property file 'saros.properties'", e); // $NON-NLS-1$
}
setInitialized(false);
lifecycle = EclipsePluginLifecycle.getInstance(this);
}
/**
* Closes underlying client.
* If <tt>append()</tt> is called after this function is called,
* it will throw an exception.
* @throws FlumeException if errors occur during close
*/
@Override
public synchronized void close() throws FlumeException {
// Any append calls after this will result in an Exception.
if (rpcClient != null) {
try {
rpcClient.close();
} catch (FlumeException ex) {
LogLog.error("Error while trying to close RpcClient.", ex);
if (unsafeMode) {
return;
}
throw ex;
} finally {
rpcClient = null;
}
} else {
String errorMsg = "Flume log4jappender already closed!";
LogLog.error(errorMsg);
if(unsafeMode) {
return;
}
throw new FlumeException(errorMsg);
}
}
/**
This method determines if there is a sense in attempting to append.
<p>It checks whether there is a set output target and also if
there is a set layout. If these checks fail, then the boolean
value <code>false</code> is returned. */
protected
boolean checkEntryConditions() {
if(this.closed) {
LogLog.warn("Not allowed to write to a closed appender.");
return false;
}
if(this.qw == null) {
errorHandler.error("No output stream or file set for the appender named ["+
name+"].");
return false;
}
if(this.layout == null) {
errorHandler.error("No layout set for the appender named ["+ name+"].");
return false;
}
return true;
}
public void activateOptions() {
super.activateOptions();
LogLog.debug("Max backup file kept: " + maxBackupIndex + ".");
if (datePattern != null && fileName != null) {
now.setTime(System.currentTimeMillis());
sdf = new SimpleDateFormat(datePattern);
int type = computeCheckPeriod();
printPeriodicity(type);
rpc.setType(type);
File file = new File(fileName);
scheduledFilename = fileName + sdf.format(new Date(file.lastModified()));
} else {
LogLog.error("Either File or DatePattern options are not set for appender [" + name + "].");
}
}
/**
Activate the specified options, such as the smtp host, the
recipient, from, etc. */
public
void activateOptions() {
Session session = createSession();
msg = new MimeMessage(session);
try {
addressMessage(msg);
if(subject != null) {
msg.setSubject(subject);
}
} catch(MessagingException e) {
LogLog.error("Could not activate SMTPAppender options.", e );
}
if (evaluator instanceof OptionHandler) {
((OptionHandler) evaluator).activateOptions();
}
}
/**
Add a renderer to a hierarchy passed as parameter.
*/
static
public
void addRenderer(RendererSupport repository, String renderedClassName,
String renderingClassName) {
LogLog.debug("Rendering class: ["+renderingClassName+"], Rendered class: ["+
renderedClassName+"].");
ObjectRenderer renderer = (ObjectRenderer)
OptionConverter.instantiateByClassName(renderingClassName,
ObjectRenderer.class,
null);
if(renderer == null) {
LogLog.error("Could not instantiate renderer ["+renderingClassName+"].");
return;
} else {
try {
Class renderedClass = Loader.loadClass(renderedClassName);
repository.setRenderer(renderedClass, renderer);
} catch(ClassNotFoundException e) {
LogLog.error("Could not find class ["+renderedClassName+"].", e);
}
}
}