下面列出了org.apache.log4j.helpers.LogLog#error ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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;
}
}
/**
* 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;
}
/**
Release the underlying ServerMonitor thread, and drop the connections
to all connected remote servers. */
public
void cleanUp() {
// stop the monitor thread
LogLog.debug("stopping ServerSocket");
serverMonitor.stopMonitor();
serverMonitor = null;
// close all of the connections
LogLog.debug("closing client connections");
while (oosList.size() != 0) {
ObjectOutputStream oos = (ObjectOutputStream)oosList.elementAt(0);
if(oos != null) {
try {
oos.close();
}
catch(IOException e) {
LogLog.error("could not close oos.", e);
}
oosList.removeElementAt(0);
}
}
}
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);
}
/**
* 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);
}
public void activateOptions() {
LogLog.debug("Getting initial context.");
if (!checkEntryConditions()) {
return;
}
try {
producer = ProducerInstance.getProducerInstance().getInstance(nameServerAddress, producerGroup);
} catch (Exception e) {
LogLog.error("activateOptions nameserver:" + nameServerAddress + " group:" + producerGroup + " " + e.getMessage());
}
}
/**
Used internally to parse a level element.
*/
protected
void parseLevel(Element element, Logger logger, boolean isRoot) {
String catName = logger.getName();
if(isRoot) {
catName = "root";
}
String priStr = subst(element.getAttribute(VALUE_ATTR));
LogLog.debug("Level value for "+catName+" is ["+priStr+"].");
if(INHERITED.equalsIgnoreCase(priStr) || NULL.equalsIgnoreCase(priStr)) {
if(isRoot) {
LogLog.error("Root level cannot be inherited. Ignoring directive.");
} else {
logger.setLevel(null);
}
} else {
String className = subst(element.getAttribute(CLASS_ATTR));
if(EMPTY_STR.equals(className)) {
logger.setLevel(OptionConverter.toLevel(priStr, Level.DEBUG));
} else {
LogLog.debug("Desired Level sub-class: ["+className+']');
try {
Class clazz = Loader.loadClass(className);
Method toLevelMethod = clazz.getMethod("toLevel",
ONE_STRING_PARAM);
Level pri = (Level) toLevelMethod.invoke(null,
new Object[] {priStr});
logger.setLevel(pri);
} catch (Exception oops) {
LogLog.error("Could not create level ["+priStr+
"]. Reported error follows.", oops);
return;
}
}
}
LogLog.debug(catName + " level set to " + logger.getLevel());
}
public
String convert(LoggingEvent event) {
date.setTime(event.timeStamp);
String converted = null;
try {
converted = df.format(date);
}
catch (Exception ex) {
LogLog.error("Error occured while converting date.", ex);
}
return converted;
}
protected void subAppend(LoggingEvent event) {
long n = System.currentTimeMillis();
if (n >= this.nextCheck) {
this.now.setTime(n);
this.nextCheck = this.rpc.getNextCheckMillis(this.now);
try {
this.rollOver();
} catch (IOException var5) {
LogLog.error("rollOver() failed.", var5);
}
}
super.subAppend(event);
}
/**
Continually accepts client connections. Client connections
are refused when MAX_CONNECTIONS is reached.
*/
public void run() {
while(!serverSocket.isClosed()) {
try {
Socket newClient = serverSocket.accept();
PrintWriter pw = new PrintWriter(newClient.getOutputStream());
if(connections.size() < MAX_CONNECTIONS) {
connections.addElement(newClient);
writers.addElement(pw);
pw.print("TelnetAppender v1.0 (" + connections.size()
+ " active connections)\r\n\r\n");
pw.flush();
} else {
pw.print("Too many connections.\r\n");
pw.flush();
newClient.close();
}
} catch(Exception e) {
if (!serverSocket.isClosed()) {
LogLog.error("Encountered error while in SocketHandler loop.", e);
}
break;
}
}
try {
serverSocket.close();
} catch(IOException ex) {
}
}
static
InetAddress getAddressByName(String host) {
try {
return InetAddress.getByName(host);
} catch(Exception e) {
LogLog.error("Could not find address of ["+host+"].", e);
return null;
}
}
/**
Setting a null value to the level of the root logger may have catastrophic
results. We prevent this here.
@since 0.8.3 */
public final void setLevel(Level level) {
if (level == null) {
LogLog.error(
"You have tried to set a null level to root.", new Throwable());
} else {
this.level = level;
}
}
/**
Setting a null value to the level of the root category may have catastrophic
results. We prevent this here.
@since 0.8.3 */
final
public
void setLevel(Level level) {
if(level == null) {
LogLog.error("You have tried to set a null level to root.",
new Throwable());
}
else {
this.level = level;
}
}
/**
Render a {@link javax.jms.Message}.
*/
public
String doRender(Object o) {
if(o instanceof Message) {
StringBuffer sbuf = new StringBuffer();
Message m = (Message) o;
try {
sbuf.append("DeliveryMode=");
switch(m.getJMSDeliveryMode()) {
case DeliveryMode.NON_PERSISTENT :
sbuf.append("NON_PERSISTENT");
break;
case DeliveryMode.PERSISTENT :
sbuf.append("PERSISTENT");
break;
default: sbuf.append("UNKNOWN");
}
sbuf.append(", CorrelationID=");
sbuf.append(m.getJMSCorrelationID());
sbuf.append(", Destination=");
sbuf.append(m.getJMSDestination());
sbuf.append(", Expiration=");
sbuf.append(m.getJMSExpiration());
sbuf.append(", MessageID=");
sbuf.append(m.getJMSMessageID());
sbuf.append(", Priority=");
sbuf.append(m.getJMSPriority());
sbuf.append(", Redelivered=");
sbuf.append(m.getJMSRedelivered());
sbuf.append(", ReplyTo=");
sbuf.append(m.getJMSReplyTo());
sbuf.append(", Timestamp=");
sbuf.append(m.getJMSTimestamp());
sbuf.append(", Type=");
sbuf.append(m.getJMSType());
//Enumeration enum = m.getPropertyNames();
//while(enum.hasMoreElements()) {
// String key = (String) enum.nextElement();
// sbuf.append("; "+key+"=");
// sbuf.append(m.getStringProperty(key));
//}
} catch(JMSException e) {
LogLog.error("Could not parse Message.", e);
}
return sbuf.toString();
} else {
return o.toString();
}
}
private synchronized void initClient()
{
// We should be able to go without an Atomic variable here. There are two potential problems:
// 1. Multiple threads read intialized=false and call init client. However, the method is
// synchronized so only one will get the lock first, and the others will drop out here.
// 2. One thread reads initialized=true before initClient finishes. This also should not
// happen as the lock should include a memory barrier.
if (initialized || initializationFailed)
return;
// Just while we initialise the client, we must temporarily
// disable all logging or else we get into an infinite loop
Level globalThreshold = LogManager.getLoggerRepository().getThreshold();
LogManager.getLoggerRepository().setThreshold(Level.OFF);
try
{
Cluster.Builder builder = Cluster.builder()
.addContactPoints(hosts.split(",\\s*"))
.withPort(port)
.withLoadBalancingPolicy(new RoundRobinPolicy());
// Kerberos provides authentication anyway, so a username and password are superfluous. SSL
// is compatible with either.
boolean passwordAuthentication = !password.equals("") || !username.equals("");
if (authProviderOptions != null && passwordAuthentication)
throw new IllegalArgumentException("Authentication via both Cassandra usernames and Kerberos " +
"requested.");
// Encryption
if (authProviderOptions != null)
builder = builder.withAuthProvider(getAuthProvider());
if (sslOptions != null)
builder = builder.withSSL(getSslOptions());
if (passwordAuthentication)
builder = builder.withCredentials(username, password);
cluster = builder.build();
session = cluster.connect();
setupSchema();
setupStatement();
}
catch (Exception e)
{
LogLog.error("Error ", e);
errorHandler.error("Error setting up cassandra logging schema: " + e);
//If the user misconfigures the port or something, don't keep failing.
initializationFailed = true;
}
finally
{
//Always reenable logging
LogManager.getLoggerRepository().setThreshold(globalThreshold);
initialized = true;
}
}
/**
* 初始化kafka config
*/
private void initKafkaConfig() {
if (!LazySingletonProducer.isInstanced()) {
// app配置
if (StringUtil.isBlank(this.host)) {
// host未获取到
LogLog.error("can't get the host");
closed = true;
return;
}
if (StringUtil.isBlank(this.app)) {
// app name未设置
LogLog.error("log4j.xml is not set the app");
closed = true;
return;
}
// zk配置
if (StringUtil.isBlank(this.zkServers)) {
// zk地址未设置
LogLog.error("can't get zkServers");
closed = true;
return;
}
if (StringUtil.isBlank(this.topic)) {
// topic未设置(或者设置成了""),无法写入kafka
LogLog.error("topic is not set, appender: " + name);
closed = true;
return;
}
if (StringUtil.isBlank(this.mail)) {
// 报警mail未设置
LogLog.error("mail is not set, appender: " + name);
closed = true;
return;
}
if (StringUtil.isBlank(this.rpc) || !this.checkRpcType(this.rpc)) {
// rpc未设置或者rpc值不对
LogLog.error("rpc is not set or value not right, appender: " + name);
closed = true;
return;
}
new Thread() {
@Override
public void run() {
// 初始化zk
KafkaAppender.this.zkRegister = new ZkRegister(new ZkClient(zkServers, 60000, 5000));
// 对app重新编号,防止一台host部署一个app的多个实例
KafkaAppender.this.app = KafkaAppender.this.app + KafkaAppender.this.zkRegister.mark(KafkaAppender.this.app, KafkaAppender.this.host);
KafkaAppender.this.key = ByteBuffer.allocate(4).putInt(new StringBuilder(app).append(host).toString().hashCode()).array();
// 注册节点
KafkaAppender.this.zkRegister.registerNode(KafkaAppender.this.host, KafkaAppender.this.app, KafkaAppender.this.mail);
// rpc trace注册中心
KafkaAppender.this.zkRegister.registerRpc(KafkaAppender.this.host, KafkaAppender.this.app, KafkaAppender.this.rpc);
}
}.start();
if (StringUtil.isNotBlank(this.bootstrapServers)) {
this.config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, this.bootstrapServers);
}
if (StringUtil.isNotBlank(this.acks)) {
this.config.put(ProducerConfig.ACKS_CONFIG, this.acks);
}
if (StringUtil.isNotBlank(this.lingerMs)) {
this.config.put(ProducerConfig.LINGER_MS_CONFIG, this.lingerMs);
}
if (StringUtil.isNotBlank(this.maxBlockMs)) {
this.config.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, this.maxBlockMs);
}
if (StringUtil.isNotBlank(this.app) && StringUtil.isNotBlank(this.host)) {
this.config.put(ProducerConfig.CLIENT_ID_CONFIG, this.app + Constants.MIDDLE_LINE + this.host + Constants.MIDDLE_LINE + "log4j");
}
LazySingletonProducer.getInstance(this.config);
}
}
/**
Send the contents of the cyclic buffer as an e-mail message.
*/
protected
void sendBuffer() {
// Note: this code already owns the monitor for this
// appender. This frees us from needing to synchronize on 'cb'.
try {
MimeBodyPart part = new MimeBodyPart();
StringBuffer sbuf = new StringBuffer();
String t = layout.getHeader();
if(t != null)
sbuf.append(t);
int len = cb.length();
for(int i = 0; i < len; i++) {
//sbuf.append(MimeUtility.encodeText(layout.format(cb.get())));
LoggingEvent event = cb.get();
sbuf.append(layout.format(event));
if(layout.ignoresThrowable()) {
String[] s = event.getThrowableStrRep();
if (s != null) {
for(int j = 0; j < s.length; j++) {
sbuf.append(s[j]);
sbuf.append(Layout.LINE_SEP);
}
}
}
}
t = layout.getFooter();
if(t != null)
sbuf.append(t);
part.setContent(sbuf.toString(), layout.getContentType());
Multipart mp = new MimeMultipart();
mp.addBodyPart(part);
msg.setContent(mp);
msg.setSentDate(new Date());
Transport.send(msg);
} catch(Exception e) {
LogLog.error("Error occured while sending e-mail notification.", e);
}
}
/**
Rollover the current file to a new file.
*/
void rollOver() throws IOException {
/* Compute filename, but only if datePattern is specified */
if (datePattern == null) {
errorHandler.error("Missing DatePattern option in rollOver().");
return;
}
String datedFilename = fileName+sdf.format(now);
// It is too early to roll over because we are still within the
// bounds of the current interval. Rollover will occur once the
// next interval is reached.
if (scheduledFilename.equals(datedFilename)) {
return;
}
// close current file, and rename it to datedFilename
this.closeFile();
File target = new File(scheduledFilename);
if (target.exists()) {
target.delete();
}
File file = new File(fileName);
boolean result = file.renameTo(target);
if(result) {
LogLog.debug(fileName +" -> "+ scheduledFilename);
} else {
LogLog.error("Failed to rename ["+fileName+"] to ["+scheduledFilename+"].");
}
try {
// This will also close the file. This is OK since multiple
// close operations are safe.
this.setFile(fileName, false, this.bufferedIO, this.bufferSize);
}
catch(IOException e) {
errorHandler.error("setFile("+fileName+", false) call failed.");
}
scheduledFilename = datedFilename;
}
public
PatternConverter parse() {
char c;
i = 0;
while(i < patternLength) {
c = pattern.charAt(i++);
switch(state) {
case LITERAL_STATE:
// In literal state, the last char is always a literal.
if(i == patternLength) {
currentLiteral.append(c);
continue;
}
if(c == ESCAPE_CHAR) {
// peek at the next char.
switch(pattern.charAt(i)) {
case ESCAPE_CHAR:
currentLiteral.append(c);
i++; // move pointer
break;
case 'n':
currentLiteral.append(Layout.LINE_SEP);
i++; // move pointer
break;
default:
if(currentLiteral.length() != 0) {
addToList(new LiteralPatternConverter(
currentLiteral.toString()));
//LogLog.debug("Parsed LITERAL converter: \""
// +currentLiteral+"\".");
}
currentLiteral.setLength(0);
currentLiteral.append(c); // append %
state = CONVERTER_STATE;
formattingInfo.reset();
}
}
else {
currentLiteral.append(c);
}
break;
case CONVERTER_STATE:
currentLiteral.append(c);
switch(c) {
case '-':
formattingInfo.leftAlign = true;
break;
case '.':
state = DOT_STATE;
break;
default:
if(c >= '0' && c <= '9') {
formattingInfo.min = c - '0';
state = MIN_STATE;
}
else
finalizeConverter(c);
} // switch
break;
case MIN_STATE:
currentLiteral.append(c);
if(c >= '0' && c <= '9')
formattingInfo.min = formattingInfo.min*10 + (c - '0');
else if(c == '.')
state = DOT_STATE;
else {
finalizeConverter(c);
}
break;
case DOT_STATE:
currentLiteral.append(c);
if(c >= '0' && c <= '9') {
formattingInfo.max = c - '0';
state = MAX_STATE;
}
else {
LogLog.error("Error occured in position "+i
+".\n Was expecting digit, instead got char \""+c+"\".");
state = LITERAL_STATE;
}
break;
case MAX_STATE:
currentLiteral.append(c);
if(c >= '0' && c <= '9')
formattingInfo.max = formattingInfo.max*10 + (c - '0');
else {
finalizeConverter(c);
state = LITERAL_STATE;
}
break;
} // switch
} // while
if(currentLiteral.length() != 0) {
addToList(new LiteralPatternConverter(currentLiteral.toString()));
//LogLog.debug("Parsed LITERAL converter: \""+currentLiteral+"\".");
}
return head;
}
/**
Used internally to parse an appender element.
*/
protected
Appender parseAppender (Element appenderElement) {
String className = subst(appenderElement.getAttribute(CLASS_ATTR));
LogLog.debug("Class name: [" + className+']');
try {
Object instance = Loader.loadClass(className).newInstance();
Appender appender = (Appender)instance;
PropertySetter propSetter = new PropertySetter(appender);
appender.setName(subst(appenderElement.getAttribute(NAME_ATTR)));
NodeList children = appenderElement.getChildNodes();
final int length = children.getLength();
for (int loop = 0; loop < length; loop++) {
Node currentNode = children.item(loop);
/* We're only interested in Elements */
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
Element currentElement = (Element)currentNode;
// Parse appender parameters
if (currentElement.getTagName().equals(PARAM_TAG)) {
setParameter(currentElement, propSetter);
}
// Set appender layout
else if (currentElement.getTagName().equals(LAYOUT_TAG)) {
appender.setLayout(parseLayout(currentElement));
}
// Add filters
else if (currentElement.getTagName().equals(FILTER_TAG)) {
parseFilters(currentElement, appender);
}
else if (currentElement.getTagName().equals(ERROR_HANDLER_TAG)) {
parseErrorHandler(currentElement, appender);
}
else if (currentElement.getTagName().equals(APPENDER_REF_TAG)) {
String refName = subst(currentElement.getAttribute(REF_ATTR));
if(appender instanceof AppenderAttachable) {
AppenderAttachable aa = (AppenderAttachable) appender;
LogLog.debug("Attaching appender named ["+ refName+
"] to appender named ["+ appender.getName()+"].");
aa.addAppender(findAppenderByReference(currentElement));
} else {
LogLog.error("Requesting attachment of appender named ["+
refName+ "] to appender named ["+ appender.getName()+
"] which does not implement org.apache.log4j.spi.AppenderAttachable.");
}
} else {
parseUnrecognizedElement(instance, currentElement, props);
}
}
}
propSetter.activate();
return appender;
}
/* Yes, it's ugly. But all of these exceptions point to the same
problem: we can't create an Appender */
catch (Exception oops) {
LogLog.error("Could not create an Appender. Reported error follows.",
oops);
return null;
}
}