log4net.ILog.Error(object, System.Exception)

Here are the examples of the csharp api log4net.ILog.Error(object, System.Exception) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

527 Examples 7

19 View Source File : Tunneler.cs
License : MIT License
Project Creator : 1upD

public override void Step(AlifeMap map)
        {
            try {
                int seed = this.X + this.Y + this.Z + (int)this.Direction + this.Height + this.Width + (int)System.DateTime.Now.Ticks;

                // Get random number
                Random random = new Random(seed);
                double sample = random.NextDouble();

                // Check turn probability. If turning, change direction 90 degrees
                if (sample < this.ProbTurn)
                {
                    sample = random.NextDouble();
                    int polarity = sample > 0.5 ? 1 : -1;
                    this.Direction = AlifeDirectionOperations.Add(this.Direction, polarity);
                }

                // Get new random seed
                sample = random.NextDouble();

                // Check reproduction probability
                if (sample < this.ProbReproduce)
                {
                    sample = random.NextDouble();
                    int polarity = sample > 0.5 ? 1 : -1;
                    AlifeDirection childDirection = AlifeDirectionOperations.Add(this.Direction, polarity);
                    int widthDecay = random.Next(this.MinWidthDecayRate, this.MaxWidthDecayRate);
                    int heightDecay = random.Next(this.MinHeightDecayRate, this.MaxHeightDecayRate);
                    Tunneler child = new Tunneler(this.Style, this.X, this.Y, this.Z, this.Width - widthDecay, this.Height - heightDecay, this.MaxLifetime - this.LifetimeDecayRate, this.MaxLifetime - this.LifetimeDecayRate, this.ProbReproduce, this.ProbTurn, this.ProbAscend, childDirection);
                    map.Agents.Add(child);
                }
                else
                {
                    sample = random.NextDouble();
                    if (sample < this.ProbSpawnRoomer)
                    {
                        Roomer child = new Roomer(x: this.X, y: this.Y, z: this.Z, style: this.Style, height: Math.Max(this.Height, 2), maxWidth: Math.Min(this.Width * 2, 3), mustDeploy: false);
                        map.Agents.Add(child);
                        }
                }

                // Get new random seed
                sample = random.NextDouble();

                // Check a s c e n d probability
                if (sample < this.ProbAscend)
                {
                    sample = random.NextDouble();
                        int verticalDistance = random.Next(1, Math.Min(this.Height, this.MaxVerticalDrop));
                    int polarity = sample > 0.5 ? verticalDistance : -verticalDistance;
                    this.Z += polarity;
                }
                else
                {
                    // Update location
                    switch (this.Direction)
                    {
                        case AlifeDirection.East:
                            this.X++;
                            break;
                        case AlifeDirection.North:
                            this.Y++;
                            break;
                        case AlifeDirection.West:
                            this.X--;
                            break;
                        case AlifeDirection.South:
                            this.Y--;
                            break;
                        case AlifeDirection.Up:
                            this.Z++;
                            break;
                        case AlifeDirection.Down:
                            this.Z--;
                            break;
                    }

                }


                // Mark location
                // Nasty nested four loop to handle the added spaces from the height and width
                bool vertical = this.Direction == AlifeDirection.North || this.Direction == AlifeDirection.South;
                for (int x = this.X; x <= (vertical ? this.X + this.Width : this.X); x++)
                {
                    for (int y = this.Y; y <= (vertical ? this.Y : this.Y + this.Width); y++)
                    {
                        for (int z = this.Z; z <= this.Z + this.Height; z++)
                        {
                            map.MarkLocation(this.Style, x, y, z);
                        }
                    }
                }

            if (this.Lifetime == 1 && this.SpawnRoomerOnDeath)
            {
                    log.Debug(string.Format("Tunneler died at {0}, {1}, {2}.", this.X, this.Y, this.Z));

                    // Add a roomer
                    Roomer child = new Roomer(x: this.X, y: this.Y, z: this.Z, style: this.Style, height: Math.Max(this.Height, 2), maxWidth: Math.Min(this.Width * 2, 3));
                    map.Agents.Add(child);
                }

            this.Lifetime--;
            }
            catch (Exception e){
                log.Error("Error in Tunneler Step function: ", e);
            }
        }

19 View Source File : VMFAdapter.cs
License : MIT License
Project Creator : 1upD

public NailsMap Import()
        {
            try {
            // Reset adapter VMF
            this._vmf = new VMF();


            NailsMap map = new NailsMap();

            List<string> lines = new List<string>();

            using (StreamReader sr = new StreamReader(new FileStream(this._filename, FileMode.OpenOrCreate)))
            {
                while (!sr.EndOfStream)
                {
                    lines.Add(sr.ReadLine());
                }
            }


            VMF input_vmf = new VMF(lines.ToArray());

            for (int blockIndex = 0; blockIndex < input_vmf.Body.Count; blockIndex++)
            {
                // Should this object be included when the VMF is output?
                bool includeThisBlock = true;
                // Get the next object from the VMF
                var obj  = input_vmf.Body[blockIndex];

                try
                {
                // Try to cast to block
                VMFParser.VBlock block = (VMFParser.VBlock)obj;
                

                // If this block is an enreplacedy
                if (block.Name == "enreplacedy")
                {
                    
                    var body = block.Body;
                    foreach (var innerObj in body) {
                        try
                        {
                            VMFParser.VProperty prop = (VMFParser.VProperty)innerObj;

                            // If this block is an instance
                            if (prop.Name == "clreplacedname" && prop.Value == "func_instance")
                            {
                                VProperty fileProperty = (VProperty)body.Where(p => p.Name == "file").ToList()[0];
                                var filePathParts = fileProperty.Value.Split('/');

                                // If this is a nails instance
                                if (filePathParts[0] == "Nails")
                                {
                                    // Get position
                                    VProperty originProperty = (VProperty)body.Where(p => p.Name == "origin").ToList()[0];
                                    var originParts = originProperty.Value.Split(' ');
                                    int x_pos = int.Parse(originParts[0]) / this._horizontal_scale;
                                    int y_pos = int.Parse(originParts[1]) / this._horizontal_scale;
                                    int z_pos = int.Parse(originParts[2]) / this._vertical_scale;
                                    string style = filePathParts[1];
                                    map.MarkLocation(style, x_pos, y_pos, z_pos);

                                        // Remove this block from the vmf
                                        includeThisBlock = false;

                                }

                                break;
                            }

                        } catch (InvalidCastException e)
                        {
                                    log.Error("Invalid cast exception. VMF Object is not a VProperty.", e);
                        }
                    }
                }
            } catch(InvalidCastException e)
                {
                        log.Error("Invalid cast exception. VMF object is not a VBlock.", e);
                }
                // If this object is not a Nails block, add it to the adapter's VMF to be output later
                if (includeThisBlock)
                {
                    this._vmf.Body.Add(obj);
                }

            }

            return map;

        } catch (Exception e)
            {
                log.Error("VMFAdapter.Import(): Caught exception: ", e);
                log.Info(string.Format("Failed to read from VMF file: {0}", this._filename));
            }

            return null;
}

19 View Source File : NailsConfig.cs
License : MIT License
Project Creator : 1upD

public static void WriteConfiguration(string filepath,  NailsConfig config)
		{
			try
			{
				log.Info(string.Format("Writing Nails configuration to file: {0}", filepath));

				XmlSerializer serializer = new XmlSerializer(typeof(NailsConfig));

				StreamWriter writer = new StreamWriter(filepath);
				serializer.Serialize(writer, config);
				writer.Close();
			}
			catch (Exception e)
			{
				log.Error(string.Format("Error writing Nails configuration to file: {0}", filepath), e);
			}
		}

19 View Source File : AlifeConfigurator.cs
License : MIT License
Project Creator : 1upD

public static List<BaseAgent> ReadConfiguration(string filepath)
        {
            List<BaseAgent> agents = null;
            try
            {
                log.Info(string.Format("Loading artificial life configuration from file: {0}", filepath));
                XmlSerializer serializer = new XmlSerializer(typeof(List<BaseAgent>));

                StreamReader reader = new StreamReader(filepath);
                agents = (List<BaseAgent>)serializer.Deserialize(reader);
                reader.Close();
            }
            catch (Exception e)
            {
                log.Error(string.Format("Error reading artificial life configuration in file: {0}", filepath), e);
            }

            return agents;
        }

19 View Source File : AlifeConfigurator.cs
License : MIT License
Project Creator : 1upD

public static void WriteConfiguration(string filepath, List<BaseAgent> agents)
        {
            try
            {
                log.Info(string.Format("Writing artificial life configuration from file: {0}", filepath));

                XmlSerializer serializer = new XmlSerializer(typeof(List<BaseAgent>));

                StreamWriter writer = new StreamWriter(filepath);
                serializer.Serialize(writer, agents);
                writer.Close();
            }
            catch (Exception e)
            {
                log.Error(string.Format("Error writing artificial life configuration to file: {0}", filepath), e);
            }
        }

19 View Source File : VMFAdapter.cs
License : MIT License
Project Creator : 1upD

private instanceData MakeInstance(string aInstanceName, string aStyleName, int aRotation, int aEntID, int aX, int aY, int aZ)
        {
            try
            {
                int seed = aEntID + aX + aY + aZ + aRotation;
                Random random = new Random(seed);

                List<string> filepaths = this.Config.GetStyle(aStyleName).GetInstancePaths(aInstanceName);

                string filepath = filepaths[random.Next(filepaths.Count)];

                instanceData instance = new instanceData { filename = "Nails/" + filepath, rotation = aRotation };
                instance.xpos = aX;
                instance.ypos = aY;
                instance.zpos = aZ;
                instance.ent_id = aEntID;
                return instance;
            } catch(Exception e)
            {
                log.Error("VMFAdapter caught exception while generating instance data: ", e);
            }
            return null;
        }

19 View Source File : VMFAdapter.cs
License : MIT License
Project Creator : 1upD

public void Export(NailsMap map)
        {
            try
            {

            log.Info(string.Format("Exporting Nails map data to VMF file: {0}", this._filename));

            // Make a deep copy of the stored VMF to add instances to
            VMF output_vmf = new VMFParser.VMF(this._vmf.ToVMFStrings());
            int i = 0;

            foreach(NailsCube cube in map.NailsCubes)
            {
                int x_pos = cube.X * this._horizontal_scale;
                int y_pos = cube.Y * this._horizontal_scale;
                int z_pos = cube.Z * this._vertical_scale;

                var faces = cube.GetFaces();

                if (faces.Contains(NailsCubeFace.Floor))
                {
                    instanceData instance = this.MakeInstance("floor", cube.StyleName, 0, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Front))
                {
                    instanceData instance = this.MakeInstance("wall", cube.StyleName, 0, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Left))
                {
                    instanceData instance = this.MakeInstance("wall", cube.StyleName, 90, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Back))
                {
                    instanceData instance = this.MakeInstance("wall", cube.StyleName, 180, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Right))
                {
                    instanceData instance = this.MakeInstance("wall", cube.StyleName, 270, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Ceiling))
                {
                    instanceData instance = this.MakeInstance("ceiling", cube.StyleName, 0, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }
            }


            using (StreamWriter sw = new StreamWriter(new FileStream(this._filename, FileMode.Create)))
            {
                var vmfStrings = output_vmf.ToVMFStrings();
                foreach (string line in vmfStrings)
                {
                    sw.WriteLine(line);
                }
            }

            log.Info(string.Format("Wrote to VMF file: {0}", this._filename));

            } catch (Exception e)
            {
                log.Error("VMFAdapter.Export(): Caught exception: ", e);
                log.Info(string.Format("Failed to write to VMF file: {0}", this._filename));
            }


        }

19 View Source File : VMFAdapter.cs
License : MIT License
Project Creator : 1upD

private static void insertInstanceIntoVMF(instanceData instance, VMF output_vmf)
        {
            try
            {
                IList<int> list = null;

                VBlock instance_block = new VBlock("enreplacedy");
                instance_block.Body.Add(new VProperty("id", instance.ent_id.ToString()));
                instance_block.Body.Add(new VProperty("clreplacedname", "func_instance"));
                instance_block.Body.Add(new VProperty("angles", "0 " + instance.rotation + " 0"));
                instance_block.Body.Add(new VProperty("origin", instance.xpos + " " + instance.ypos + " " + instance.zpos));
                instance_block.Body.Add(new VProperty("file", instance.filename));
                output_vmf.Body.Add(instance_block);
            }
            catch (Exception e)
            {
                log.Error("VMFAdapter.insertInstanceIntoVMF(): Caught exception: ", e);
                log.Info(string.Format("Failed to insert instance: {0}", instance.filename));
            }
        }

19 View Source File : Roomer.cs
License : MIT License
Project Creator : 1upD

public override void Step(AlifeMap map)
        {
            try
            {
                // Mark to discard
                this._completed = true;

                // Local variables
                int spacesOccupied = 0;
                int total = 0;
                List<Tuple<int, int, int>> locationsToMark = new List<Tuple<int, int, int>>();

                for (int z = this.Z; z < this.Z + this.Height; z++)
                {
                    for (int x = this.X + this._x2; x < this.X + this._x1; x++)
                    {
                        for (int y = this.Y + this._y2; y < this.Y + this._y1; y++)
                        {
                            locationsToMark.Add(new Tuple<int, int, int>(x, y, z));
                            bool isSpaceOccupied = map.GetLocation(x, y, z) != null && map.GetLocation(x, y, z) != "";
                            spacesOccupied += isSpaceOccupied ? 1 : 0;
                            total++;
                        }
                    }
                }

                if (spacesOccupied < total / 2 && MustDeploy)
                {
                    log.Debug(string.Format("Roomer deployed: {0} spaces occupied, {1} total.", spacesOccupied, total));
                    log.Debug(string.Format("Roomer deployed at x: {0} y: {1} z: {2}", this.X, this.Y, this.Z));
                    foreach (var tuple in locationsToMark)
                    {
                        map.MarkLocation(this.Style, tuple.Item1, tuple.Item2, tuple.Item3);
                    }
                } else
                {
                    log.Debug(string.Format("Roomer did not deploy. {0} spaces occupied, {1} total.", spacesOccupied, total));
                }

            }
            catch (Exception e)
            {
                log.Error("Error in Roomer Step function: ", e);
            }

        }

19 View Source File : NailsConfig.cs
License : MIT License
Project Creator : 1upD

public static NailsConfig ReadConfiguration(string filepath)
		{
			NailsConfig config = null;
			try
			{
				log.Info(string.Format("Loading Nails configuration from file: {0}", filepath));
				XmlSerializer serializer = new XmlSerializer(typeof(NailsConfig));

				StreamReader reader = new StreamReader(filepath);
				config = (NailsConfig)serializer.Deserialize(reader);
				reader.Close();
			}
			catch (Exception e)
			{
				log.Error(string.Format("Error reading Nails configuration in file: {0}", filepath), e);
			}

			return config;
		}

19 View Source File : MonitorItemForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void stb_home_url_Enter(object sender, EventArgs e)
        {
            string sdir = stb_project_source_dir.Text;
            string appname = stb_app_name.Text;
            string url = stb_home_url.Text;
            if(!string.IsNullOrWhiteSpace(sdir) && !string.IsNullOrWhiteSpace(appname) && url.EndsWith("[port]")){
                try
                {
                    if (get_spboot_port_run)
                    {
                        return;
                    }
                    get_spboot_port_run = true;
                    if (!sdir.EndsWith("/"))
                    {
                        sdir += "/";
                    }
                    string serverxml = string.Format("{0}{1}/src/main/resources/config/application-dev.yml", sdir, appname);
                    string targetxml = MainForm.TEMP_DIR + string.Format("application-dev-{0}.yml", DateTime.Now.ToString("MMddHHmmss"));
                    targetxml = targetxml.Replace("\\", "/");
                    parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        string port = "", ctx = "";
                        string yml = YSTools.YSFile.readFileToString(targetxml);
                        if(!string.IsNullOrWhiteSpace(yml)){
                            string[] lines = yml.Split('\n');
                            bool find = false;                            
                            int index = 0, start = 0;
                            foreach(string line in lines){
                                if (line.Trim().StartsWith("server:"))
                                {
                                    find = true;
                                    start = index;
                                }
                                else if(find && line.Trim().StartsWith("port:")){
                                    port = line.Substring(line.IndexOf(":") + 1).Trim();
                                }
                                else if (find && line.Trim().StartsWith("context-path:"))
                                {
                                    ctx = line.Substring(line.IndexOf(":") + 1).Trim();
                                }
                                if (index - start > 4 && start > 0)
                                {
                                    break;
                                }
                                index++;
                            }
                        }

                        if (port != "")
                        {
                            stb_home_url.BeginInvoke((MethodInvoker)delegate()
                            {
                                stb_home_url.Text = string.Format("http://{0}:{1}{2}", config.Host, port, ctx);
                            });
                        }
                        
                        get_spboot_port_run = false;

                        File.Delete(targetxml);
                    });
                }
                catch(Exception ex) {
                    logger.Error("Error", ex);
                }

            }
        }

19 View Source File : IceMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void CheckItem(string uri, ListViewItem item)
        {
            try
            {
                RequestHttpWebRequest req = new RequestHttpWebRequest();
                req.GetResponseAsync(new RequestInfo(uri), x =>
                {
                    try
                    {
                        if (x.StatusCode == HttpStatusCode.OK || x.StatusCode == HttpStatusCode.Found)
                        {
                            // 正常
                            SetLisreplacedemStatus(item, 1);
                        }
                        else
                        {
                            // 异常
                            SetLisreplacedemStatus(item, 2);
                        }
                    }
                    catch (Exception ex)
                    {
                        // 异常
                        SetLisreplacedemStatus(item, 2);
                        logger.Error("http请求异常:" + ex.Message, ex);
                    }
                });
            }
            catch (Exception e)
            {
                if (e.Message.IndexOf("未能为 SSL/TLS 安全通道建立信任关系") != -1)
                {
                    ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                    CheckItem(uri, item);
                }
                logger.Error("http请求异常:" + e.Message, e);
            }
        }

19 View Source File : SpringBootMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void CheckItem()
        {
            try
            {
                button5.Enabled = false;
                button5.Text = "检测中..";

                timer = resetTimer;
                progressBar1.Value = timer;

                string uri = l_pro_visit_url.Text;
                //HttpUtil.get(uri, new DownloadStringCompletedEventHandler(AsyncDownloadCompleted));

                RequestHttpWebRequest req = new RequestHttpWebRequest();
                req.GetResponseAsync(new RequestInfo(uri), x =>
                {
                    try
                    {
                        if (x.StatusCode == HttpStatusCode.OK || x.StatusCode == HttpStatusCode.Found)
                        {
                            // 正常
                            SetStatus(1);
                        }
                        else
                        {
                            // 异常
                            SetStatus(0);
                        }
                    }
                    catch (Exception ex)
                    {
                        SetStatus(0);
                        logger.Error("http请求异常:" + ex.Message, ex);
                    }                    
                });
            }
            catch (Exception e)
            {
                if (e.Message.IndexOf("未能为 SSL/TLS 安全通道建立信任关系") != -1)
                {
                    ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                    CheckItem();
                }
                logger.Error("http请求异常:" + e.Message, e);
            }

            button5.Enabled = true;
            button5.Text = "立即检测";
        }

19 View Source File : SpringBootMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void AsyncDownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                // 返回结果在 e.Result 里
                string html = e.Result;
                if (e.Error == null || string.IsNullOrWhiteSpace(html))
                {
                    // 正常
                    SetStatus(1);
                    return;
                }
                else if (e.Error != null)
                {
                    string error = e.Error.Message;
                    logger.Error("异步Http请求异常:" + error, e.Error);
                }
                // 异常
                SetStatus(0);
            }
            catch (Exception ex)
            {
                if (ex.InnerException.Message.IndexOf("未能为 SSL/TLS 安全通道建立信任关系") != -1)
                {
                    ServicePointManager.ServerCertificateValidationCallback = (ser, certificate, chain, sslPolicyErrors) => true;
                    CheckItem();
                }
            }
        }

19 View Source File : NailsAlifeMap.cs
License : MIT License
Project Creator : 1upD

public string GetLocation(int x, int y, int z)
        {
            NailsCube cube = null;
            try
            {
                cube = this.map.GetCube(x, y, z);
            } catch(Exception e)
            {
                log.Error("NailsAlifeMap.GetLocation(): Caught exception: ", e);
            }

            if(cube == null)
            {
                return null;
            }

            return cube.StyleName;

        }

19 View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void TransfersFileProgress(string id, long precent, long c, long max, int elapsed)
        {
            try
            {
                int start = 0, end = Convert.ToInt32(DateTime.Now.ToString("ffff"));
                if(TIMEDIC.ContainsKey(id)){
                    start = TIMEDIC[id];
                    TIMEDIC[id] = end;
                } else {
                    TIMEDIC.Add(id, end);
                }
                long startByte = 0, endByte = c;
                if (BYTEDIC.ContainsKey(id))
                {
                    startByte = BYTEDIC[id];
                    BYTEDIC[id] = endByte;
                } else {
                    BYTEDIC.Add(id, endByte);
                }
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    TransferItem obj = null;
                    foreach (ListViewItem item in listView3.Items)
                    {
                        if (item.Name == id)
                        {
                            obj = (TransferItem)item.Tag;
                        
                            obj.Progress = precent;
                            item.SubItems[1].Text = TransferStatus.Transfers.ToString();
                            item.SubItems[2].Text = precent + "%";
                            item.SubItems[6].Text = Utils.CalculaSpeed(startByte, endByte, max, start, end);
                            item.SubItems[7].Text = Utils.CalculaTimeLeft(startByte, endByte, max, start, end);
                            break;
                        }
                    }
                });
            }
            catch(Exception ex) {
                logger.Error("传输文件的到服务器时异常:" + ex.Message, ex);
                ChangeTransferItemStatus("R2L", id, TransferStatus.Failed);
            }
            
        }

19 View Source File : SftpLinuxForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void ChangeListView(string tag)
        {
            try
            {
                largeIconTool.Checked = tag == "Large";
                largeIconTool2.Checked = tag == "Large";
                smallIconTool.Checked = tag == "Small";
                smallIconTool2.Checked = tag == "Small";
                listTool.Checked = tag == "List";
                listTool2.Checked = tag == "List";
                detailTool.Checked = tag == "Detail";
                detailTool2.Checked = tag == "Detail";

                if (tag == "Large")
                {
                    listView2.View = View.LargeIcon;
                }
                else if (tag == "Small")
                {
                    listView2.View = View.SmallIcon;
                }
                else if (tag == "List")
                {
                    listView2.View = View.List;
                }
                else if (tag == "Detail")
                {
                    listView2.View = View.Details;
                }
                listViewTag = tag;
            }
            catch (Exception e)
            {
                logger.Error("更改列表显示方式异常:" + e.Message, e);
            }            
        }

19 View Source File : SftpLinuxForm.cs
License : Apache License 2.0
Project Creator : 214175590

public SftpProgressMonitor TransfersToRemote(string id, string localPath, string remotePath, int mode, ProgressDelegate progress, TransfersEndDelegate end)
        {
            SftpProgressMonitor monitor = new MyProgressMonitor(id, progress, end);
            try
            {
                sftpChannel.put(localPath, remotePath, monitor, mode);
            }
            catch(Exception e) {
                Console.WriteLine(localPath + "================>" + remotePath);
                logger.Error("put文件到服务器异常:" + e.Message, e);
            }            
            return monitor;
        }

19 View Source File : TomcatMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void CheckItem()
        {
            button5.Enabled = false;
            button5.Text = "检测中..";
            try
            {
                timer = resetTimer;
                progressBar1.Value = timer;

                string uri = l_visit_url.Text;

                RequestHttpWebRequest req = new RequestHttpWebRequest();
                req.GetResponseAsync(new RequestInfo(uri), x =>
                {
                    try
                    {
                        if (x.StatusCode == HttpStatusCode.OK || x.StatusCode == HttpStatusCode.Found)
                        {
                            // 正常
                            SetStatus(1);
                        }
                        else
                        {
                            // 异常
                            SetStatus(0);
                        }
                    }
                    catch (Exception ex)
                    {
                        SetStatus(0);
                        logger.Error("http请求异常:" + ex.Message, ex);
                    }
                });
            }
            catch (Exception e)
            {
                if (e.Message.IndexOf("未能为 SSL/TLS 安全通道建立信任关系") != -1)
                {
                    ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                    CheckItem();
                }
                logger.Error("http请求异常:" + e.Message, e);
            }
            button5.Enabled = true;
            button5.Text = "立即检测";
        }

19 View Source File : TomcatMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "修改")
            {
                tb_port.BorderStyle = BorderStyle.FixedSingle;
                tb_port.ReadOnly = false;
                tb_port.Location = new Point(tb_port.Location.X, tb_port.Location.Y - 2);
                button1.Text = "保存";
            }
            else if (button1.Text == "保存")
            {
                string port = tb_port.Text;
                if (port == itemConfig.tomcat.TomcatPort)
                {
                    label_msg.Text = "端口无变化";
                }
                else
                {
                    DialogResult dr = MessageBox.Show("修改端口后需要重启Tomcat才能生效,您确定要修改吗?", "操作提醒", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                    if (dr == System.Windows.Forms.DialogResult.OK)
                    {
                        button1.Enabled = false;
                        label_msg.Text = "修改中...";
                        try
                        {
                            string targetxml = MainForm.TEMP_DIR + string.Format("server-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
                            targetxml = targetxml.Replace("\\", "/");
                            string serverxml = l_xml_path.Text;
                            monitorForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                            string content = YSFile.readFileToString(targetxml);
                            if (null != content)
                            {
                                content = content.Replace(itemConfig.tomcat.TomcatPort, port);

                                YSFile.writeFileByString(targetxml, content);

                                monitorForm.RunSftpShell(string.Format("put {0} {1}", targetxml, serverxml), false, false);

                                itemConfig.tomcat.TomcatPort = port;

                                AppConfig.Instance.SaveConfig(2);

                                label_msg.Text = "修改成功";
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.Error("修改Tomcat端口异常:" + ex.Message, ex);
                            label_msg.Text = "修改失败";
                        }

                    }
                    else
                    {
                        tb_port.Text = itemConfig.tomcat.TomcatPort;
                    }                 
                }

                button1.Enabled = true;
                button1.Text = "修改";
                tb_port.BorderStyle = BorderStyle.None;
                tb_port.ReadOnly = true;
                tb_port.Location = new Point(tb_port.Location.X, tb_port.Location.Y + 2);

                ControlUtil.delayClearText(new DelayDelegate(labelMsg), 2000);
            }
        }

19 View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void RunRemoteToLocal()
        {
            getTransferItem("R2L", (item) =>
            {
                if (item != null)
                {
                    transfering = true;
                    try
                    {
                        if (File.Exists(item.LocalPath))
                        {
                            this.BeginInvoke((MethodInvoker)delegate()
                            {
                                DialogResult dr = MessageBox.Show(this, item.LocalPath + "已存在,是否覆盖?", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                                if (dr == System.Windows.Forms.DialogResult.Yes)
                                {
                                    WriteLog("R2L", item.Id, item.LocalPath, item.RemotePath);
                                    SftpProgressMonitor monitor = rightForm.TransfersToLocal(item.Id, item.LocalPath, item.RemotePath, ChannelSftp.OVERWRITE, new ProgressDelegate(TransfersFileProgress), new TransfersEndDelegate(TransfersFileEnd));
                                }
                                else
                                {
                                    ChangeTransferItemStatus("R2L", item.Id, TransferStatus.Cancel);
                                }
                            });
                        }
                        else
                        {
                            FileInfo file = new FileInfo(item.LocalPath);
                            if (!file.Directory.Exists)
                            {
                                Utils.createParentDir(file.Directory);
                            }
                            WriteLog("R2L", item.Id, item.LocalPath, item.RemotePath);
                            SftpProgressMonitor monitor = rightForm.TransfersToLocal(item.Id, item.LocalPath, item.RemotePath, ChannelSftp.OVERWRITE, new ProgressDelegate(TransfersFileProgress), new TransfersEndDelegate(TransfersFileEnd));
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error("传输文件的到服务器时异常:" + ex.Message, ex);
                        ChangeTransferItemStatus("R2L", item.Id, TransferStatus.Failed);
                    }
                }
                else
                {
                    remoteToLocalRun = false;
                }
            });
        }

19 View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void WriteLog(string flag, string id, string local, string remote)
        {
            try
            {
                string log = "";
                if (flag == "L2R")
                {
                    log = string.Format("【{0}】 - [{1}] Transfers File To {2},{3} -> {4}   ", user.Host, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "Remote", local, remote);
                }
                else
                {
                    log = string.Format("[{0} {1}] Transfers File To {2},{3} -> {4}   ", user.Host, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "Local", remote, local);
                }
                WriteLog2(log);
            }
            catch(Exception e) {
                logger.Error("格式化日志报错", e);
            }
        }

19 View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void WriteLog2(string msg)
        {
            try
            {
                this.BeginInvoke((MethodInvoker)delegate() {
                    logtext.AppendText(msg);

                    logtext.Focus();
                    logtext.SelectionStart = logtext.TextLength + 1000;
                    logtext.ScrollToCaret();
                });                
            }
            catch (Exception e)
            {
                logger.Error("显示日志报错:" + e.Message, e);
            }
        }

19 View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string text = logtext.SelectedText;
                if (text != "")
                {
                    Clipboard.SetText(text);
                }
            }
            catch (Exception ex)
            {
                logger.Error("复制时异常:" + ex.Message, ex);
            }
        }

19 View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void clearToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                logtext.Clear();
            }
            catch (Exception ex)
            {
                logger.Error("清除所有日志时异常:" + ex.Message, ex);
            }
        }

19 View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                logtext.SelectAll();
            }
            catch (Exception ex)
            {
                logger.Error("选择全部时异常:" + ex.Message, ex);
            }
        }

19 View Source File : SftpLinuxForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void Disconnection()
        {
            try
            {
                RUN_CUT = false;
                exit();

                if (null != shell)
                {
                    shell.Close();
                }
                if (null != m_Channel)
                {
                    m_Channel.disconnect();
                }
                if (null != sftpChannel)
                {
                    sftpChannel.disconnect();
                }
                logger.Debug("断开Ssh...OK");
            }
            catch (Exception ex)
            {
                logger.Error("断开链接异常:" + ex.Message, ex);
            }
        }

19 View Source File : SftpLinuxForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void LoadDirFilesToListView(string path, LoadFilesResult result = null)
        {
            this.BeginInvoke((MethodInvoker)delegate()
            {
                try
                {
                    if (null == sftpChannel)
                    {
                        return;
                    }
                    ArrayList files = sftpChannel.ls(path);
                    if (files != null)
                    {
                        ChannelSftp.LsEntry file = null;
                        listView2.Items.Clear();
                        LargeImages.Images.Clear();
                        SmallImages.Images.Clear();

                        LargeImages.Images.Add(Properties.Resources.filen_64px);
                        LargeImages.Images.Add(Properties.Resources.folder_64px);
                        SmallImages.Images.Add(Properties.Resources.filen_16px);
                        SmallImages.Images.Add(Properties.Resources.folder_16px);

                        ListViewItem item = null;
                        ListViewItem.ListViewSubItem subItem = null;
                        List<ListViewItem> itemList = new List<ListViewItem>();
                        for (int i = 0; i < files.Count; i++)
                        {
                            object obj = files[i];
                            if (obj is ChannelSftp.LsEntry)
                            {
                                file = (ChannelSftp.LsEntry)obj;
                                if (file.getFilename() == ".")
                                {
                                    continue;
                                }

                                item = new ListViewItem();
                                item.Text = file.getFilename();
                                item.Tag = file;

                                if (file.getFilename() != "..")
                                {
                                    subItem = new ListViewItem.ListViewSubItem();
                                    subItem.Text = Utils.getFileSize(file.getAttrs().getSize());
                                    item.SubItems.Add(subItem);

                                    subItem = new ListViewItem.ListViewSubItem();
                                    subItem.Text = file.getAttrs().isDir() ? "文件夹" : file.getAttrs().isLink() ? "快捷方式" : getFileExt(file.getFilename());
                                    item.SubItems.Add(subItem);

                                    subItem = new ListViewItem.ListViewSubItem();
                                    subItem.Text = file.getAttrs().getMtimeString();
                                    item.SubItems.Add(subItem);

                                    subItem = new ListViewItem.ListViewSubItem();
                                    subItem.Text = file.getAttrs().getPermissionsString();
                                    item.SubItems.Add(subItem);

                                    subItem = new ListViewItem.ListViewSubItem();
                                    subItem.Text = getFileOwner(file.getLongname());
                                    item.SubItems.Add(subItem);

                                    item.ImageIndex = file.getAttrs().isDir() ? 1 : 0;
                                    if(file.getAttrs().isDir()){
                                        listView2.Items.Add(item);
                                    }
                                    else
                                    {
                                        itemList.Add(item);
                                    }
                                }
                                else
                                {
                                    subItem = new ListViewItem.ListViewSubItem();
                                    subItem.Text = "";
                                    item.SubItems.Add(subItem);
                                    subItem = new ListViewItem.ListViewSubItem();
                                    subItem.Text = "";
                                    item.SubItems.Add(subItem);
                                    subItem = new ListViewItem.ListViewSubItem();
                                    subItem.Text = "";
                                    item.SubItems.Add(subItem);
                                    subItem = new ListViewItem.ListViewSubItem();
                                    subItem.Text = "";
                                    item.SubItems.Add(subItem);
                                    subItem = new ListViewItem.ListViewSubItem();
                                    subItem.Text = "";
                                    item.SubItems.Add(subItem);
                                    item.ImageIndex = 1;
                                    listView2.Items.Add(item);
                                }
                            }
                        }
                        foreach (ListViewItem item2 in itemList)
                        {
                            listView2.Items.Add(item2);
                        }
                        if (null != result)
                        {
                            result();
                        }
                    }
                    else
                    {
                        MessageBox.Show(this, "目录不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch(Exception e) {
                    logger.Error("加载数据失败:" + e.Message, e);
                    if(!success){
                        sftpForm.CloseTab(this);
                    }                    
                }                
            });
        }

19 View Source File : SftpWinForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void LoadDirFilesToListView(string path, LoadFilesResult result = null)
        {
            this.BeginInvoke((MethodInvoker)delegate()
            {
                try
                {
                    DirectoryInfo dire = new DirectoryInfo(path);
                    if(dire.Exists){
                        listView1.Items.Clear();
                        LargeImages.Images.Clear();
                        SmallImages.Images.Clear();
                
                        FileInfo[] files = dire.GetFiles();
                        DirectoryInfo[] dires = dire.GetDirectories();
                        Icon icon = null;
                        ListViewItem item = null;
                        ListViewItem.ListViewSubItem subItem = null;
                        LargeImages.Images.Add(Properties.Resources.filen_64px);
                        LargeImages.Images.Add(Properties.Resources.folder_64px);
                        SmallImages.Images.Add(Properties.Resources.filen_16px);
                        SmallImages.Images.Add(Properties.Resources.folder_16px);
                        int index = 2;

                        item = new ListViewItem();
                        item.Text = "..";

                        subItem = new ListViewItem.ListViewSubItem();
                        subItem.Text = "";
                        item.SubItems.Add(subItem);

                        subItem = new ListViewItem.ListViewSubItem();
                        subItem.Text = "文件夹";
                        item.SubItems.Add(subItem);

                        subItem = new ListViewItem.ListViewSubItem();
                        subItem.Text = "";
                        item.SubItems.Add(subItem);

                        item.ImageIndex = 1;
                        listView1.Items.Add(item);

                        foreach (DirectoryInfo file in dires)
                        {
                            item = new ListViewItem();
                            item.Text = file.Name;
                            item.Tag = file;

                            subItem = new ListViewItem.ListViewSubItem();
                            subItem.Text = "";
                            item.SubItems.Add(subItem);

                            subItem = new ListViewItem.ListViewSubItem();
                            subItem.Text = "文件夹";
                            item.SubItems.Add(subItem);

                            subItem = new ListViewItem.ListViewSubItem();
                            subItem.Text = file.LastWriteTime.ToString("yyyy-MM-dd, HH:mm:ss");
                            item.SubItems.Add(subItem);
                            item.ImageIndex = 1;
                            listView1.Items.Add(item);
                            //Console.WriteLine(file.Name + " - " + file.ToString());
                        }
                        foreach(FileInfo file in files){
                            if(file.Extension == ".lnk"){
                                continue;
                            }

                            icon = Icon.ExtractreplacedociatedIcon(file.FullName);
                            LargeImages.Images.Add(icon.ToBitmap());
                            SmallImages.Images.Add(icon.ToBitmap());
                            item = new ListViewItem();
                            item.Text = file.Name;
                            item.Tag = file;

                            subItem = new ListViewItem.ListViewSubItem();
                            subItem.Text = Utils.getFileSize(file.Length);
                            item.SubItems.Add(subItem);

                            subItem = new ListViewItem.ListViewSubItem();
                            subItem.Text = file.Extension;
                            item.SubItems.Add(subItem);

                            subItem = new ListViewItem.ListViewSubItem();
                            subItem.Text = file.LastWriteTime.ToString("yyyy-MM-dd, HH:mm:ss");
                            item.SubItems.Add(subItem);
                            item.ImageIndex = index++;
                            listView1.Items.Add(item);
                            //Console.WriteLine(file.Name + " - " + file.ToString());
                        }
                        if (null != result)
                        {
                            result();
                        }
                    }
                    else
                    {
                        MessageBox.Show(this, "目录不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception e)
                {
                    logger.Error("加载数据失败:" + e.Message, e);
                }
            });
        }

19 View Source File : SftpWinForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void ChangeListView(string tag)
        {
            try
            {
                largeIconTool.Checked = tag == "Large";
                largeIconTool2.Checked = tag == "Large";
                smallIconTool.Checked = tag == "Small";
                smallIconTool2.Checked = tag == "Small";
                listTool.Checked = tag == "List";
                listTool2.Checked = tag == "List";
                detailTool.Checked = tag == "Detail";
                detailTool2.Checked = tag == "Detail";

                if (tag == "Large")
                {
                    listView1.View = View.LargeIcon;
                }
                else if (tag == "Small")
                {
                    listView1.View = View.SmallIcon;
                }
                else if (tag == "List")
                {
                    listView1.View = View.List;
                }
                else if (tag == "Detail")
                {
                    listView1.View = View.Details;
                }
                listViewTag = tag;
            }
            catch (Exception e)
            {
                logger.Error("更改列表显示方式异常:" + e.Message, e);
            }
        }

19 View Source File : Log4NetAdapter.cs
License : MIT License
Project Creator : afaniuolo

public void Log(LogEntry entry)
		{
			//Here invoke m_Adaptee
			if (entry.Severity == LoggingEventType.Debug)
				m_Adaptee.Debug(entry.Message, entry.Exception);
			else if (entry.Severity == LoggingEventType.Information)
				m_Adaptee.Info(entry.Message, entry.Exception);
			else if (entry.Severity == LoggingEventType.Warning)
				m_Adaptee.Warn(entry.Message, entry.Exception);
			else if (entry.Severity == LoggingEventType.Error)
				m_Adaptee.Error(entry.Message, entry.Exception);
			else
				m_Adaptee.Fatal(entry.Message, entry.Exception);
		}

19 View Source File : Controller.cs
License : MIT License
Project Creator : AlturosDestinations

private void RegisterWebApi(int port)
        {
            var url = $"http://*:{port}";
            var fullUrl = url.Replace("*", "localhost");

            Log.Info($"{nameof(RegisterWebApi)} - Swagger: {fullUrl}/swagger/");

            try
            {
                this._webApp = WebApp.Start(url, (app) =>
                {
                    //Use JSON friendly default settings
                    var defaultSettings = new JsonSerializerSettings
                    {
                        Formatting = Formatting.Indented,
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        Converters = new List<JsonConverter> { new StringEnumConverter { NamingStrategy = new CamelCaseNamingStrategy() }, }
                    };
                    JsonConvert.DefaultSettings = () => { return defaultSettings; };

                    var config = new HttpConfiguration();
                    config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(this._container);

                    //Specify JSON as the default media type
                    config.Formatters.Clear();
                    config.Formatters.Add(new JsonMediaTypeFormatter());
                    config.Formatters.JsonFormatter.SerializerSettings = defaultSettings;

                    //Route all requests to the RootController by default
                    config.Routes.MapHttpRoute("api", "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });
                    config.MapHttpAttributeRoutes();

                    //Tell swagger to generate doreplacedentation based on the XML doc file output from msbuild
                    config.EnableSwagger(c =>
                    {
                        c.SingleApiVersion("1.0", SystemName);
                    }).EnableSwaggerUi();

                    app.UseWebApi(config);
                });
            }
            catch (Exception exception)
            {
                Log.Error($"{nameof(RegisterWebApi)} - run first AllowWebserver.cmd", exception);
            }
        }

19 View Source File : LoggingExample.cs
License : Apache License 2.0
Project Creator : apache

public static void Main(string[] args)
		{
			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [ConsoleApp] Start");

			// Log a debug message. Test if debug is enabled before
			// attempting to log the message. This is not required but
			// can make running without logging faster.
			if (log.IsDebugEnabled) log.Debug("This is a debug message");

			try
			{
				Bar();
			}
			catch(Exception ex)
			{
				// Log an error with an exception
				log.Error("Exception thrown from method Bar", ex);
			}

			log.Error("Hey this is an error!");

			// Push a message on to the Nested Diagnostic Context stack
			using(log4net.NDC.Push("NDC_Message"))
			{
				log.Warn("This should have an NDC message");

				// Set a Mapped Diagnostic Context value  
				log4net.MDC.Set("auth", "auth-none");
				log.Warn("This should have an MDC message for the key 'auth'");

			} // The NDC message is popped off the stack at the end of the using {} block

			log.Warn("See the NDC has been popped of! The MDC 'auth' key is still with us.");

			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [ConsoleApp] End");

			Console.Write("Press Enter to exit...");
			Console.ReadLine();
		}

19 View Source File : LoggingExample.cs
License : Apache License 2.0
Project Creator : apache

public static void Main(string[] args)
		{
			log4net.ThreadContext.Properties["session"] = 21;

			// Hookup the FireEventAppender event
			if (FireEventAppender.Instance != null)
			{
				FireEventAppender.Instance.MessageLoggedEvent += new MessageLoggedEventHandler(FireEventAppender_MessageLoggedEventHandler);
			}

			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [ConsoleApp] Start");

			// Log a debug message. Test if debug is enabled before
			// attempting to log the message. This is not required but
			// can make running without logging faster.
			if (log.IsDebugEnabled) log.Debug("This is a debug message");

			// Log a custom object as the log message
			log.Warn(new MsgObj(42, "So long and thanks for all the fish"));

			try
			{
				Bar();
			}
			catch(Exception ex)
			{
				// Log an error with an exception
				log.Error("Exception thrown from method Bar", ex);
			}

			log.Error("Hey this is an error!");

			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [ConsoleApp] End");

			Console.Write("Press Enter to exit...");
			Console.ReadLine();
		}

19 View Source File : RemotingClient.cs
License : Apache License 2.0
Project Creator : apache

static void Main(string[] args)
		{
			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [RemotingClient] Start");

			log.Fatal("First Fatal message");

			for(int i=0; i<8; i++)
			{
				log.Debug("Hello");
			}

			// Log a message with an exception and nested exception
			log.Error("An exception has occured", new Exception("Some exception", new Exception("Some nested exception")));

			for(int i=0; i<8; i++)
			{
				log.Debug("There");
			}

			// Stress test can be called here
			//StessTest();

			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [RemotingClient] End");
		}

19 View Source File : LoggingExample.cs
License : Apache License 2.0
Project Creator : apache

public static void LogEvents()
		{
			// Log a debug message. Test if debug is enabled before
			// attempting to log the message. This is not required but
			// can make running without logging faster.
			if (log.IsDebugEnabled) log.Debug("This is a debug message");

			try
			{
				Bar();
			}
			catch(Exception ex)
			{
				// Log an error with an exception
				log.Error("Exception thrown from method Bar", ex);
			}

			log.Error("Hey this is an error!");

			// Push a message on to the Nested Diagnostic Context stack
			using(log4net.NDC.Push("NDC_Message"))
			{
				log.Warn("This should have an NDC message");

				// Set a Mapped Diagnostic Context value  
				log4net.MDC.Set("auth", "auth-none");
				log.Warn("This should have an MDC message for the key 'auth'");

			} // The NDC message is popped off the stack at the end of the using {} block

			log.Warn("See the NDC has been popped of! The MDC 'auth' key is still with us.");
		}

19 View Source File : StringFormatTest.cs
License : Apache License 2.0
Project Creator : apache

[Test]
		public void TestLogFormatApi_Error()
		{
			StringAppender stringAppender = new StringAppender();
			stringAppender.Layout = new PatternLayout("%level:%message");

			ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
			BasicConfigurator.Configure(rep, stringAppender);

			ILog log1 = LogManager.GetLogger(rep.Name, "TestLogFormatApi_Error");

			// ***
			log1.Error("TestMessage");
			replacedert.AreEqual("ERROR:TestMessage", stringAppender.GetString(), "Test simple ERROR event 1");
			stringAppender.Reset();

			// ***
			log1.Error("TestMessage", null);
			replacedert.AreEqual("ERROR:TestMessage", stringAppender.GetString(), "Test simple ERROR event 2");
			stringAppender.Reset();

			// ***
			log1.Error("TestMessage", new Exception("Exception message"));
			replacedert.AreEqual("ERROR:TestMessageSystem.Exception: Exception message" + Environment.NewLine, stringAppender.GetString(), "Test simple ERROR event 3");
			stringAppender.Reset();

			// ***
			log1.ErrorFormat("a{0}", "1");
			replacedert.AreEqual("ERROR:a1", stringAppender.GetString(), "Test formatted ERROR event with 1 parm");
			stringAppender.Reset();

			// ***
			log1.ErrorFormat("a{0}b{1}", "1", "2");
			replacedert.AreEqual("ERROR:a1b2", stringAppender.GetString(), "Test formatted ERROR event with 2 parm");
			stringAppender.Reset();

			// ***
			log1.ErrorFormat("a{0}b{1}c{2}", "1", "2", "3");
			replacedert.AreEqual("ERROR:a1b2c3", stringAppender.GetString(), "Test formatted ERROR event with 3 parm");
			stringAppender.Reset();


			// ***
			log1.ErrorFormat("a{0}b{1}c{2}d{3}e{4}f", "Q", "W", "E", "R", "T", "Y");
			replacedert.AreEqual("ERROR:aQbWcEdReTf", stringAppender.GetString(), "Test formatted ERROR event with 5 parms (only 4 used)");
			stringAppender.Reset();

			// ***
			log1.ErrorFormat(null, "Before {0} After {1}", "Middle", "End");
			replacedert.AreEqual("ERROR:Before Middle After End", stringAppender.GetString(), "Test formatting with null provider");
			stringAppender.Reset();

			// ***
			log1.ErrorFormat(new CultureInfo("en"), "Before {0} After {1}", "Middle", "End");
			replacedert.AreEqual("ERROR:Before Middle After End", stringAppender.GetString(), "Test formatting with 'en' provider");
			stringAppender.Reset();
		}

19 View Source File : StringFormatTest.cs
License : Apache License 2.0
Project Creator : apache

[Test]
		public void TestLogFormatApi_NoError()
		{
			StringAppender stringAppender = new StringAppender();
			stringAppender.Threshold = Level.Fatal;
			stringAppender.Layout = new PatternLayout("%level:%message");

			ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
			BasicConfigurator.Configure(rep, stringAppender);

			ILog log1 = LogManager.GetLogger(rep.Name, "TestLogFormatApi_Error");

			// ***
			log1.Error("TestMessage");
			replacedert.AreEqual("", stringAppender.GetString(), "Test simple ERROR event 1");
			stringAppender.Reset();

			// ***
			log1.Error("TestMessage", null);
			replacedert.AreEqual("", stringAppender.GetString(), "Test simple ERROR event 2");
			stringAppender.Reset();

			// ***
			log1.Error("TestMessage", new Exception("Exception message"));
			replacedert.AreEqual("", stringAppender.GetString(), "Test simple ERROR event 3");
			stringAppender.Reset();

			// ***
			log1.ErrorFormat("a{0}", "1");
			replacedert.AreEqual("", stringAppender.GetString(), "Test formatted ERROR event with 1 parm");
			stringAppender.Reset();

			// ***
			log1.ErrorFormat("a{0}b{1}", "1", "2");
			replacedert.AreEqual("", stringAppender.GetString(), "Test formatted ERROR event with 2 parm");
			stringAppender.Reset();

			// ***
			log1.ErrorFormat("a{0}b{1}c{2}", "1", "2", "3");
			replacedert.AreEqual("", stringAppender.GetString(), "Test formatted ERROR event with 3 parm");
			stringAppender.Reset();


			// ***
			log1.ErrorFormat("a{0}b{1}c{2}d{3}e{4}f", "Q", "W", "E", "R", "T", "Y");
			replacedert.AreEqual("", stringAppender.GetString(), "Test formatted ERROR event with 5 parms (only 4 used)");
			stringAppender.Reset();

			// ***
			log1.ErrorFormat(null, "Before {0} After {1}", "Middle", "End");
			replacedert.AreEqual("", stringAppender.GetString(), "Test formatting with null provider");
			stringAppender.Reset();

			// ***
			log1.ErrorFormat(new CultureInfo("en"), "Before {0} After {1}", "Middle", "End");
			replacedert.AreEqual("", stringAppender.GetString(), "Test formatting with 'en' provider");
			stringAppender.Reset();
		}

19 View Source File : Log4NetLogger.cs
License : Apache License 2.0
Project Creator : aspnet

public void Log(TraceLevel level, string message, Exception ex)
        {
            switch (level)
            {
                case TraceLevel.Fatal:
                    Logger.Fatal(message, ex);
                    break;

                case TraceLevel.Error:
                    Logger.Error(message, ex);
                    break;

                case TraceLevel.Warn:
                    Logger.Warn(message, ex);
                    break;

                case TraceLevel.Info:
                    Logger.Info(message, ex);
                    break;

                case TraceLevel.Debug:
                    Logger.Debug(message, ex);
                    break;
            }
        }

19 View Source File : LogHelper.cs
License : MIT License
Project Creator : chi8708

public void Error(object message, Exception e)
        {
            this.logger.Error(message, e);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : craignicholson

private static void LogSamples()
        {
            // The global context is shared by all threads in the current AppDomain. This context is thread
            // safe for use by multiple threads concurrently.  We can create these as needed and add these
            // into layout pattern or have the ability to remove from the conversionPattern.
            // https://logging.apache.org/log4net/release/manual/contexts.html
            // Adding these into the conversionPattern _-> %property{EnreplacedyName} and  %property{AllocatedBytes}
            log4net.GlobalContext.Properties["EnreplacedyName"] = EnreplacedyName;
            log4net.GlobalContext.Properties["AllocatedBytes"] = new StructuredMessage.GcAllocatedBytesHelper();

            Logger.Info(MyLogMessage.GetMessage(Guid.NewGuid().ToString(), "LogSamples"));
            Logger.InfoFormat(MyLogMessage.GetMessage(Guid.NewGuid().ToString(), "LogSamples"));

            Logger.Debug(MyLogMessage.GetMessage(Guid.NewGuid().ToString(), "LogSamples"));
            Logger.DebugFormat(MyLogMessage.GetMessage(Guid.NewGuid().ToString(), "LogSamples"));

            Logger.Error(MyLogMessage.GetMessage(Guid.NewGuid().ToString(), "LogSamples"));
            Logger.ErrorFormat(MyLogMessage.GetMessage(Guid.NewGuid().ToString(), "LogSamples"));

            Logger.Fatal(MyLogMessage.GetMessage(Guid.NewGuid().ToString(), "LogSamples"));
            Logger.FatalFormat(MyLogMessage.GetMessage(Guid.NewGuid().ToString(), "LogSamples"));

            Logger.Warn(MyLogMessage.GetMessage(Guid.NewGuid().ToString(), "LogSamples"));
            Logger.WarnFormat(MyLogMessage.GetMessage(Guid.NewGuid().ToString(), "LogSamples"));
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : craignicholson

private static void LogErrors()
        {
            var correlationId = new Guid().ToString();
            Logger.Error(
                MyLogMessage.GetMessage(
                    correlationId: correlationId,
                    methodName: "Program.LogErrors",
                    message: "Running LogErrors Test",
                    error: "IF ONE EXISTS",
                    stackTrace: "IF YOU WANT IT",
                    exception: new Exception("Test Exception")));
        }

19 View Source File : App.xaml.cs
License : Apache License 2.0
Project Creator : danielpalme

private static void HandleException(Exception ex)
        {
            logger.Error("Unhandled exception occured.", ex);
            MessageBox.Show(string.Format(CultureInfo.InvariantCulture, Palmmedia.BackUp.UI.Wpf.Properties.Resources.ApplicationError, ex.Message));
        }

19 View Source File : Log4NetLogger.cs
License : Apache License 2.0
Project Creator : dotnetcore

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }
            Check.NotNull(formatter, nameof(formatter));
            string message = null;
            if (formatter != null)
            {
                message = formatter(state, exception);
            }
            if (!string.IsNullOrEmpty(message) || exception != null)
            {
                switch (logLevel)
                {
                    case LogLevel.Trace:
                    case LogLevel.Debug:
                        _log.Debug(message);
                        break;
                    case LogLevel.Information:
                        _log.Info(message);
                        break;
                    case LogLevel.Warning:
                        _log.Warn(message);
                        break;
                    case LogLevel.Error:
                        _log.Error(message, exception);
                        break;
                    case LogLevel.Critical:
                        _log.Fatal(message, exception);
                        break;
                    case LogLevel.None:
                        break;
                    default:
                        _log.Warn($"遇到未知的日志级别 {logLevel}, 使用Info级别写入日志。");
                        _log.Info(message, exception);
                        break;
                }
            }
        }

19 View Source File : NoteEditor.xaml.cs
License : MIT License
Project Creator : ekblom

private string ToggleFormatting(string text, string startFormat, string endFormat, int selectionStart, int selectionLength)
        {
            var expression =
                [email protected]"{Regex.Escape(startFormat)}
                    (?:      # Start of non-capturing group that matches...
                     (?!{Regex.Escape(startFormat)}) # (if startFormat can't be matched here)
                     .       # any character
                    ) *?      # Repeat any number of times, as few as possible
                    {Regex.Escape(endFormat)}";
            try
            {
                var reg = new Regex(expression, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);

                var matches = reg.Matches(text);
                if (matches.Count > 0)
                    foreach (Match m in matches)
                        if (selectionStart >= m.Index && selectionStart + selectionLength <= m.Index + m.Length)
                            if (m.Value.StartsWith(startFormat) && m.Value.EndsWith(endFormat))
                            {
                                text = text.Remove(m.Index, m.Length);
                                text = text.Insert(m.Index, m.Value.Replace(startFormat, string.Empty).Replace(endFormat, string.Empty).TrimStart());
                                return text;
                            }

                if (selectionLength == 0)
                    return text;

                var selection = text.Substring(selectionStart, selectionLength);
                text = text.Remove(selectionStart, selectionLength);
                text = text.Insert(selectionStart, startFormat + selection + endFormat);
                return text;
            }
            catch (Exception e)
            {
                _log.Error("Exception when formatting with " + startFormat, e);
            }

            return text;
        }

19 View Source File : DataStore.cs
License : MIT License
Project Creator : ekblom

public void BackupData()
        {
            try
            {
                var backupFile = _backupFolder.FullName + "\\" + DateTime.Now.ToString(BackupFileDateFormat) + ".zip";
                ZipFile.CreateFromDirectory(_dataFolder.FullName, backupFile, CompressionLevel.Fastest, false);
            }
            catch (Exception e)
            {
                _log.Error("Error when creating backup file.", e);
            }
        }

19 View Source File : DataStore.cs
License : MIT License
Project Creator : ekblom

public void CleanBackupData(int backupsToKeep)
        {
            if (backupsToKeep <= 0)
                return;

            try
            {
                var temp = _backupFolder.GetFiles("*.zip");
                if (temp.Length == 0)
                    return;

                var files = new List<FileInfo>();
                files.AddRange(temp);

                files.Sort((x, y) => DateTime.Compare(GetFileDate(y), GetFileDate(x)));

                var filesToDelete = files.Skip(backupsToKeep).ToList();

                filesToDelete.ForEach(fi => fi.Delete());
            }
            catch (Exception e)
            {
                _log.Error(e.Message, e);
            }
        }

19 View Source File : App.xaml.cs
License : MIT License
Project Creator : ekblom

public void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            if (_log != null)
            {
                _log.Error(e.Exception.Message, e.Exception);
                return;
            }

            Hub.Instance.AppSettings.LogFatal(e.Exception.ToString());
        }

19 View Source File : DataStore.cs
License : MIT License
Project Creator : ekblom

private void HandleNoteChange(FileSystemEventArgs e)
        {
            var fileName = Path.GetFileName(e.FullPath);
            if (string.IsNullOrWhiteSpace(fileName))
                return;

            var idString = fileName.Replace("." + File.NoteFileExtension, string.Empty);
            Guid noteId;
            if (Guid.TryParse(idString, out noteId))
            {
                var n = GetNote(noteId);
                if (n != null)
                {
                    if (e.ChangeType == WatcherChangeTypes.Changed)
                    {
                        var tempNote = FileHelpers.LoadObjectFromFile<Note>(new FileInfo(e.FullPath));
                        if (tempNote.Changed > n.Changed)
                            try
                            {
                                n.IsUpdatingFromDisc = true;
                                Application.Current.Dispatcher.Invoke(() =>
                                {
                                    tempNote?.CopyProperties(n);
                                    tempNote?.RaiseRefreshedFromDisk();
                                });
                            }
                            catch (Exception ex)
                            {
                                _log.Error("Unable to update note from disk", ex);
                            }
                            finally
                            {
                                n.IsUpdatingFromDisc = false;
                            }
                    }
                    else if (e.ChangeType == WatcherChangeTypes.Deleted)
                    {
                        DeleteNote(n);
                    }
                }
                else
                {
                    n = FileHelpers.LoadObjectFromFile<Note>(new FileInfo(e.FullPath));
                    if (n != null)
                    {
                        var nb = GetNoteBook(n.Notebook);
                        if (nb != null && _cache.ContainsKey(nb))
                        {
                            var noteList = _cache[nb];
                            if (!noteList.Contains(n))
                                noteList.Add(n);
                        }
                    }
                }
            }

            _log.Debug($"Handled changed note {e.Name}");
        }

19 View Source File : Logger.cs
License : GNU General Public License v3.0
Project Creator : faib920

public void Error(object message, Exception exception = null)
        {
            log.Error(message, exception);
        }

See More Examples