I have the following code to write a log item to a file. It creates the file correctly but there is never anything in the file (ie it is always 0 bytes in size). What am I doing wrong?
ILog log = LogManager.GetLogger("mainlog");
RollingFileAppender logAppender = new RollingFileAppender();
string filePath = ConfigurationManager.AppSettings["LoggingFilePath"];
filePath = filePath + "EventLog.csv";
logAppender.File = filePath;
logAppender.AppendToFile = true;
logAppender.RollingStyle = RollingFileAppender.RollingMode.Date;
logAppender.MaxSizeRollBackups = 60;
logAppender.StaticLogFileName = true;
log4net.Config.BasicConfigurator.Configure(logAppender);
logAppender.ActivateOptions();
StringBuilder sb = new StringBuilder();
sb.Append(DateTime.Now.ToShortDateString());
sb.Append(",");
sb.Append(DateTime.Now.ToShortTimeString());
sb.Append(",");
sb.Append(applicationID.ToString());
sb.Append(",");
sb.Append(itemName);
sb.Append(",");
sb.Append(itemException.Message);
sb.Append(",");
sb.Append(itemException.StackTrace);
sb.Append(",");
sb.Append(itemException.Source);
sb.Append(",");
sb.Append(itemException.TargetSite);
sb.Append(",");
sb.Append(itemEventType.ToString());
log.Debug(sb.ToString());
logAppender.Close();
You need to specify the layout, for example
logAppender.Layout = new log4net.Layout.PatternLayout(
"%date [%thread] %-5level %logger [%property{NDC}] - %message%newline");
Related
I need to configure a log4net Logger programmatically. Specifically, I need to add a Logger with one appender. However, when I retrieve it, I find that it doesn't have the correct level or appender, and was hoping I was missing some simple configuration ceremony:
var patternLayout = new PatternLayout { ConversionPattern = "%message%newline" };
patternLayout.ActivateOptions();
var hierarchy = (Hierarchy)LogManager.GetRepository();
var testAppender = new RollingFileAppender
{
Name = "test-appender",
AppendToFile = true,
File = "c:\\temp\\test.log",
Layout = patternLayout,
DatePattern = "yyyyMMdd-HHmm",
MaxSizeRollBackups = 50,
MaximumFileSize = "20MB",
RollingStyle = RollingFileAppender.RollingMode.Size,
StaticLogFileName = false,
Encoding = Encoding.UTF8,
PreserveLogFileNameExtension = true,
Threshold = Level.Debug
};
testAppender.ActivateOptions();
var testLogger = hierarchy.LoggerFactory.CreateLogger(hierarchy, "test");
testLogger.Hierarchy = hierarchy;
testLogger.AddAppender(testAppender);
testLogger.Repository.Configured = true;
testLogger.Level = Level.Debug;
testLogger.Additivity = false;
hierarchy.Configured = true;
var testLogger = LogManager.GetLogger("test");
The logger 'testLogger' has a null Level and no appenders. What am I missing?
Instead of calling
var testLogger = hierarchy.LoggerFactory.CreateLogger(hierarchy, "test");
I called
var testLogger = hierarchy.GetLogger("test", hierarchy.LoggerFactory);
And that worked. GetLogger will create the logger if it does not already exist.
I'm trying migrate code to version 2. But, I'm running into some issues with finding an alternative to getCurrentLoggers in log4j 2.1.1
import org.apache.logging.log4j.LogManager.getCurrentLoggers(); does not exist.
private ArrayList<LoggerName> getLoggerList() {
// Generate a list of all the loggers and levels
ArrayList<String> al = new ArrayList<String>();
HashMap<Object, Object> hm = new HashMap<Object, Object>();
ArrayList<LoggerName> list = new ArrayList<LoggerName>();
// Get RootLogger
Logger rootLogger = LogManager.getRootLogger();
String rootLoggerName = rootLogger.getName();
al.add(rootLoggerName);
hm.put(rootLoggerName, rootLogger);
// All Other Loggers ISSUE HERE
Enumeration e = LogManager.getCurrentLoggers();
while (e.hasMoreElements()) {
Logger t1Logger = (Logger) e.nextElement();
String loggerName = t1Logger.getName();
al.add(loggerName);
hm.put(loggerName, t1Logger);
}
String[] alLoggerStr = ((String[]) al.toArray(new String[0]));
Arrays.sort(alLoggerStr);
for (int i=0; i < alLoggerStr.length; i++) {
Logger logger = (Logger) hm.get(alLoggerStr[i]);
String name = logger.getName();
String level = logger.getLevel().toString();
String parent = GenFuncs.EMPTY_STRING;
if (logger.getParent() != null) {
parent = (logger.getParent().getName();
}
LoggerName logData = new LoggerNameImpl(name, parent, level);
list.add(logData);
}
return list;
}
Found answer from Stack Overflow
File configFile = new File("c:\\my_path\\log4j2.xml");
LoggerContext loggerContext = Configurator.initialize("my_config", null, configFile.toURI());
Configuration configuration = loggerContext.getConfiguration();
Collection<LoggerConfig> loggerConfigs = configuration.getLoggers().values();
I want to send DataSet data with email excel file attachment in C# but I don't want to create Excel file physically. It can be do with MemoryStream but I couldn't.
Another problem I want to set Excel file's encoding type because data may be Russian or Turkish special character.
Please help me...
Here is my sample code...
<!-- language: c# -->
var response = HttpContext.Response;
response.Clear();
response.Charset = "utf-8";
response.ContentEncoding = System.Text.Encoding.Default;
GridView excelGridView = new GridView();
excelGridView.DataSource = InfoDataSet;
excelGridView.DataBind();
excelStringWriter = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(excelStringWriter);
excelGridView.RenderControl(htw);
byte[] ExcelData = emailEncoding.GetBytes(excelStringWriter.ToString());
MemoryStream ms = new MemoryStream(ExcelData);
mailMessage.Attachments.Add(new Attachment(ms, excelFileName, "application/ms-excel"));
<!-- language: c# -->
here is another one simple and easy with excel attchment
public string SendMail(string LastId)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
SqlCommand cmd = new SqlCommand("sp_GetMailData", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#LastID", LastId);
con.Open();
string result = "0";
string temptext = "";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
//ExportToSpreadsheet(dt,"My sheet");
GridView gv = new GridView();
gv.DataSource = dt;
gv.DataBind();
AttachandSend(gv);
con.Close();
return result.ToString();
}
public void AttachandSend(GridView gv)
{
StringWriter stw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(stw);
gv.RenderControl(hw);
System.Text.Encoding Enc = System.Text.Encoding.ASCII;
byte[] mBArray = Enc.GetBytes(stw.ToString());
System.IO.MemoryStream mAtt = new System.IO.MemoryStream(mBArray, false);
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
MailAddress address = new
MailAddress("xxxxxxxxxxxxx", "Admin");
mailMessage.Attachments.Add(new Attachment(mAtt, "sales.xls"));
mailMessage.Body = "Hi PFA";
mailMessage.From = address;
mailMessage.To.Add("xxxxxxxxxxxx");
mailMessage.Subject = "xxxxxxxxxxxxxx";
mailMessage.IsBodyHtml = true;
var smtp = new SmtpClient();
smtp.Send(mailMessage);
}
Here is your solution
private static Stream DataTableToStream(DataTable table)
{
const string semiColon = ";";
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
foreach (DataColumn column in table.Columns)
{
sw.Write(column.ColumnName);
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
sw.Write(row[i].ToString().Replace(semiColon, string.Empty));
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
}
return ms;
}
private static MailMessage CreateMail(string from,
string to,
string subject,
string body,
string attname,
Stream tableStream)
{
// using System.Net.Mail
var mailMsg = new MailMessage(from, to, subject, body);
tableStream.Position = 0;
mailMsg.Attachments.Add(
new Attachment(tableStream, attname, CsvContentType));
return mailMsg;
}
private const string CsvContentType = "application/ms-excel";
private static void ExportToSpreadsheetInternal(Stream tableStream, string name)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ContentType = CsvContentType;
context.Response.AppendHeader(
"Content-Disposition"
, "attachment; filename=" + name + ".xls");
tableStream.Position = 0;
tableStream.CopyTo(context.Response.OutputStream);
context.Response.End();
}
public static void ExportToSpreadsheet(DataTable table, string name)
{
var stream = DataTableToStream(table);
var mailMsg = CreateMail("from#ddd.com",
"to#ddd.com",
"spread",
"the spread",
name,
stream);
//ExportToSpreadsheetInternal(stream, name);
// send the mailMsg with SmtpClient (config in your web.config)
var smtp = new SmtpClient();
smtp.Send(mailMsg);
}
Call this method
ExportToSpreadsheet(DataTable table, string name)
I am trying to zip a 30Mb excel file.
Wrapping th fileinputstream and fileoutputstream reduced some of the memory consumption.
Please suggest if you have a better option than this approach.
Do you think, flushing the ZipOutputStream after zos.write() inside while loop will be of any advantage?
Following is the code which i use.
public void zipBigFile()
throws IOException, ParseException {
String outFileName= "D:/Out/Big.zip";
File file = new File(outFileName);
FileOutputStream out = new FileOutputStream(file);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(out));
byte[] buffer = new byte[1024 * 8];
String inFileName = "D:/In/Big_File.xlsx";
FileInputStream fis = new FileInputStream(inFileName);
BufferedInputStream bis = new BufferedInputStream(fis);
ZipEntry zipEntry = new ZipEntry("Big_File_Zipped.xlsx");
zos.putNextEntry(zipEntry);
int length;
while ((length = bis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
fis = null;
buffer = null;
zos.flush();
zos.close();
out.close();
out = null;
zos = null;
}
Hii Guys !!!
I made an application in which i need to export data from database into .excel formate in which i have given hard coded path for generated .excel file to save at particular position on the system.Now as per my requirement I need to give download option for openwith and saveAs from the browser.
Below I am postion my code .Plz guys help me ...will be gratefull.Thanx in advance...
String datum1 = request.getParameter("fromdate");
String datum2 = request.getParameter("todate");
SimpleDateFormat sdfSource = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdfSource.parse(datum1);
Date date2 = sdfSource.parse(datum2);
SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd");
datum1 = sdfDestination.format(date);
System.out.println(datum1);
datum2 = sdfDestination.format(date2);
System.out.println(datum2);
String filename = "d:/".concat(datum1).concat(" ").concat("To").concat(" ").concat(datum2).concat(".xls");
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("CallBillingSystem");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("calldate");
rowhead.createCell((short) 1).setCellValue("src");
rowhead.createCell((short) 2).setCellValue("dst");
String strQuery = "";
ResultSet rs = null;
conexion conexiondb = new conexion();
conexiondb.Conectar();
strQuery = "SELECT * FROM cdrcost where date(calldate) between '" + datum1 + "' and '" + datum2 + "'";
// strQuery = "SELECT * FROM cdrcost where date(calldate) between '2011-09-01' and '2012-01-01'";
rs = conexiondb.Consulta(strQuery);
int i = 1;
while (rs.next()) {
HSSFRow row = sheet.createRow((short) i);
row.createCell((short) 0).setCellValue(rs.getString("calldate"));
row.createCell((short) 1).setCellValue(rs.getString("src"));
row.createCell((short) 2).setCellValue(rs.getString("dst"));
i++;
}
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated!");
} catch (Exception ex) {
System.out.println(ex);
}
}
You should use Content-Disposition in the response header
Try using this code
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=FileName.xls");
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();