1. 程式人生 > >java實時監聽日誌寫入kafka

java實時監聽日誌寫入kafka

put article -c exti tab round 1.5 valueof max

目的

實時監聽某目錄下的日誌文件,如有新文件切換到新文件,並同步寫入kafka,同時記錄日誌文件的行位置,以應對進程異常退出,能從上次的文件位置開始讀取(考慮到效率,這裏是每100條記一次,可調整)

源碼:

[java] view plain copy
  1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileReader;
  7. import java.io.FileWriter;
  8. import java.io.IOException;
  9. import java.io.LineNumberReader;
  10. import java.io.PrintWriter;
  11. import java.io.RandomAccessFile;
  12. import java.net.NoRouteToHostException;
  13. import java.util.ArrayList;
  14. import java.util.Collection;
  15. import java.util.List;
  16. import java.util.Properties;
  17. import java.util.Random;
  18. import java.util.concurrent.Executors;
  19. import java.util.concurrent.ScheduledExecutorService;
  20. import java.util.concurrent.TimeUnit;
  21. import kafka.javaapi.producer.Producer;
  22. import kafka.producer.KeyedMessage;
  23. import kafka.producer.ProducerConfig;
  24. /*
  25. * 自己在源服務器寫生產者往kafka插入數據,註意文件"producer.properties放在linux下該jar文件同一目錄
  26. * 監聽某個目錄下的文件數據然後寫入kafka
  27. * nohup java -jar portallog_producer.jar portallog /var/apache/logs portallog.position >/home/sre/portalhandler/handler.log 2>&1 &
  28. *
  29. *
  30. */
  31. public class PortalLogTail_Line {
  32. private Producer<String,String> inner;
  33. java.util.Random ran = new Random();
  34. public PortalLogTail_Line() throws FileNotFoundException, IOException {
  35. Properties properties = new Properties();
  36. // properties.load(ClassLoader.getSystemResourceAsStream("producer.properties"));
  37. properties.load(new FileInputStream("producer.properties"));
  38. ProducerConfig config = new ProducerConfig(properties);
  39. inner = new Producer<String, String>(config);
  40. }
  41. public void send(String topicName,String message) {
  42. if(topicName == null || message == null){
  43. return;
  44. }
  45. // KeyedMessage<String, String> km = new KeyedMessage<String, String>(topicName,message);
  46. //隨機作為key,hash分散到各個分區
  47. KeyedMessage<String, String> km = new KeyedMessage<String, String>(topicName,String.valueOf(ran.nextInt(9)),message);
  48. // KeyedMessage<String, String> km = new KeyedMessage<String, String>(topicName,message,message);
  49. inner.send(km);
  50. }
  51. public void send(String topicName,Collection<String> messages) {
  52. if(topicName == null || messages == null){
  53. return;
  54. }
  55. if(messages.isEmpty()){
  56. return;
  57. }
  58. List<KeyedMessage<String, String>> kms = new ArrayList<KeyedMessage<String, String>>();
  59. for(String entry : messages){
  60. KeyedMessage<String, String> km = new KeyedMessage<String, String>(topicName,entry);
  61. kms.add(km);
  62. }
  63. inner.send(kms);
  64. }
  65. public void close(){
  66. inner.close();
  67. }
  68. public String getNewFile(File file)
  69. {
  70. File[] fs=file.listFiles();
  71. long maxtime=0;
  72. String newfilename="";
  73. for (int i=0;i<fs.length;i++)
  74. {
  75. if (fs[i].lastModified()>maxtime && fs[i].getName().contains("access"))
  76. {
  77. maxtime=fs[i].lastModified();
  78. newfilename=fs[i].getAbsolutePath();
  79. }
  80. }
  81. return newfilename;
  82. }
  83. //寫入文件名及行號
  84. public void writePosition(String path,int rn,String positionpath)
  85. {
  86. try {
  87. BufferedWriter out = new BufferedWriter(new FileWriter(positionpath));
  88. out.write(path+","+rn);
  89. out.close();
  90. } catch (IOException e) {
  91. }
  92. }
  93. LineNumberReader randomFile=null;
  94. String newfile=null;
  95. String thisfile=null;
  96. String prefile=null;
  97. int ln=0;
  98. int beginln=0;
  99. public void realtimeShowLog(final File file,final String topicname, final String positionpath) throws IOException{
  100. //啟動一個線程每1秒鐘讀取新增的日誌信息
  101. new Thread(new Runnable(){
  102. public void run() {
  103. thisfile=getNewFile(file);
  104. prefile=thisfile;
  105. //訪問position文件,如果記錄了文件路徑,及行號,則定位,否則使用最新的文件
  106. try {
  107. BufferedReader br=new BufferedReader(new FileReader(positionpath));
  108. String line=br.readLine();
  109. if (line!=null &&line.contains(","))
  110. {
  111. thisfile=line.split(",")[0];
  112. prefile=thisfile;
  113. beginln=Integer.parseInt(line.split(",")[1]);
  114. }
  115. } catch (FileNotFoundException e2) {
  116. // TODO Auto-generated catch block
  117. e2.printStackTrace();
  118. }
  119. catch (IOException e2) {
  120. // TODO Auto-generated catch block
  121. e2.printStackTrace();
  122. }
  123. //指定文件可讀可寫
  124. try {
  125. randomFile = new LineNumberReader(new FileReader(thisfile));
  126. } catch (FileNotFoundException e) {
  127. // TODO Auto-generated catch block
  128. e.printStackTrace();
  129. }
  130. while (true)
  131. {
  132. try {
  133. Thread.sleep(100);
  134. } catch (InterruptedException e1) {
  135. // TODO Auto-generated catch block
  136. e1.printStackTrace();
  137. }
  138. try {
  139. //獲得變化部分的
  140. // randomFile.seek(lastTimeFileSize);
  141. String tmp = "";
  142. while( (tmp = randomFile.readLine())!= null) {
  143. int currln=randomFile.getLineNumber();
  144. //beginln默認為0
  145. if (currln>beginln)
  146. send(topicname,new String(tmp.getBytes("utf8")));
  147. ln++;
  148. //每發生一條寫一次影響效率,連續發100次後再記錄位置
  149. if (ln>100)
  150. {
  151. writePosition(thisfile,currln,positionpath);
  152. ln=0;
  153. }
  154. }
  155. thisfile=getNewFile(file);
  156. if(!thisfile.equals(prefile))
  157. {
  158. randomFile.close();
  159. randomFile = new LineNumberReader(new FileReader(thisfile));
  160. prefile=thisfile;
  161. beginln=0;
  162. }
  163. } catch (IOException e) {
  164. throw new RuntimeException(e);
  165. }
  166. }
  167. }}).start();
  168. }
  169. /**
  170. * @param args
  171. * @throws Exception
  172. */
  173. public static void main(String[] args) throws Exception {
  174. PortalLogTail_Line producer = new PortalLogTail_Line();
  175. if (args.length!=3)
  176. {
  177. System.out.println("usage:topicname pathname positionpath");
  178. System.exit(1);
  179. }
  180. String topicname=args[0];
  181. String pathname=args[1];
  182. String positionpath=args[2];
  183. final File tmpLogFile = new File(pathname);
  184. producer.realtimeShowLog(tmpLogFile,topicname,positionpath);
  185. }
  186. }
producer.properties文件放在同級目錄下 [html] view plain copy
  1. metadata.broker.list=xxx:10909,xxx:10909
  2. # name of the partitioner class for partitioning events; default partition spreads data randomly
  3. #partitioner.class=
  4. # specifies whether the messages are sent asynchronously (async) or synchronously (sync)
  5. producer.type=sync
  6. #producer.type=async
  7. # specify the compression codec for all data generated: none , gzip, snappy.
  8. # the old config values work as well: 0, 1, 2 for none, gzip, snappy, respectivally
  9. compression.codec=none
  10. #compression.codec=gzip
  11. # message encoder
  12. serializer.class=kafka.serializer.StringEncoder


測試

最後執行: [java] view plain copy
  1. nohup java -jar portallog_producer.jar portallog /var/apache/logs portallog.position >/home/sre/portalhandler/handler.log 2>&1 &
  2. 轉:http://blog.csdn.net/u011750989/article/details/21237251

java實時監聽日誌寫入kafka