branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>josephowatkins/simple-calendar<file_sep>/src/App.js import React from 'react'; import styled, { createGlobalStyle } from 'styled-components'; import Calendar from './Calendar'; const Center = styled.div` max-width: 702px; margin: 25px auto; background-color: #eeeeee; `; const GlobalStyle = createGlobalStyle` body { background-color: #eeeeee; padding: 0; height: 100%; font-family: Sans-Serif; } `; function App() { return ( <React.Fragment> <GlobalStyle /> <Center> <Calendar></Calendar> </Center> </React.Fragment> ); } export default App; <file_sep>/src/Calendar/index.js import React from 'react'; import styled, { css } from 'styled-components'; import moment from 'moment'; import * as R from 'ramda'; const DAY_NAMES = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]; const Title = styled.div` flex: 1 0 auto; margin-bottom: 15px; font-size: 30px; `; const Content = styled.div` border: 1px solid black; background-color: #fff; display: flex; flex-wrap: wrap; `; const Date = styled.div` margin: 4px; padding: 4px; color: ${props => (props.isInMonth ? '#000' : '#b3b3b3')}; ${props => props.isToday && css` height: 18px; width: 18px; text-align: center; border-radius: 50%; background-color: red; color: white; `} `; const Box = styled.div` flex: 0 0 auto; width: 100px; height: 100px; box-sizing: border-box; border: 1px solid black; `; function DateBox({ isInMonth, isToday, children }) { return ( <Box> <Date isInMonth={isInMonth} isToday={isToday}> {children} </Date> </Box> ); } const Day = styled.div` display: inline-block; width: 100px; box-sizing: border-box; padding-left: 5px; margin-bottom: 7px; font-size: 15px; `; function generateDays() { const today = moment().startOf('day'); const start = moment() .startOf('month') .startOf('week'); const end = moment() .endOf('month') .endOf('week'); const startOfMonth = moment().startOf('month'); const endOfMonth = moment().endOf('month'); const days = R.unfold( date => (date.isAfter(end) ? false : [date.clone(), date.add(1, 'days')]), start ); return days.map(day => ({ number: day.date(), isToday: day.isSame(today), isInMonth: day.isBetween(startOfMonth, endOfMonth, null, '[]'), ISOString: day.toISOString() })); } export default function() { const days = generateDays(); return ( <div> <Title>December 2019</Title> {DAY_NAMES.map(name => ( <Day key={name}>{name}</Day> ))} <Content> {days.map(({ number, isInMonth, isToday, ISOString }) => ( <DateBox key={ISOString} isInMonth={isInMonth} isToday={isToday}> {number} </DateBox> ))} </Content> </div> ); }
3b5ff783cdca20eb19bffed80ab6c9fade02cd37
[ "JavaScript" ]
2
JavaScript
josephowatkins/simple-calendar
0d92a7a296f97894de0c6addf32ba81f7975641d
5a89bb8feccfa5cf480d137a8e45d143577411d7
refs/heads/master
<file_sep>package com.cognizant.gto.apexresearch.datasetgenerator.exception; public class DataGeneratorException extends Exception { private static final long serialVersionUID = 1L; public DataGeneratorException(Exception exception) { super(exception); } public DataGeneratorException(String errorMessage, Exception exception) { super(errorMessage, exception); } public DataGeneratorException(String errorMessage) { super(errorMessage); } } <file_sep>package com.cognizant.gto.apexresearch.datasetgenerator.model; public class UIComponents { private Component[] components; public Component[] getComponents() { return components; } public void setComponents(Component[] components) { this.components = components; } @Override public String toString() { return this.getClass().getSimpleName() + ": [components = " + components + "]"; } } <file_sep>package com.cognizant.gto.apexresearch.datasetgenerator.coco.model; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "id", "image_id", "category_id", "segmentation", "area", "bbox", "iscrowd" }) public class Annotation { @JsonProperty("id") private int id; @JsonProperty("image_id") private String imageId; @JsonProperty("category_id") private int categoryId; @JsonProperty("segmentation") private List<List<Float>> segmentation = null; @JsonProperty("area") private float area; @JsonProperty("bbox") private List<Float> bbox = null; @JsonProperty("iscrowd") private String iscrowd; @JsonProperty("id") public int getId() { return id; } @JsonProperty("id") public void setId(int id) { this.id = id; } @JsonProperty("image_id") public String getImageId() { return imageId; } @JsonProperty("image_id") public void setImageId(String imageId) { this.imageId = imageId; } @JsonProperty("category_id") public int getCategoryId() { return categoryId; } @JsonProperty("category_id") public void setCategoryId(int categoryId) { this.categoryId = categoryId; } @JsonProperty("segmentation") public List<List<Float>> getSegmentation() { return segmentation; } @JsonProperty("segmentation") public void setSegmentation(List<List<Float>> segmentation) { this.segmentation = segmentation; } @JsonProperty("area") public float getArea() { return area; } @JsonProperty("area") public void setArea(float area) { this.area = area; } @JsonProperty("bbox") public List<Float> getBbox() { return bbox; } @JsonProperty("bbox") public void setBbox(List<Float> bbox) { this.bbox = bbox; } @JsonProperty("iscrowd") public String getIscrowd() { return iscrowd; } @JsonProperty("iscrowd") public void setIscrowd(String iscrowd) { this.iscrowd = iscrowd; } } <file_sep>package com.cognizant.gto.apexresearch.datasetgenerator.htmlgenerator; import static j2html.TagCreator.body; import static j2html.TagCreator.button; import static j2html.TagCreator.html; import static j2html.TagCreator.join; import static j2html.TagCreator.option; import static j2html.TagCreator.select; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.List; import java.util.Scanner; import org.apache.commons.lang3.StringUtils; import com.cognizant.gto.apexresearch.datasetgenerator.coco.model.Annotation; import com.cognizant.gto.apexresearch.datasetgenerator.coco.model.COCODataSetJSON; import com.cognizant.gto.apexresearch.datasetgenerator.coco.model.Category; import com.cognizant.gto.apexresearch.datasetgenerator.coco.model.Image; import com.cognizant.gto.apexresearch.datasetgenerator.coco.model.Info; import com.cognizant.gto.apexresearch.datasetgenerator.exception.DataGeneratorException; import com.cognizant.gto.apexresearch.datasetgenerator.exception.HTMLGeneratorException; import com.cognizant.gto.apexresearch.datasetgenerator.helper.FileHelper; import com.cognizant.gto.apexresearch.datasetgenerator.model.Attribute; import com.cognizant.gto.apexresearch.datasetgenerator.model.Component; import com.cognizant.gto.apexresearch.datasetgenerator.model.UIComponents; import com.fasterxml.jackson.databind.ObjectMapper; public class COCODatasetGenerator { private static final String DEFAULT_IMG_FORMAT = "jpg"; private static final int IMG_WIDTH = 100; private static final int IMG_HEIGHT = 25; private static String datasetImgFormat; private static COCODataSetJSON cocoDatasetJson; private static Info info; private static List<Image> images; private static List<Category> categories; private static List<Annotation> annotations; private static List<String> licenses; private static List<Float> bbox; private static List<List<Float>> segmentation; public static void generateCOCODataset(String imageFormat) throws DataGeneratorException { initialize(imageFormat); generateDataset(); } private static void initialize(String imageFormat) { datasetImgFormat = (StringUtils.isEmpty(imageFormat) ? DEFAULT_IMG_FORMAT : imageFormat).toLowerCase().trim(); Float[] bboxCoordinates = { (float) 0.0, (float) 0.0, (float) IMG_WIDTH, (float) IMG_HEIGHT }; bbox = Arrays.asList(bboxCoordinates); segmentation = new ArrayList<>(); Float[] segmentationRectCoordinates = { (float) 0.0, (float) IMG_HEIGHT, (float) 0.0, (float) 0.0, (float) IMG_WIDTH, (float) 0.0, (float) IMG_WIDTH, (float) IMG_HEIGHT, (float) 0.0, (float) IMG_HEIGHT }; List<Float> segmentationRectangle = Arrays.asList(segmentationRectCoordinates); segmentation.add(segmentationRectangle); cocoDatasetJson = new COCODataSetJSON(); info = new Info(); info.setContributor("<EMAIL>"); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); Calendar currentDateTime = Calendar.getInstance(); info.setDateCreated(dateFormat.format(currentDateTime.getTime())); info.setDescription("GUI Components DataSet"); info.setVersion("1.0"); info.setYear(currentDateTime.get(Calendar.YEAR)); cocoDatasetJson.setInfo(info); // Defaults to empty at present licenses = new ArrayList<String>(); cocoDatasetJson.setLicenses(licenses); images = new ArrayList<Image>(); categories = new ArrayList<Category>(); annotations = new ArrayList<Annotation>(); } private static void generateDataset() throws DataGeneratorException { UIComponents uiComponents = FileHelper.getObjectModel(); Component[] components = uiComponents.getComponents(); int counter = 0; for (Component component : components) { Category category = new Category(); category.setId(++counter); category.setName(component.getName()); category.setSupercategory("component"); categories.add(category); generateDataForComponent(component, counter); } cocoDatasetJson.setImages(images); cocoDatasetJson.setAnnotations(annotations); cocoDatasetJson.setCategories(categories); ObjectMapper mapper = new ObjectMapper(); try { mapper.writerWithDefaultPrettyPrinter() .writeValue(new File("C:\\GUIComponents\\json\\instances_train2017.json"), cocoDatasetJson); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void generateDataForComponent(Component component, int categoryId) throws HTMLGeneratorException { String componentName = component.getName(); Attribute[] attributes = component.getAttributes(); List<String> styleValues = new ArrayList<String>(); for (Attribute attribute : attributes) { styleValues = processAttribute(attribute, styleValues, componentName); } int counter = 0; j2html.attributes.Attribute zeroMarginPaddingAttribute = new j2html.attributes.Attribute("style", "margin:0;padding:0;"); for (String styleValue : styleValues) { j2html.attributes.Attribute componentAttribute = new j2html.attributes.Attribute("style", styleValue); String htmlContent = StringUtils.EMPTY; if (componentName.equalsIgnoreCase("button")) { htmlContent = html(body(button("Submit").attr(componentAttribute)).attr(zeroMarginPaddingAttribute)) .attr(zeroMarginPaddingAttribute).render(); } else if (componentName.equalsIgnoreCase("dropdown")) { htmlContent = html( body(select(option(join("option1"))).attr(componentAttribute)).attr(zeroMarginPaddingAttribute)) .attr(zeroMarginPaddingAttribute).render(); } String imageFileName = componentName + ++counter; try (PrintWriter out = new PrintWriter("C:\\GUIComponents\\html\\" + imageFileName + ".html")) { out.println(htmlContent); Image image = new Image(); image.setId(Integer.toString(counter)); image.setFileName(imageFileName + "." + datasetImgFormat); image.setHeight(IMG_HEIGHT); image.setWidth(IMG_WIDTH); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); Calendar currentDateTime = Calendar.getInstance(); image.setDateCaptured(dateFormat.format(currentDateTime.getTime())); images.add(image); Annotation annotation = new Annotation(); annotation.setId(counter); annotation.setCategoryId(categoryId); annotation.setImageId(Integer.toString(counter)); annotation.setIscrowd("0");// annotation individual/single gui component annotation.setArea(IMG_WIDTH * IMG_HEIGHT); annotation.setBbox(bbox); annotation.setSegmentation(segmentation); annotations.add(annotation); } catch (FileNotFoundException e) { e.printStackTrace(); } } } private static List<String> processAttribute(Attribute attribute, List<String> styleValues, String componentName) throws HTMLGeneratorException { String attributeName = attribute.getName(); String attributeValueType = attribute.getType(); String attributeValueSourceType = attribute.getSourceType(); if (attributeValueType.equalsIgnoreCase("list")) { if (attributeValueSourceType.equalsIgnoreCase("file")) { String attributeValuesFilePath = attribute.getFile(); ClassLoader classLoader = FileHelper.class.getClassLoader(); File attributeValuesFile = new File(classLoader.getResource(attributeValuesFilePath).getFile()); try (Scanner scanner = new Scanner(attributeValuesFile)) { List<String> attrValueList = new ArrayList<String>(); while (scanner.hasNextLine()) { attrValueList.add(scanner.nextLine()); } styleValues = processAttrValues(styleValues, attributeName, attrValueList); } catch (FileNotFoundException exception) { throw new HTMLGeneratorException(exception); } } else if (attributeValueSourceType.equalsIgnoreCase("values")) { String attrValues = attribute.getValues(); List<String> attrValueList = Arrays.asList(attrValues.split(",")); styleValues = processAttrValues(styleValues, attributeName, attrValueList); } else { String errMsg = "Unknown Attribute Value Source Type - " + attributeValueSourceType + ".\n Attribute " + attributeName + " of component " + componentName + " would be ignored!!"; } } else if (attributeValueType.equalsIgnoreCase("range")) { if (attributeValueSourceType.equalsIgnoreCase("values")) { String attrValueRange = attribute.getValues(); String[] attrValueRangeLimits = attrValueRange.split(","); int upperLimit = Integer.parseInt(attrValueRangeLimits[1]); int lowerLimit = Integer.parseInt(attrValueRangeLimits[0]); if (lowerLimit <= upperLimit) { int increment = attribute.getIncrement(); List<String> attrValueList = new ArrayList<String>(); for (int i = lowerLimit; i < upperLimit; i = i + increment) { attrValueList.add(StringUtils.EMPTY + i); } styleValues = processAttrValues(styleValues, attributeName, attrValueList); } else { String errMsg = "UpperLimit: " + upperLimit + " is less than LowerLimit: " + lowerLimit + " in specified range " + attrValueRange + " for attribute " + attributeName + "for Component " + componentName + ".\n Therefore attribute " + attributeName + " would be ignored!!"; } } else { String errMsg = "Unknown Attribute Value Source Type - " + attributeValueSourceType + ".\n Attribute " + attributeName + " of component " + componentName + " would be ignored!!"; } } else { String errMsg = "Unknown Attribute Value Type - " + attributeValueType + ".\n Attribute " + attributeName + " of component " + componentName + " would be ignored!!"; } return styleValues; } private static List<String> processAttrValues(List<String> styleValues, String attributeName, List<String> attrValueList) { if (styleValues.isEmpty()) { for (String attrValue : attrValueList) { // initialize with fixed height & width // String styleValue = StringUtils.EMPTY; // String styleValue = "width:100%;height:100%;"; String styleValue = "width:" + IMG_WIDTH + "px;height:" + IMG_HEIGHT + "px;"; styleValue = styleValue + attributeName + ":" + attrValue; styleValues.add(styleValue); } } else { List<String> tempStyleValues = new ArrayList<String>(); for (String styleValue : styleValues) { for (String attrValue : attrValueList) { String tempStyleValue = styleValue + ";" + attributeName + ":" + attrValue; tempStyleValues.add(tempStyleValue); } } styleValues = tempStyleValues; } return styleValues; } public static void main(String[] args) { try { generateCOCODataset("jpg"); } catch (DataGeneratorException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cognizant.gto.apexresearch</groupId> <artifactId>datasetgenerator</artifactId> <version>1.0.0</version> <name>DataSetGenerator</name> <description>DataSet Generator</description> <dependencies> <!-- <dependency> <groupId>gui.ava</groupId> <artifactId>html2image</artifactId> <version>0.9</version> </dependency> --> <dependency> <groupId>com.pdfcrowd</groupId> <artifactId>pdfcrowd</artifactId> <version>4.3.6</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.j2html</groupId> <artifactId>j2html</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.5</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.0</version> </dependency> </dependencies> <!-- <repositories> <repository> <id>yoava</id> <name>AOL yoava</name> <url>http://yoava.artifactoryonline.com/yoava/repo</url> </repository> </repositories> --> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project> <file_sep>package com.cognizant.gto.apexresearch.datasetgenerator.coco.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "year", "version", "description", "contributor", "url", "date_created" }) public class Info { @JsonProperty("year") private int year; @JsonProperty("version") private String version; @JsonProperty("description") private String description; @JsonProperty("contributor") private String contributor; @JsonProperty("url") private String url; @JsonProperty("date_created") private String dateCreated; @JsonProperty("year") public int getYear() { return year; } @JsonProperty("year") public void setYear(int year) { this.year = year; } @JsonProperty("version") public String getVersion() { return version; } @JsonProperty("version") public void setVersion(String version) { this.version = version; } @JsonProperty("description") public String getDescription() { return description; } @JsonProperty("description") public void setDescription(String description) { this.description = description; } @JsonProperty("contributor") public String getContributor() { return contributor; } @JsonProperty("contributor") public void setContributor(String contributor) { this.contributor = contributor; } @JsonProperty("url") public String getUrl() { return url; } @JsonProperty("url") public void setUrl(String url) { this.url = url; } @JsonProperty("date_created") public String getDateCreated() { return dateCreated; } @JsonProperty("date_created") public void setDateCreated(String dateCreated) { this.dateCreated = dateCreated; } } <file_sep>package com.cognizant.gto.apexresearch.datasetgenerator.coco.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "supercategory", "id", "name" }) public class Category { @JsonProperty("supercategory") private String supercategory; @JsonProperty("id") private int id; @JsonProperty("name") private String name; @JsonProperty("supercategory") public String getSupercategory() { return supercategory; } @JsonProperty("supercategory") public void setSupercategory(String supercategory) { this.supercategory = supercategory; } @JsonProperty("id") public int getId() { return id; } @JsonProperty("id") public void setId(int id) { this.id = id; } @JsonProperty("name") public String getName() { return name; } @JsonProperty("name") public void setName(String name) { this.name = name; } } <file_sep>package com.cognizant.gto.apexresearch.datasetgenerator.exception; public class HTMLGeneratorException extends DataGeneratorException { private static final long serialVersionUID = 1L; public HTMLGeneratorException(Exception exception) { super(exception); } public HTMLGeneratorException(String errorMessage, Exception exception) { super(errorMessage, exception); } public HTMLGeneratorException(String errorMessage) { super(errorMessage); } } <file_sep>package com.cognizant.gto.apexresearch.datasetgenerator.exception; public class HTMLToImageConverterException extends DataGeneratorException { private static final long serialVersionUID = 1L; public HTMLToImageConverterException(Exception exception) { super(exception); } public HTMLToImageConverterException(String errorMessage, Exception exception) { super(errorMessage, exception); } public HTMLToImageConverterException(String errorMessage) { super(errorMessage); } }
f2ee6f5e92f38bb5c8ec574ad291bc5123a30e23
[ "Java", "Maven POM" ]
9
Java
hkuyam008/DatasetGenerator
a46762daac35cfae019894195406b712a1e02b82
529c6887828956af48a8cf7033a93a400f311791
refs/heads/master
<repo_name>ignacykasperowicz/code-challenges<file_sep>/bob-bot/backend/app.rb require 'em-websocket' require_relative 'lib/responser' EM.run do EM::WebSocket.run(:host => "0.0.0.0", :port => 8080) do |ws| ws.onmessage { |msg| responser ||= Responser.new ws.send responser.get_answer(msg).dup } end end <file_sep>/bob-bot/README.md This is a two part test. The first part is to write a very simple chat bot with some very specific canned responses. The second is to write a realtime chat application to interface with the chat bot. The required technologies here are Ruby, Coffeescript / Javscript outside of that you may use any gems or npm modules to assist in the completion. Ruby === This is a simple evaluation problem. You'll code Bob, a simple message responder as follows: * Bob answers 'Sure.' if you ask him a question. * He answers 'Woah, chill out!' if you yell at him (ALL CAPS). * He says 'Fine. Be that way!' if you address him without actually saying anything. * He answers 'Whatever.' to anything else. * Write tests to asset the above is working correctly. *Do not use “if”, “unless” or “case” in your response code.* Coffeescript / Javascript === This is a simple real time, browser based chat room to interface with Bob as follows: * Public Lobby - Each user joining the lobby should be assigned a numbered username (e.g. User1234). * Private Messages - Each user should be able to send/receive private messages. * Bob should be able to listen, and respond to both the public lobby, and his own private messages. * Write tests to assess the above is working correctly. ## Setup ### Backend Install dependencies: ``` $ bundle install ``` Validate tests: ``` $ ruby tests/responser_test.rb ``` Run server: ``` $ ruby app.rb ``` Server listens at `ws://localhost:8080` ### Frontend Install dependencies: ``` $ npm install ``` Run server: ``` $ node app.js ``` Open web page at `http://localhost:3000` ## Usage #### Chat * `chat` shows each message send to chat room with username as a prefix * `Socket.io` is used for communication between users #### Bot * `bob-bot` can be asked by using `bot` mention in message e.g. `bot how was your day?` * `chat` and `bot-bot` uses clean WS to interact * on chat window only `bob-bot` response is shown #### Private messages * private message can be sent to a user by using mention e.g. `user1234 this is for your eyes only` * private message is marked as orange <file_sep>/bob-bot/backend/tests/responser_test.rb require 'minitest/autorun' require_relative '../lib/responser' class TestResponses < Minitest::Test def setup @responser = Responser.new end def test_question_message assert_equal "Sure", @responser.get_answer('foobar?') end def test_question_mark_message assert_equal "Whatever", @responser.get_answer('?foobar') end def test_uppercase_message assert_equal "Woah, chill out!", @responser.get_answer('FOOBAR BARFOO') end def test_empty_message assert_equal "Fine. Be that way!", @responser.get_answer('') end def test_not_matched_message assert_equal "Whatever", @responser.get_answer('foobar FDFDF') end end<file_sep>/bob-bot/backend/lib/responser.rb class Responser def get_answer(msg) h = { 'Sure' => question?(msg), 'Woah, chill out!' => capitals?(msg), 'Fine. Be that way!' => msg.empty?, 'Whatever' => not_matched?(msg) } h.key(true) end private def question?(msg) !(msg.scan /\?$/).empty? end def capitals?(msg) !(msg.scan /^[A-Z\s]+$/).empty? && !msg.empty? end def not_matched?(msg) !question?(msg) && !capitals?(msg) && !msg.empty? end end<file_sep>/bob-bot/frontend/app.js var express = require('express'); var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var _ = require('lodash'); var users = []; app.use(express.static('public')); app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); var userName = function() { return 'user' + Math.floor(1000 + Math.random() * 9000); }; var findUserBySocketId = function(socket) { return _.find(users, function(user) { return user.socket == socket; }); }; io.on('connection', function(socket){ users.push({ name: userName(), socket: socket.id }); io.emit('connected', { users: users, user: socket.id } ); socket.on('disconnect', function() { _.remove(users, { socket: socket.id }); io.emit('disconnected', { users: users } ); }); socket.on('send-private-message', function(data) { var user = findUserBySocketId(data.from) data['name'] = user.name; io.to(data.to).emit('receive-private-message', data); io.to(data.from).emit('receive-private-message', data); }); socket.on('send-public-message', function(data){ var user = findUserBySocketId(data.from) data['name'] = user.name; io.emit('receive-public-message', data); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); });<file_sep>/bob-bot/frontend/public/scripts.js var socket = io(); var allUsers; var ws; var setupEvents = function() { $('#users').on('click', 'li.username', function() { $('#m').val($(this).text() + ' '); $('#m').focus(); }); } var setupBot = function() { ws = new WebSocket("ws://localhost:8080"); ws.onmessage = function(message) { helpers.showBotMessage({ name: 'bob-bot', msg: message.data }); }; } var setupSockets = function() { socket.on('receive-private-message', function(data) { helpers.showPrivateMessage(data); }); socket.on('receive-public-message', function(data) { helpers.showPublicMesage(data); }); socket.on('connected', function(users) { allUsers = users.users; helpers.refreshUsersList(users.users); }); socket.on('disconnected', function(users) { helpers.refreshUsersList(users.users); }); } setupEvents(); setupBot(); setupSockets(); $('form').submit(function() { var msg = $('#m').val(); if( helpers.isBotMessage(msg) ) { ws.send( helpers.trimBotMessage(msg) ); } if( helpers.isPrivateMessage(msg) ) { var toUser = helpers.findUserByUserName( helpers.toUserName( msg ) ); if( toUser ) { if( toUser.socket != helpers.currentUserSocketId() ) { socket.emit('send-private-message', { from: helpers.currentUserSocketId(), to: toUser.socket, msg: helpers.trimPrivateMessage(msg) }); } else { helpers.showErrorMessage('You cannot send private message to yourself.'); } } else { helpers.showErrorMessage('User ' + helpers.toUserName(msg) + ' does not exists.'); } } if( helpers.isPublicMessage(msg) ) { socket.emit('send-public-message', { from: helpers.currentUserSocketId(), msg: msg }); } $('#m').val(''); return false; }); <file_sep>/words/analyser.rb class Parser attr_accessor :sourced, :mapped, :reversed, :filtered WINDOW_SIZE = 4 def initialize @sourced = [] @mapped = [] @reversed = Hash.new { |h, k| h[k] = [] } @filtered = {} end def parse read map reverse filter save end private def read @sourced = File.foreach('dictionary.txt').inject([]) { |arr, line| arr << line.strip } end def split(word) (0..word.length - WINDOW_SIZE).inject([]) { |ret, index| ret << word[index..index + WINDOW_SIZE - 1] } end def map sourced.each do |word| split = split(word) split.each { |sequence| @mapped << [word, sequence] } unless split.empty? end end def reverse mapped.map(&:reverse).each { |pair| @reversed[pair.first] << pair.last } end def filter reversed.each { |sequence, words| @filtered[sequence] = words.flatten unless words.size > 1 } end def save File.open('words.txt', 'w') { |file| file.puts(filtered.values) } File.open('sequences.txt', 'w') { |file| file.puts(filtered.keys) } end end Parser.new.parse
8f6a3922ba3ba6ccfa8af85c10e19f044d0f7318
[ "Markdown", "JavaScript", "Ruby" ]
7
Ruby
ignacykasperowicz/code-challenges
af23559d4c8c207b5c6873aa541a745d07db9888
4b41c7751dbeb37edb44c862dc10856c8e410af3
refs/heads/master
<file_sep># Create your views here. from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect from django.contrib import messages from uniauth.decorators import login_required from .models import Checklist, Person, Deadline def start(request): st = request.GET.get('State') cache.set('a', st) print(cache.get('a')) return render(request, 'rise/start.html', {}) def issue(request): print(cache.get('a')) iss = request.GET.get('Issue') return render(request, 'rise/issue.html', {}) def index(request): return render(request, 'rise/index.html') def choice(request): return render (request, 'rise/choice.html') def action(request): return render (request, 'rise/action.html') def learn(request): peoplebutton = request.POST.get("people") deadlinesbutton = request.POST.get("deadlines") if peoplebutton: return render(request, 'rise/people.html') elif deadlinesbutton: return render(request, 'rise/deadlines.html') return render (request, 'rise/learn.html') def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('<PASSWORD>') user = authenticate(username=username, password=raw_password) login(request, user) messages.success(request, f'Your account has been created! You are now able to log in.') return redirect('start') else: form = UserCreationForm() return render(request, 'rise/register.html', {'form': form}) @login_required def checklist(request): user = request.user current_state = Checklist.objects.filter(user=user)[0].stateName return render(request, 'rise/checklist.html', {'current_state': current_state}) def people(request): user = request.user current_state = Checklist.objects.filter(user=user)[0].stateName people = Person.objects.filter(state=current_state) return render(request, 'rise/people.html', {'people': people}) def deadlines(request): user = request.user current_state = Checklist.objects.filter(user=user)[0].stateName deadlines = Deadline.objects.filter(state=current_state) return render (request, 'rise/deadlines.html', {'deadlines': deadlines}) <file_sep>from django.contrib import admin from .models import State, Campaign, Checklist # Register your models here. admin.site.register(State) admin.site.register(Campaign) <file_sep>from django.db import models from django.contrib.auth.models import User class State(models.Model): name = models.CharField(max_length=2, blank=False, null=False, primary_key=True) class Campaign(models.Model): name = models.CharField(max_length=200, blank=False, null=False) state = models.ForeignKey("State", models.DO_NOTHING, blank=False, null=False) class Person(models.Model): first_name = models.CharField(max_length=100, blank=False, null=False) last_name = models.CharField(max_length=100, blank=False, null=False) email = models.CharField(max_length=300, blank=True, null=True) district = models.IntegerField(blank=True, null=False) party = models.CharField(max_length=3, blank=False, null=False) first_elected = models.IntegerField(blank=True, null=True) state = models.ForeignKey("State", models.DO_NOTHING, blank=False, null=False) campaign = models.ForeignKey("Campaign", models.DO_NOTHING, blank=False, null=False) branch = models.CharField(max_length=15, null=False) number = models.BigIntegerField(null=True) class Deadline(models.Model): name = models.CharField(max_length=100, blank=False, null=False, primary_key=True) date = models.DateField(blank=False, null=False) state = models.ForeignKey("State", models.DO_NOTHING, blank=False, null=False) class Checklist(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) stateName = models.CharField(max_length=2, blank=False, null=False) campaignName = models.CharField(max_length=200, blank=False, null=False) def __str__(self): return f'{self.user.username} Profile'<file_sep>from django.urls import path from . import views urlpatterns = [ path('', views.index, name='rise-index'), path('issue.html', views.issue, name='rise-issue'), path('choice.html/', views.choice, name='rise-choice'), path('action.html/', views.action, name='rise-action'), path('learn.html/', views.learn, name='rise-learn'), path('register.html/', views.register, name='rise-register'), ] <file_sep>certifi==2019.9.11 chardet==3.0.4 dj-database-url==0.5.0 Django==2.2.5 django-crispy-forms==1.7.2 django-uniauth==1.2.2 gunicorn==19.9.0 idna==2.8 lxml==4.4.1 psycopg2==2.8.3 python-cas==1.4.0 pytz==2019.2 requests==2.22.0 six==1.12.0 sqlparse==0.3.0 urllib3==1.25.6 whitenoise==4.1.4
fc6368db095cd669743da71bba22b836204e5ed1
[ "Python", "Text" ]
5
Python
delaware19/team-3
6c9c1bfbb83b8cb00383e480e39f529433544dd2
a1156bd67460e5ee994f9651fef3c693bf28cbf4
refs/heads/master
<repo_name>joerobmunoz/Inter-App-Messaging<file_sep>/Database.py __author__ = '<NAME>' import sqlite3 from MessageObject import Message class Deployment(): def deploy(self): try: db = sqlite3.connect(':memory:') cursor = db.cursor() cursor.execute(''' CREATE TABLE messages(id INTEGER PRIMARY KEY, sender TEXT, application TEXT unique, message TEXT, creation_time TEXT) ''') db.commit() except Exception as e: db.rollback() finally: db.close() def drop(self): try: # Get a cursor object db = sqlite3.connect(':memory:') cursor = db.cursor() cursor.execute('''DROP TABLE users''') db.commit() except Exception as e: db.rollback() finally: db.close() class MessageOperations(): def insert(self, Message): try: db = sqlite3.connect(':memory:') cursor = db.cursor() cursor.execute( '''INSERT INTO users(sender, application, message, creation_time) VALUES(?, ?, ?, ?)''', (Message.sender, Message.application, Message.message, Message.creation_time) ) db.commit() except Exception as e: db.rollback() finally: db.close() def remove_by_id(self, id): try: db = sqlite3.connect(':memory:') cursor = db.cursor() cursor.execute('''DELETE FROM messages WHERE id = ? ''', (id)) db.commit() except Exception as e: db.rollback() finally: db.close() def get_first(self): db = sqlite3.connect(':memory:') cursor = db.cursor() cursor.execute( '''SELECT id, sender, application, message, creation_time FROM messages ORDER BY id ASC LIMIT 1''' ) def last_row_id(self): db = sqlite3.connect(':memory:') cursor = db.cursor() return cursor.lastrowid def get_by_id(self, id): db = sqlite3.connect(':memory:') cursor = db.cursor() cursor.execute( '''SELECT name, email, phone FROM users WHERE id=?''', id ) <file_sep>/Client.py __author__ = '<NAME>' #!/usr/bin/env python """ Client implementation of a client/server inter-application messaging system. This consists of the main pushing client and an additional open socket to receive pushes from the server. """ import Database import socket import sys import getopt import datetime import time import thread # Constants port = 54307 size = 1024 host = 'localhost' class Client(): def __init__(self): self.address = (host, port) self.soc = None # Database doesn't do anything yet. def set_up_database(self): db = Database.Deployment() db.deploy() # Kicks off the listener and the initial socket connection def establish_socket_connection(self): try: self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connected = False while connected == False: self.soc.connect(self.address) self.listener = thread.start_new_thread(self.listen, ()) connected = True self.send_data() except socket.error, (value, message): if self.soc: self.soc.close() print "Socket error: " + message self.reconnect() # Reconnect method can be changed to include fixed polling and writing failed messages # to the DB. def reconnect(self): connected = False try: while connected == False: if self.soc: self.soc.connect(self.address) conntected = True except socket.error as e: print "Socket error: " + e.message time.sleep(1) def listen(self): while self.soc: msg = self.soc.recv(size) print "Received (" + str(datetime.datetime.now()) + "): " + msg + "%" def send_data(self): sys.stdout.write('%') while 1: data_to_send = sys.stdin.readline() try: bytes_sent = self.soc.send(data_to_send) if bytes_sent == 0: self.establish_socket_connection() else: sys.stdout.write('%') except socket.error, (value, message): print "Could not send data over socket: " + message + "\n Attempting to reconnect..." self.establish_socket_connection() # Command line args to set the host and port def main(argv): try: opts, args = getopt.getopt(argv,"hi:o:",["host","port"]) except getopt.GetoptError: print "Client.py -h <host> -p <post>\nDefaults to 'localhost' and '54322'" sys.exit(2) for opt, arg in opts: if opt == '-l': print "Client.py -h <host> -p <post>\nDefaults to " + str(host) + " and " + str(port) sys.exit() elif opt in ("-h", "--host"): host = arg elif opt in ("-p", "--post"): port = arg # Set up the client cli = Client() cli.set_up_database() cli.establish_socket_connection() if __name__ == "__main__": main(sys.argv[1:]) <file_sep>/Server.py __author__ = '<NAME>' #!/usr/bin/env python """ Server implementation of a client/server inter-application messaging system. This is comprised of the main server, and alternate thread workers that push updates to existing socket connections. """ import Database import socket import sys import getopt import thread import time import select # Constants size = 1024 backlog = 10 host = 'localhost' port = 54307 # Main server class. Just call #start() and it deploys the DB and socket listener class Server: def __init__(self): self.address = (host, port) self.clients = dict() def start(self): db = Database.Deployment() db.deploy() self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.soc.bind(self.address) self.soc.listen(backlog) self.acceptor = thread.start_new_thread(self.accept, ()) # Kick off separate listener thread # TODO BUG # This thread needs to take a back seat, but this is not the right way. time.sleep(500000) def stop(self): self.soc = None def accept(self): try: input = [self.soc, sys.stdin] while self.soc: inputready, outputready, exceptready = select.select(input, [], []) for s in inputready: if s == self.soc: # handle the server socket connection, name = self.soc.accept() print str(name[0]) + ":" + str(name[1]) + "@ has connected" cli = Client(conn=connection, cl=name) self.clients[name] = cli cli.spoke = self.tell except socket.error as e: print "Error accepting socket connection\n:" + e.message self.soc.close() def tell(self, ip, msg): print str(ip[0]) + ":" + str(ip[1]) + "@ " + msg for id in self.clients: self.clients[id].hear(msg) # Server implementation of the Client Object. class Client: def __init__(self, conn, cl): self.soc = conn self.ip = cl self.cliname = cl self.spoke = None self.speaker = thread.start_new_thread(self.speak, ()) def speak(self): while self.soc: msg = self.soc.recv(size) if msg: self.spoke(self.cliname, msg) def hear(self, msg): self.soc.send(msg) # Command line args to set the host and port def main(argv): try: opts, args = getopt.getopt(argv, "hi:o:", ["host", "port"]) except getopt.GetoptError: print "Client.py -h <host> -p <post>\nDefaults to 'localhost' and '54322'" sys.exit(2) for opt, arg in opts: if opt == '-l': print "Client.py -h <host> -p <post>\nDefaults to " + str(host[0]) + " and " + str(port) sys.exit() elif opt in ("-h", "--host"): host = arg elif opt in ("-p", "--post"): port = arg Server().start() if __name__ == "__main__": main(sys.argv[1:])<file_sep>/MessageObject.py __author__ = '<NAME>' import datetime class Message(): def __init__(self, sender="default", application="default", message=""): self.sender = sender self.application = application self.message = message self.creation_time = str(datetime.datetime.now()) def fill_from_db(self, row): self.id = row[0] self.sender = row[1] self.application = row[2] self.message = row[3] self.creation_time = row[4] <file_sep>/README.md Inter-App-Messaging =================== An inter app messaging system based on a subscriber-type system, managed by a socket server. UPDATE: - This application had reading/writing from the database pulled out of it to be reworked. Currently, any data not included in the socket connection is lost.
e9ebe4bbaa6d8bacc8a65ba2a061134a3d3fdd75
[ "Markdown", "Python" ]
5
Python
joerobmunoz/Inter-App-Messaging
e38cb664e41cca830344ecadffba9176b90745f6
9dc41fb2df1914fdbc2dd6c091e15cbb0bbddbdb
refs/heads/master
<repo_name>BB9z/MMOfficeAutomator<file_sep>/launcher.command #! /bin/sh set -euo pipefail cd "$(dirname "$0")" pwsh -File "$PWD/Scripts/main.ps1" <file_sep>/README.md # MMOfficeAutomatror ## 配置 需要 powershell core v6,安装包下载: * Windows 10 之前的系统需要装额外的[运行时依赖](https://download.microsoft.com/download/3/1/1/311C06C1-F162-405C-B538-D9DC3A4007D1/WindowsUCRT.zip) * [Win X64](https://github.com/PowerShell/PowerShell/releases/download/v6.2.3/PowerShell-6.2.3-win-x64.msi) * [Win x86](https://github.com/PowerShell/PowerShell/releases/download/v6.2.3/PowerShell-6.2.3-win-x86.msi) * [macOS 参照](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-macos) Windows 需装到 C 盘,或者自行改 `launcher.bat`。升级系统自带 PowerShell [参照](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-windows-powershell?view=powershell-6#upgrading-existing-windows-powershell)。
e5c96c9f580340ac90f7312980d1afcbca47831a
[ "Markdown", "Shell" ]
2
Shell
BB9z/MMOfficeAutomator
740b5ba2b96ee7de13925bb9dda4c1af91387937
4f04b3d92c3a4fe91c1ee0471de86c66c000147d
refs/heads/master
<repo_name>glyfina/OpenCV<file_sep>/main.c #include <iostream> #include <cv.h> #include <highgui.h> #include <stdio.h> #include <cxcore.h> #include <stdio.h> #define h 280 #define w 320 #include <math.h> #include "SerialPort.h" using namespace std; CSerialPort serial; int main() { serial.OpenSerial(); CvCapture* capture = cvCaptureFromCAM(2 ); if ( !capture ) { fprintf( stderr, "ERROR: capture is NULL \n" ); getchar(); //return -1; } int x; while(x!=27){ //IplImage*f=0; //f=setup(); IplImage* rimg=cvCreateImage(cvSize(w,h),8,3); IplImage* hsvimg =cvCreateImage(cvSize(w,h),8,3); cvNamedWindow("original",CV_WINDOW_AUTOSIZE); IplImage*img=0; img= cvQueryFrame( capture ); img= cvQueryFrame( capture ); img= cvQueryFrame( capture ); cvResize(img,rimg,CV_INTER_LINEAR); cvShowImage("original",rimg); cvCvtColor( rimg,hsvimg, CV_BGR2HSV ); //cvReleaseImage(&rimg); // cent(f); IplImage* thresh_r =cvCreateImage(cvSize(w,h),8,1); IplImage* thresh_b =cvCreateImage(cvSize(w,h),8,1); IplImage* thresh_g =cvCreateImage(cvSize(w,h),8,1); IplImage* hough =cvCreateImage(cvSize(w,h),8,1); cvInRangeS(hsvimg,cvScalar(0,121,78),cvScalar(15,250,255),thresh_r); cvInRangeS(hsvimg,cvScalar(101,121,64),cvScalar(170,250,255),thresh_b); cvInRangeS(hsvimg,cvScalar(64,121,64),cvScalar(106,255,255),thresh_g); cvNamedWindow("threshed",CV_WINDOW_AUTOSIZE); // centroid of red // Calculate the moments to estimate the position of the ball CvMoments *momentsr = (CvMoments*)malloc(sizeof(CvMoments)); cvMoments(thresh_r, momentsr, 1); // The actual moment values double moment10r = cvGetSpatialMoment(momentsr, 1, 0); double moment01r = cvGetSpatialMoment(momentsr, 0, 1); double arear = cvGetCentralMoment(momentsr, 0, 0); int posX_r; int posY_r; posX_r = moment10r/arear; posY_r = moment01r/arear; cout<< "x="<<posX_r; cout<< "y="<<posY_r; // centroid of blue // Calculate the moments to estimate the position of the ball CvMoments *momentsb = (CvMoments*)malloc(sizeof(CvMoments)); cvMoments(thresh_b, momentsb, 1); // The actual moment values double moment10b = cvGetSpatialMoment(momentsb, 1, 0); double moment01b = cvGetSpatialMoment(momentsb, 0, 1); double areab = cvGetCentralMoment(momentsb, 0, 0); int posX_b; int posY_b; posX_b = moment10b/areab; posY_b = moment01b/areab; cout<< "x="<<posX_b; cout<< "y="<<posY_b; // centroid of green // Calculate the moments to estimate the position of the ball cvCopy(thresh_g,hough,NULL); cvSmooth(hough,hough,CV_GAUSSIAN,5,5,0,0); //cvCanny(grayimg,thresh,h1,h2,3); CvMemStorage * storage=cvCreateMemStorage(0); CvSeq* circles= cvHoughCircles( hough, storage,CV_HOUGH_GRADIENT,4, hough->height/2 ,100 ,40,0 ,0); cvReleaseMemStorage(&storage); // draw circles int i; int u; int y; for (i=0;i<circles->total;i++){ float *p = (float*)cvGetSeqElem(circles, i); //cvCircle( img,center,radius,color,thickness,line type, shift) CvPoint center = cvPoint(cvRound(p[0]),cvRound(p[1])); // CvScalar val = cvGet2D(hough, center.y, center.x); //if (val.val[0] < 1) continue; //printf("x=%d, y=%d",cvRound(p[0]),cvRound(p[1])); if(i==0){ u=cvRound(p[0]); y=cvRound(p[1]); cout<< u; cout<< y; } cvCircle(hsvimg, center, 3, CV_RGB(0,255,0), -1, CV_AA, 0); cvCircle(hsvimg, center, cvRound(p[2]), CV_RGB(255,0,0), 3, CV_AA, 0); cvCircle(hough, center, 3, CV_RGB(0,255,0), -1, CV_AA, 0); cvCircle(hough, center, cvRound(p[2]), CV_RGB(255,0,0), 3, CV_AA, 0); } cvAdd(thresh_r,thresh_b,thresh_b); cvAdd(thresh_b,thresh_g,thresh_g); cvShowImage("threshed",thresh_g); cvReleaseImage(&thresh_r); cvReleaseImage(&thresh_b); cvReleaseImage(&thresh_g); cvReleaseImage(&hsvimg); cvReleaseImage(&hough); int dist0; int dist; dist0= (((posX_b-u)*(posX_b-u)) + ((posY_b-y)*(posY_b-y))); dist=sqrt(dist0); cout<<"dist="<<dist; int dist2; int dist3; dist2= (((posX_b-10)*(posX_b-10)) + ((posY_b-10)*(posY_b-10))); dist3=sqrt(dist2); cout<<"dist3="<<dist3; float slope1_f; float slope2_f; slope1_f=((posY_b-y)/(posX_b-u)); slope2_f=((posY_r-y)/(posX_r-u)); float slope1_b; float slope2_b; slope1_b=((posY_b-10)/(posX_b-10)); slope2_b=((posY_r-10)/(posX_r-10)); if(posX_b > posX_r){ if(dist < 35){ serial.Send("s"); Sleep(1000); serial.Send("c"); Sleep(50); serial.Send("e"); Sleep(1000); serial.Send("s"); } // blue is front part else if (slope1_f>slope2_f){ serial.Send("r"); } else if (slope1_f<slope2_f){ serial.Send("l"); } else if (slope1_f==slope2_f){ serial.Send("f"); } } else { if(dist3 < 70){ serial.Send("s"); Sleep(1000); serial.Send("d"); Sleep(500); serial.Send("s"); } if (slope1_b>slope2_b){ serial.Send("l"); } else if (slope1_b<slope2_b){ serial.Send("r"); } else if (slope1_b==slope2_b){ serial.Send("f"); } } cvLine(rimg, cvPoint(posX_r, posY_r), cvPoint(u, y), cvScalar(255,255,255), 2); cvLine(rimg, cvPoint(posX_b, posY_b), cvPoint(u, y), cvScalar(255,255,255), 2); cvShowImage("original",rimg); cvReleaseImage(&rimg); x=cvWaitKey(10); } serial.CloseSerial(); return 0; } <file_sep>/SerialPort.hpp #pragma once #include "windows.h" class CSerialPort { public: CSerialPort(void); ~CSerialPort(void); // prototypes void OpenSerial( void ); void Send(unsigned char* data ); void Send(char* data ); void CloseSerial( void ); protected: HANDLE SerialPort; int Error; unsigned long dwNumberOfBytesWritten; };
3563a391f6abc9a9e03763cadb8c1ccc112680ac
[ "C", "C++" ]
2
C
glyfina/OpenCV
4a231cd8feb297160e2605d2b6926b646fa5de78
ad1116987d6b9033d5fd94753ec094c5f8a12709
refs/heads/master
<repo_name>reconquest/monk<file_sep>/monk.go package main import ( "fmt" "net" "sync" "time" "github.com/reconquest/karma-go" ) const ( intervalPresence = time.Second * 2 ) type Monk struct { mutex *sync.Mutex machine string security *SecureLayer port int udp net.PacketConn dataDir string networks Networks peers Peers stream *Stream streamBufferSize int } func NewMonk( machineID string, security *SecureLayer, dataDir string, port int, streamBufferSize int, ) *Monk { monk := &Monk{ machine: machineID, security: security, mutex: &sync.Mutex{}, dataDir: dataDir, port: port, streamBufferSize: streamBufferSize, peers: Peers{ mutex: &sync.Mutex{}, }, stream: NewStream(streamBufferSize), } return monk } func (monk *Monk) Close() { monk.stream.Close() } func (monk *Monk) SetNetworks(networks []Network) { monk.mutex.Lock() defer monk.mutex.Unlock() same := func(a, b Network) bool { if a.Interface == b.Interface && a.BroadcastAddress.String() == b.BroadcastAddress.String() && a.IP.String() == b.IP.String() { return true } return false } toAdd := []Network{} for _, network := range networks { found := false for _, saved := range monk.networks { if same(saved, network) { found = true break } } if found { continue } toAdd = append(toAdd, network) logger.Infof( "network added: %s dev %s", network.BroadcastAddress, network.Interface, ) } for index := len(monk.networks) - 1; index > 0; index-- { saved := monk.networks[index] found := false for _, network := range networks { if same(saved, network) { found = true break } } if found { continue } monk.networks = append( monk.networks[:index], monk.networks[index+1:]..., ) logger.Infof( "network removed: %s dev %s", saved.BroadcastAddress, saved.Interface, ) } monk.networks = append(monk.networks, toAdd...) } func (monk *Monk) getPeer(id string) (*Peer, error) { var found *Peer peers := monk.peers.get() for i, _ := range peers { peer := peers[i] if peer.Machine == id { if found != nil { return nil, karma. Describe(found.IP, found.Fingerprint.String()). Describe(peer.IP, peer.Fingerprint.String()). Format( nil, "found two peers with the same machine id", ) } found = &peer } } if found == nil { return nil, fmt.Errorf("no such peer: %s", id) } return found, nil } <file_sep>/handle_client.go package main func handleClient(args map[string]interface{}) { var ( socketPath = args["--socket"].(string) ) client := NewClient("unix", socketPath) // corner case: fingerprint can be obtained without communication with // daemon if !args["fingerprint"].(bool) { err := client.Dial() if err != nil { fatalh( err, "unable to dial to %s, is monk daemon running?", socketPath, ) } } var err error switch { case args["peers"].(bool): err = handleClientQuery( client, args["--fingerprint"].(bool), ) case args["stream"].(bool): machine, _ := args["<machine>"].(string) err = handleClientStream( client, machine, ) case args["fingerprint"].(bool): err = handleClientFingerprint(args["--data-dir"].(string)) case args["trust"].(bool): err = handleClientTrust(client, args["<machine>"].(string)) default: panic("unexpected action") } if err != nil { fatalln(err) } } <file_sep>/peer.go package main import ( "bytes" "sync" "time" ) type Peer struct { IP string `json:"ip"` Trusted bool `json:"trusted"` Machine string `json:"machine"` Fingerprint Fingerprint `json:"fingerprint"` LastSeen time.Time `json:"last_seen"` Latency time.Duration `json:"latency"` data map[string]interface{} } type Peers struct { peers []Peer mutex *sync.Mutex } func (peer *Peer) String() string { return peer.Machine + " " + peer.IP + " " + peer.Fingerprint.String() } func (peers *Peers) add(peer Peer) { peers.mutex.Lock() defer peers.mutex.Unlock() peers.peers = append(peers.peers, peer) } func (peers *Peers) updateLastSeen( ip string, fingerprint Fingerprint, id string, latency time.Duration, ) bool { peers.mutex.Lock() defer peers.mutex.Unlock() for i, peer := range peers.peers { if peer.IP == ip && bytes.Compare(fingerprint, peer.Fingerprint) == 0 && peer.Machine == id { peers.peers[i].LastSeen = time.Now() peers.peers[i].Latency = latency return true } } return false } func (peers *Peers) remove(peer Peer) { peers.mutex.Lock() defer peers.mutex.Unlock() for index, known := range peers.peers { if peer.IP == known.IP && bytes.Compare(peer.Fingerprint, known.Fingerprint) == 0 && peer.Machine == known.Machine { peers.peers = append( peers.peers[:index], peers.peers[index+1:]..., ) break } } } func (peers *Peers) cleanup(timeout time.Duration) { peers.mutex.Lock() defer peers.mutex.Unlock() clean := []Peer{} for _, peer := range peers.peers { if time.Now().Sub(peer.LastSeen) > timeout { continue } clean = append(clean, peer) } peers.peers = clean } func (peers *Peers) len() int { peers.mutex.Lock() defer peers.mutex.Unlock() return len(peers.peers) } func (peers *Peers) get() []Peer { peers.mutex.Lock() defer peers.mutex.Unlock() data := make([]Peer, len(peers.peers)) copy(data, peers.peers) return data } <file_sep>/tls.go package main import ( "crypto/tls" "path/filepath" ) func getPeerCertificatePath(dataDir string, fingerprint Fingerprint) string { return filepath.Join(dataDir, DataDirTrusted, fingerprint.String()) } func getPeerTLS(peer Peer) (*tls.Config, error) { return nil, nil } <file_sep>/stream.go package main import ( "errors" "fmt" "io" "sync" "time" ) const ( StreamChunkSize = 32 * 1024 ) type StreamBuffer struct { conn *StreamConnection data []byte } type Stream struct { started bool startedMutex sync.Mutex conns []*StreamConnection connsMutex sync.Mutex buffer chan StreamBuffer maxBufferSize int transferCond sync.Cond } type StreamConnection struct { machine string pipe io.ReadWriteCloser once sync.Once onClose func() } func (conn *StreamConnection) Close() { conn.once.Do(func() { conn.pipe.Close() if conn.onClose != nil { conn.onClose() } }) } func NewStream(bufferSize int) *Stream { return &Stream{ buffer: make(chan StreamBuffer, bufferSize/StreamChunkSize), transferCond: sync.Cond{ L: &sync.Mutex{}, }, } } func (stream *Stream) write(conn *StreamConnection, data []byte) error { select { case stream.buffer <- StreamBuffer{conn, data}: return nil default: return errors.New("buffer is full") } } func (stream *Stream) Close() { close(stream.buffer) conns := []*StreamConnection{} stream.connsMutex.Lock() for _, conn := range stream.conns { conns = append(conns, conn) } stream.connsMutex.Unlock() for _, conn := range conns { conn.Close() } } func (stream *Stream) transfer() { for { item, ok := <-stream.buffer if !ok { return } stream.transferCond.L.Lock() for { if stream.broadcast(item.conn, item.data) { break } stream.transferCond.Wait() } stream.transferCond.L.Unlock() } } func (stream *Stream) Serve(machine string, pipe io.ReadWriteCloser) *sync.WaitGroup { stream.start() logger.Infof("stream: connected %s", machine) worker := &sync.WaitGroup{} worker.Add(1) conn := &StreamConnection{ machine: machine, pipe: pipe, } conn.onClose = func() { defer worker.Done() stream.removeConnection(conn) } stream.connsMutex.Lock() stream.conns = append(stream.conns, conn) stream.connsMutex.Unlock() go stream.read(conn) stream.transferCond.Signal() return worker } func (stream *Stream) start() { stream.startedMutex.Lock() defer stream.startedMutex.Unlock() if stream.started { return } stream.started = true go stream.transfer() } func (stream *Stream) removeConnection(conn *StreamConnection) { stream.connsMutex.Lock() for i, item := range stream.conns { if item == conn { stream.conns = append( stream.conns[:i], stream.conns[i+1:]..., ) logger.Infof("stream: disconnected %s", conn.machine) break } } stream.connsMutex.Unlock() } func (stream *Stream) broadcast(owner *StreamConnection, data []byte) bool { running := 0 stream.connsMutex.Lock() wrote := make(chan *StreamConnection, len(stream.conns)) for _, conn := range stream.conns { if conn == owner { continue } running++ go func(conn *StreamConnection) { _, err := conn.pipe.Write(data) if err != nil { errorh(err, "unable to write to stream: %s", conn.machine) conn.Close() } wrote <- conn }(conn) } stream.connsMutex.Unlock() if running == 0 { return false } after := time.After(time.Second * 5) done := map[*StreamConnection]struct{}{} waiting: for { select { case conn := <-wrote: done[conn] = struct{}{} running-- if running == 0 { break waiting } case <-after: break waiting } } var toClose []*StreamConnection var result bool stream.connsMutex.Lock() for _, conn := range stream.conns { if conn == owner { continue } _, ok := done[conn] if !ok { errorh( fmt.Errorf("deadline exceeded: %s", time.Second*5), "unable to write to stream: %s", conn.machine, ) toClose = append(toClose, conn) } else { result = true } } stream.connsMutex.Unlock() for _, conn := range toClose { conn.Close() } return result } func (stream *Stream) read( conn *StreamConnection, ) { defer conn.Close() buffer := make([]byte, StreamChunkSize) for { read, err := conn.pipe.Read(buffer) if err != nil { if err == io.EOF { break } errorh(err, "can't read stream of %s", conn.machine) break } clone := make([]byte, read) copy(clone, buffer[:read]) err = stream.write(conn, clone) if err != nil { errorh(err, "can't write message of %s to stream", conn.machine) } } } <file_sep>/pipe.go package main import ( "fmt" "net" "os" "path/filepath" "time" ) const F_SETPIPE_SZ = 1031 const F_GETPIPE_SZ = 1032 type Pipe struct { net.Conn listener net.Listener path string } func (pipe *Pipe) Close() error { if pipe.listener != nil { pipe.listener.Close() } if pipe.Conn != nil { pipe.Conn.Close() } os.Remove(pipe.path) return nil } func StartPipe(dir string) (*Pipe, error) { path := filepath.Join( dir, "stream", fmt.Sprintf("%d.pipe", time.Now().UnixNano()), ) listener, err := net.Listen("unix", path) if err != nil { return nil, err } return &Pipe{ listener: listener, path: path, }, nil } func (pipe *Pipe) WaitConnect() error { conn, err := pipe.listener.Accept() if err != nil { return err } pipe.Conn = conn return nil } func ConnectPipe(path string) (*Pipe, error) { conn, err := net.Dial("unix", path) if err != nil { return nil, err } return &Pipe{Conn: conn, path: path}, nil } <file_sep>/tcp.go package main import ( "encoding/json" "fmt" "io" "net" "github.com/reconquest/karma-go" ) type TCPPacketHandler func(*TCPConnection, Packet) (Packetable, error) type TCPConnectionHandler func(*TCPConnection) error type TCPConnection struct { conn net.Conn peer *Peer } type TCP struct { listener net.Listener security *SecureLayer handlePacket TCPPacketHandler handleConnection TCPConnectionHandler } func (server *TCP) Close() error { return server.listener.Close() } func initTCP( port int, security *SecureLayer, handlePacket TCPPacketHandler, handleConnection TCPConnectionHandler, ) (*TCP, error) { sock, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) if err != nil { return nil, err } return &TCP{ listener: sock, security: security, handleConnection: handleConnection, handlePacket: handlePacket, }, nil } func (server *TCP) Serve() { for { fd, err := server.listener.Accept() if err != nil { break } go server.serve(fd) } } func (server *TCP) serve(fd net.Conn) { defer fd.Close() decoder := json.NewDecoder(fd) encoder := json.NewEncoder(fd) writeError := func(err error) { logger.Error(err) packet := PacketError{} packet.Error = "internal server error" errEncode := encoder.Encode(makePacket(packet)) if errEncode != nil { errorh(errEncode, "tcp: unable to write query") } } conn := &TCPConnection{ conn: fd, } for { var query Packet err := decoder.Decode(&query) if err != nil { if err == io.EOF { return } writeError(karma.Format(err, "tcp: unable to read message")) break } reply, err := server.handlePacket(conn, query) if err != nil { writeError(karma.Format(err, "tcp: unable to serve packet")) break } if reply != nil { err = encoder.Encode(makePacket(reply)) if err != nil { writeError(karma.Format(err, "tcp: unable to write reply packet")) continue } if reply.Signature() == SignatureEncryptConnection { err := server.handleConnection(conn) if err != nil { logger.Error(err) } break } } } } <file_sep>/assert.go package main func assert(statement bool, message string) { if !statement { panic("assertion failure: " + message) } } <file_sep>/network.go package main import ( "encoding/binary" "net" "strings" "time" ) const ( intervalWatchNetworks = time.Second * 5 ) type Network struct { Interface string BroadcastAddress net.IP *net.IPNet } type Networks []Network func (networks Networks) Strings() []string { strings := []string{} for _, network := range networks { strings = append(strings, network.String()) } return strings } func (network Network) String() string { return network.IPNet.String() } func getBroadcastAddress(ipnet *net.IPNet) net.IP { ip4 := ipnet.IP.To4() mask4 := net.IP(ipnet.Mask).To4() ip := make(net.IP, len(ip4)) binary.BigEndian.PutUint32( ip, binary.BigEndian.Uint32(ip4)|^binary.BigEndian.Uint32(mask4), ) return ip } func watchNetworks(monk *Monk, allowedInterfaces []string) { for { time.Sleep(intervalWatchNetworks) networks := filterNetworks(getNetworks(), allowedInterfaces) monk.SetNetworks(networks) } } func filterNetworks(networks []Network, allowedInterfaces []string) []Network { filtered := []Network{} for _, network := range networks { if len(allowedInterfaces) == 0 { filtered = append(filtered, network) continue } for _, allowed := range allowedInterfaces { if strings.HasPrefix(network.Interface, allowed) { filtered = append(filtered, network) break } } } return filtered } func getNetworks() []Network { networks := []Network{} ifaces, _ := net.Interfaces() for _, iface := range ifaces { addresses, err := iface.Addrs() if err != nil { errorh( err, "unable to get addresses of interface: %s", iface.Name, ) continue } for _, address := range addresses { ipnet := address.(*net.IPNet) if ipnet.IP.IsLoopback() { continue } if ipnet.IP.To4() == nil { continue } networks = append( networks, Network{ Interface: iface.Name, BroadcastAddress: getBroadcastAddress(ipnet), IPNet: ipnet, }, ) } } return networks } func inSlice(slice []string, target string) bool { for _, item := range slice { if item == target { return true } } return false } <file_sep>/monk_handle_query_stream.go package main import ( "fmt" "github.com/reconquest/karma-go" ) var ( x = 0 ) func (monk *Monk) HandleQueryStream(query Packet) (Packetable, error) { var request PacketQueryStream err := query.Bind(&request) if err != nil { return nil, err } if request.ID == "" { return monk.handleNewStream() } else { return monk.handleConnectStream(request) } } func (monk *Monk) handleConnectStream(query PacketQueryStream) (Packetable, error) { peer, err := monk.getPeer(query.ID) if err != nil { return nil, err } address := fmt.Sprintf( "%s:%d", peer.IP, monk.port, ) client := NewClient("tcp", address) err = client.Dial() if err != nil { return nil, karma.Format( err, "unable dial connection to the peer: %s", address, ) } err = client.Encrypt(monk.machine, monk.security) if err != nil { return nil, karma.Format( err, "unable to establish tls with peer", ) } pipe, err := StartPipe(monk.dataDir) if err != nil { return nil, karma.Format( err, "unable to init pipe", ) } go func() { err := pipe.WaitConnect() if err != nil { client.Close() pipe.Close() errorh(err, "unable to accept pipe connection") return } communicate( pipe, client.secured, client.secured, pipe, ) }() return PacketStream{ Pipe: pipe.path, }, nil } func (monk *Monk) handleNewStream() (Packetable, error) { pipe, err := StartPipe(monk.dataDir) if err != nil { return nil, karma.Format( err, "unable to init pipe", ) } x++ go func() { err := pipe.WaitConnect() if err != nil { errorh(err, "unable to wait for pipe connection") return } monk.stream.Serve( monk.machine+"-"+fmt.Sprint(x), pipe, ) }() return PacketStream{ Pipe: pipe.path, }, nil } <file_sep>/packets.go package main import "time" const SignaturePresence = "presence" type PacketPresence struct { ID string `json:"id"` At time.Time `json:"at"` Fingerprint Fingerprint `json:"fingerprint"` } func (packet PacketPresence) Signature() string { return SignaturePresence } const SignatureError = "error" type PacketError struct { Error string `json:"error"` } func (packet PacketError) Signature() string { return "error" } const SignatureQueryPeers = "peers/query" type PacketQueryPeers struct { } func (packet PacketQueryPeers) Signature() string { return SignatureQueryPeers } const SignaturePeers = "peers" type PacketPeers []Peer func (packet PacketPeers) Signature() string { return SignaturePeers } const SignaturePeer = "peer" type PacketPeer struct{ *Peer } func (packet PacketPeer) Signature() string { return SignaturePeer } const SignatureTrustPeer = "peer/trust" type PacketTrustPeer struct { ID string `json:"id"` } func (packet PacketTrustPeer) Signature() string { return SignatureTrustPeer } const SignatureQueryCertificate = "certificate/query" type PacketQueryCertificate struct { } func (packet PacketQueryCertificate) Signature() string { return SignatureQueryCertificate } const SignatureCertificate = "certificate" type PacketCertificate struct { Data []byte `json:"data"` } func (packet PacketCertificate) Signature() string { return SignatureCertificate } const SignatureQueryStream = "stream/query" type PacketQueryStream struct { ID string `json:"id"` } func (packet PacketQueryStream) Signature() string { return SignatureQueryStream } const SignatureStream = "stream" type PacketStream struct { Pipe string `json:"pipe"` Buddy Peer `json:"buddy"` } func (packet PacketStream) Signature() string { return SignatureStream } const SignatureEncryptConnection = "connection/encrypt" type PacketEncryptConnection struct { ID string `json:"id"` Fingerprint Fingerprint `json:"fingerprint"` } func (packet PacketEncryptConnection) Signature() string { return SignatureEncryptConnection } <file_sep>/tests/cure.sh # requires setup.sh to be sourced first! cure_user="cure" :cure:with-key() { :cure \ -u $cure_user ${ips[*]/#/-o} -k "$(ssh-test:print-key-path)" "${@}" } :cure:with-password() { local password="$1" shift :expect() { expect -f <(cat) -- "${@}" </dev/tty } go-test:run :expect -u $cure_user ${ips[*]/#/-o} -p "${@}" <<EXPECT spawn -noecho cure {*}\$argv expect { Password: { send "$password\r" interact } eof { send_error "\$expect_out(buffer)" exit 1 } } EXPECT } :cure:with-key-passphrase() { local passphrase="$1" shift :expect() { expect -f <(cat) -- "${@}" </dev/tty } go-test:run :expect -u $cure_user ${ips[*]/#/-o} \ -k "$(ssh-test:print-key-path)" "${@}" <<EXPECT spawn -noecho cure {*}\$argv expect { "Key passphrase:" { send "$passphrase\r" interact } eof { send_error "\$expect_out(buffer)" exit 1 } } EXPECT } :cure() { tests:debug "!!! cure ${@}" go-test:run cure "${@}" } <file_sep>/main.go package main import ( "fmt" "os" "github.com/docopt/docopt-go" "github.com/kovetskiy/lorg" "github.com/reconquest/colorgful" ) var ( defaultSocketPath = fmt.Sprintf("/var/run/user/%d/monk.sock", os.Getuid()) ) var ( version = "[manual build]" usage = "monk " + version + os.ExpandEnv(` blah Usage: monk [options] [--interface <prefix>]... daemon monk [options] peers [-f] monk [options] trust <machine> monk [options] stream [<machine>] monk [options] fingerprint monk -h | --help monk --version Options: -s --socket <path> Listen and serve specified unix socket. Used for internal purposes only. [default: `+defaultSocketPath+`] -f --fingerprint Show peers' fingerprints. -p --port <port> Specify port [default: 12345]. -i --interface <prefix> Specify network interface to use. --data-dir <path> Directory with sensitive data. [default: $HOME/.config/monk/] --stream-buffer-size <bytes> Max buffer size for streaming. [default: 536870912] --debug Enable debug mode. -h --help Show this screen. --version Show version. `) ) var ( logger = lorg.NewLog() ) func main() { args, err := docopt.Parse(usage, nil, true, version, false) if err != nil { panic(err) } logger.SetFormat( colorgful.MustApplyDefaultTheme( "${time} ${level:%s:left} ${prefix}%s", colorgful.Default, ), ) logger.SetIndentLines(true) if args["--debug"].(bool) { logger.SetLevel(lorg.LevelDebug) } if args["daemon"].(bool) { handleDaemon(args) } else { handleClient(args) } } <file_sep>/packet.go package main import ( "encoding/json" "github.com/reconquest/karma-go" ) type PacketHandler func(Packet) (Packetable, error) type Packetable interface { Signature() string } type Packet struct { Signature string `json:"signature"` Payload json.RawMessage `json:"payload"` } func makePacket(data Packetable) interface{} { return struct { Signature string `json:"signature"` Payload interface{} `json:"payload"` }{data.Signature(), data} } func pack(data Packetable) []byte { encoded, err := json.Marshal(makePacket(data)) if err != nil { panic( karma.Format( err, "unable to encode packet: %s", data.Signature(), ), ) } return encoded } func unpack(data []byte) (Packet, error) { var packet Packet err := json.Unmarshal(data, &packet) if err != nil { return packet, karma.Format( err, "unable to decode packet", ) } return packet, nil } func (packet *Packet) Bind(data Packetable) error { err := json.Unmarshal(packet.Payload, data) if err != nil { return karma.Format( err, "unable to decode packet payload", ) } return nil } <file_sep>/monk_tcp.go package main import ( "crypto/tls" "crypto/x509" "fmt" "io/ioutil" "github.com/reconquest/karma-go" ) func (monk *Monk) HandleTCPPacket(conn *TCPConnection, query Packet) (Packetable, error) { logger.Debugf("socket: %s", query.Signature) switch query.Signature { case SignatureQueryCertificate: return monk.HandleQueryCertificate(query) case SignatureEncryptConnection: return monk.HandleEncryptConnection(conn, query) default: return nil, fmt.Errorf( "unexpected packet signature: %s", query.Signature, ) } } func (monk *Monk) HandleTCPConnection(conn *TCPConnection) error { if conn.peer == nil { return fmt.Errorf("conn.peer is nil") } certPath := getPeerCertificatePath(monk.dataDir, conn.peer.Fingerprint) certData, err := ioutil.ReadFile(certPath) if err != nil { return karma.Format( err, "unable to read certificate data of peer: %s", conn.peer.Machine, ) } pool := x509.NewCertPool() ok := pool.AppendCertsFromPEM(certData) if !ok { return fmt.Errorf( "unable to add client certificate to tls.Server pool: %s", conn.peer.Machine, ) } secured := tls.Server( conn.conn, &tls.Config{ Certificates: []tls.Certificate{monk.security.X509KeyPair}, ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: pool, }, ) worker := monk.stream.Serve(conn.peer.Machine, secured) worker.Wait() return nil } <file_sep>/nspawn #!/bin/bash :sudo() { echo "!! sudo: ${@}" sudo "${@}" } BRIDGE=nspawn${RANDOM} trap "{ sudo ip link set $BRIDGE down; sudo brctl delbr ${BRIDGE}; }" EXIT :sudo brctl addbr ${BRIDGE} :sudo ip link set $BRIDGE up :sudo ip addr add 169.254.0.$((RANDOM%255))/16 dev ${BRIDGE} dir=$(readlink -f .) bin=$dir/monk :sudo systemd-nspawn \ --bind "$(readlink -f . )" \ --quiet \ -D ~/container \ --network-bridge=${BRIDGE} -n \ -b <file_sep>/monk_handle_encrypt_connection.go package main func (monk *Monk) HandleEncryptConnection(conn *TCPConnection, query Packet) (Packetable, error) { var request PacketEncryptConnection err := query.Bind(&request) if err != nil { return nil, err } peer, err := monk.getPeer(request.ID) if err != nil { return PacketError{ "unknown peer", }, nil } if !monk.isTrustedPeer(peer.Fingerprint) { return PacketError{ "untrusted peer", }, nil } conn.peer = peer return PacketEncryptConnection{}, nil } <file_sep>/id.go package main import ( "io/ioutil" "math/rand" "strings" "time" "github.com/reconquest/karma-go" ) func init() { rand.Seed(time.Now().UnixNano()) } func getMachineID() (string, error) { contents, err := ioutil.ReadFile("/etc/machine-id") if err != nil { return "", karma.Format( err, "unable to read machine-id", ) } return strings.TrimSpace(string(contents)), nil } <file_sep>/security.go package main import ( "bytes" "crypto/rand" "crypto/rsa" "crypto/sha1" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/hex" "encoding/pem" "io/ioutil" "math/big" "os" "path/filepath" "strings" "time" "github.com/reconquest/karma-go" ) const ( secureLayerCertificatePath = "tls/cert.pem" secureLayerKeyPath = "tls/key.pem" ) type SecureLayer struct { Certificate *x509.Certificate CertificatePEM []byte CertificatePath string Key *rsa.PrivateKey KeyPath string Fingerprint Fingerprint X509KeyPair tls.Certificate } type Fingerprint []byte func (fingerprint Fingerprint) String() string { buffer := bytes.NewBuffer(nil) for i, _ := range fingerprint { if i != 0 { buffer.WriteRune(':') } chunk := fingerprint[i : i+1] buffer.WriteString( strings.ToUpper(hex.EncodeToString(chunk)), ) } return buffer.String() } func getSecureLayer(dataDir string, withKey bool) (*SecureLayer, error) { layer := SecureLayer{} layer.CertificatePath = filepath.Join(dataDir, secureLayerCertificatePath) layer.KeyPath = filepath.Join(dataDir, secureLayerKeyPath) found := true for _, path := range []string{ layer.CertificatePath, layer.KeyPath, } { _, err := os.Stat(path) if err != nil && !os.IsNotExist(err) { return nil, err } if os.IsNotExist(err) { found = false break } } if !found { logger.Infof("generating TLS certificate") // 10 years invalidAfter := time.Now().AddDate(10, 0, 0) err := generateCertificate(dataDir, 4096, invalidAfter) if err != nil { return nil, karma.Format( err, "unable to generate TLS key-cert pair", ) } } certPEM, err := ioutil.ReadFile(layer.CertificatePath) if err != nil { return nil, karma.Format( err, "unable to read certificate file: %s", layer.CertificatePath, ) } layer.CertificatePEM = certPEM keyPEM, err := ioutil.ReadFile(layer.KeyPath) if err != nil { return nil, karma.Format( err, "unable to read key file: %s", layer.KeyPath, ) } certBlock, _ := pem.Decode([]byte(certPEM)) if certBlock == nil { return nil, karma.Format( err, "unable to decode certificate PEM data", ) } keyBlock, _ := pem.Decode([]byte(keyPEM)) if keyBlock == nil { return nil, karma.Format( err, "unable to decode key PEM data", ) } layer.X509KeyPair, err = tls.X509KeyPair(certPEM, keyPEM) if err != nil { return nil, karma.Format( err, "unable to parse X509 key pair", ) } layer.Certificate, err = x509.ParseCertificate(certBlock.Bytes) if err != nil { return nil, karma.Format( err, "unable to parse certificate PEM block", ) } layer.Key, err = x509.ParsePKCS1PrivateKey(keyBlock.Bytes) if err != nil { return nil, karma.Format( err, "unable to parse certificate PEM block", ) } layer.Fingerprint = getFingerprint(layer.Certificate) return &layer, nil } func getFingerprint(cert *x509.Certificate) Fingerprint { hasher := sha1.New() hasher.Write(cert.Raw) return Fingerprint(hasher.Sum(nil)) } func generateCertificate( certDir string, blockSize int, invalidAfter time.Time, ) error { privateKey, err := rsa.GenerateKey(rand.Reader, blockSize) if err != nil { return karma.Format( err, "unable to generate RSA key", ) } invalidBefore := time.Now() serialNumberBlockSize := big.NewInt(0).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberBlockSize) if err != nil { return karma.Format(err, "failed to generate serial number") } cert := x509.Certificate{ IsCA: true, SerialNumber: serialNumber, NotBefore: invalidBefore, NotAfter: invalidAfter, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{ x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth, }, Subject: pkix.Name{CommonName: "monk"}, } certData, err := x509.CreateCertificate( rand.Reader, &cert, &cert, &privateKey.PublicKey, privateKey, ) if err != nil { return karma.Format( err, "can't create certificate", ) } certOutFd, err := os.Create(filepath.Join(certDir, secureLayerCertificatePath)) if err != nil { return karma.Format( err, "can't create certificate file", ) } err = pem.Encode( certOutFd, &pem.Block{ Type: "CERTIFICATE", Bytes: certData, }, ) if err != nil { return karma.Format( err, "can't write PEM data to certificate file", ) } err = certOutFd.Close() if err != nil { return karma.Format( err, "can't close certificate file", ) } keyOutFd, err := os.OpenFile( filepath.Join(certDir, secureLayerKeyPath), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600, ) if err != nil { return karma.Format( err, "can't open key file", ) } err = pem.Encode( keyOutFd, &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey), }, ) if err != nil { return karma.Format( err, "can't write PEM data to key file", ) } err = keyOutFd.Close() if err != nil { return karma.Format( err, "can't close key file", ) } return nil } <file_sep>/socket.go package main import ( "encoding/json" "io" "net" "os" "github.com/reconquest/karma-go" ) type Socket struct { path string listener net.Listener handler PacketHandler } func (socket *Socket) Close() error { return socket.listener.Close() } func initSocket(path string, handler PacketHandler) (*Socket, error) { sock, err := net.Listen("unix", path) if err != nil { return nil, err } return &Socket{ path: path, listener: sock, handler: handler, }, nil } func (socket *Socket) Serve() { defer os.Remove(socket.path) for { fd, err := socket.listener.Accept() if err != nil { break } go socket.serve(fd) } } func (socket *Socket) serve(fd net.Conn) { defer fd.Close() decoder := json.NewDecoder(fd) encoder := json.NewEncoder(fd) writeError := func(err error) { logger.Error(err) packet := PacketError{} packet.Error = err.Error() errEncode := encoder.Encode(makePacket(packet)) if errEncode != nil { errorh(errEncode, "sock: unable to write query") } } for { var query Packet err := decoder.Decode(&query) if err != nil { if err == io.EOF { return } writeError(karma.Format(err, "sock: unable to read message")) break } reply, err := socket.handler(query) if err != nil { writeError(karma.Format(err, "sock: unable to serve packet")) break } if reply == nil { panic("handler returned packet with empty signature") } err = encoder.Encode(makePacket(reply)) if err != nil { writeError(karma.Format(err, "sock: unable to write reply packet")) } } } <file_sep>/monk_udp.go package main import ( "bytes" "net" "time" ) func (monk *Monk) bind() error { udp, err := net.ListenUDP("udp", &net.UDPAddr{Port: monk.port}) if err != nil { return err } logger.Infof("listening at :%d", monk.port) monk.udp = udp return nil } func (monk *Monk) observe() { for { remote, packet, err := monk.readBroadcast() if err != nil { errorh(err, "unable to read packet") continue } go monk.handle(remote.(*net.UDPAddr), packet) } } func (monk *Monk) getNetworks() []Network { monk.mutex.Lock() defer monk.mutex.Unlock() networks := make([]Network, len(monk.networks)) copy(networks, monk.networks) return networks } func (monk *Monk) broadcastPresence() { packet := PacketPresence{ ID: monk.machine, Fingerprint: monk.security.Fingerprint, } for { networks := monk.getNetworks() for _, network := range networks { packet.At = time.Now() monk.broadcast(network, packet) } time.Sleep(intervalPresence) } } func (monk *Monk) readBroadcast() (net.Addr, []byte, error) { packet := make([]byte, 1024*4) size, remote, err := monk.udp.ReadFrom(packet) if err != nil { return nil, nil, err } return remote, packet[:size], nil } func (monk *Monk) handle(remote *net.UDPAddr, data []byte) { myIP := false for _, network := range monk.networks { if bytes.Compare(remote.IP, network.IP) == 0 { myIP = true break } } packet, err := unpack(data) if err != nil { errorh( err, "unable to unpack packet: %s", data, ) return } var presence PacketPresence err = packet.Bind(&presence) if err != nil { errorh(err, "unable to bind packet: %s", packet.Signature) return } if myIP && presence.ID == monk.machine { return } var latency time.Duration if presence.At.IsZero() { latency = time.Duration(0) } else { latency = time.Since(presence.At) } updated := monk.peers.updateLastSeen( remote.IP.String(), presence.Fingerprint, presence.ID, latency, ) if updated { logger.Debugf( "presence: %s %s %s %v", presence.ID, remote.IP, presence.Fingerprint, latency, ) } else { peer := Peer{ IP: remote.IP.String(), Machine: presence.ID, Fingerprint: presence.Fingerprint, LastSeen: time.Now(), Latency: latency, } monk.peers.add(peer) logger.Infof( "new monk: %s %s %s %v", presence.ID, remote.IP.String(), presence.Fingerprint, latency, ) } return } func (monk *Monk) broadcast(network Network, data Packetable) { debugf( "broadcasting to %s:%d dev %s", network.BroadcastAddress, monk.port, network.Interface, ) _, err := monk.udp.WriteTo( pack(data), &net.UDPAddr{IP: network.BroadcastAddress, Port: monk.port}, ) if err != nil { errorh( err, "unable to send packet to %s:%d dev %s", network.BroadcastAddress, monk.port, network.Interface, ) return } } <file_sep>/monk_handle_query_peers.go package main import ( "os" ) func (monk *Monk) HandleQueryPeers(query Packet) (Packetable, error) { peers := monk.peers.get() for i, peer := range peers { if monk.isTrustedPeer(peer.Fingerprint) { peers[i].Trusted = true } } return PacketPeers(peers), nil } func (monk *Monk) isTrustedPeer(fingerprint Fingerprint) bool { _, err := os.Stat( getPeerCertificatePath(monk.dataDir, fingerprint), ) return !os.IsNotExist(err) } <file_sep>/monk_handle_query_certificate.go package main func (monk *Monk) HandleQueryCertificate(Packet) (Packetable, error) { return PacketCertificate{ Data: monk.security.CertificatePEM, }, nil } <file_sep>/handle_client_stream.go package main import ( "io" "os" "github.com/reconquest/karma-go" ) func handleClientStream( client *Client, machine string, ) error { var stream PacketStream err := client.Query(PacketQueryStream{ID: machine}, &stream) if err != nil { return karma.Format( err, "unable to start chat", ) } pipe, err := ConnectPipe(stream.Pipe) if err != nil { return karma.Format( err, "unable to connect to %s", stream.Pipe, ) } communicate( pipe, os.Stdout, os.Stdin, pipe, ) return nil } func communicate( outputFrom io.ReadCloser, outputTo io.WriteCloser, inputFrom io.ReadCloser, inputTo io.WriteCloser, ) { close := func() { outputFrom.Close() outputTo.Close() inputFrom.Close() inputTo.Close() } closed := false withWait( func() { _, err := io.Copy(outputTo, outputFrom) if err != nil { if closed { return } errorh(err, "unable to io/copy to output from pipe") } closed = true close() }, func() { _, err := io.Copy(inputTo, inputFrom) if err != nil { errorh(err, "unable to io/copy from input to pipe") } closed = true close() }, ) } <file_sep>/data.go package main import ( "os" "path/filepath" ) const ( DataDirStream = "stream" DataDirTrusted = "trusted" DataDirTLS = "tls" ) func ensureDataDir(base string) error { dirs := []string{ DataDirStream, DataDirTrusted, DataDirTLS, } for _, dir := range dirs { fullDir := filepath.Join(base, dir) if _, err := os.Stat(fullDir); os.IsNotExist(err) { err = os.MkdirAll(fullDir, 0700) if err != nil { return err } } } return nil } <file_sep>/handle_daemon.go package main import ( "os" "strconv" "sync" "syscall" "github.com/reconquest/sign-go" ) func handleDaemon(args map[string]interface{}) { var ( port, _ = strconv.Atoi(args["--port"].(string)) allowedInterfaces = args["--interface"].([]string) socketPath = args["--socket"].(string) dataDir = args["--data-dir"].(string) ) err := ensureDataDir(dataDir) if err != nil { fatalh(err, "unable to ensure data dir") } security, err := getSecureLayer(dataDir, true) if err != nil { fatalh(err, "unable to ensure TLS certificate exists") } machineID, err := getMachineID() if err != nil { fatalh(err, "unable to get machine id") } monk := NewMonk( machineID, security, dataDir, port, argInt(args, "--stream-buffer-size"), ) err = monk.bind() if err != nil { fatalln(err) } socket, err := initSocket(socketPath, monk.HandleSock) if err != nil { fatalh( err, "unable to initialize unix sock: %s", socketPath, ) } tcp, err := initTCP( port, security, monk.HandleTCPPacket, monk.HandleTCPConnection, ) if err != nil { fatalh(err, "unable to initialize tcp at: %s", port) } monk.SetNetworks( filterNetworks( getNetworks(), allowedInterfaces, ), ) go watchNetworks(monk, allowedInterfaces) go monk.broadcastPresence() go monk.observe() go sign.Notify(func(os.Signal) bool { err := socket.Close() if err != nil { errorh(err, "unable to gracefully stop listening unix socket") } err = tcp.Close() if err != nil { errorh(err, "unable to gracefully stop listening tcp") } monk.Close() return false }, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM) withWait(socket.Serve, tcp.Serve) } func withWait(fns ...func()) { workers := &sync.WaitGroup{} for _, fn := range fns { workers.Add(1) go func(fn func()) { defer workers.Done() fn() }(fn) } workers.Wait() } <file_sep>/monk_socket.go package main import ( "fmt" ) func (monk *Monk) HandleSock(query Packet) (Packetable, error) { logger.Debugf("socket: %s", query.Signature) switch query.Signature { case SignatureQueryPeers: return monk.HandleQueryPeers(query) case SignatureTrustPeer: return monk.HandleTrustPeer(query) case SignatureQueryStream: return monk.HandleQueryStream(query) default: return nil, fmt.Errorf( "unexpected packet signature: %s", query.Signature, ) } } <file_sep>/handle_client_trust.go package main import ( "fmt" ) func handleClientTrust(client *Client, id string) error { var peer PacketPeer err := client.Query(PacketTrustPeer{ID: id}, &peer) if err != nil { return err } fmt.Printf( "Monk %s %s (%s) is trusted now.\n", peer.Machine, peer.Fingerprint, peer.IP, ) return nil } <file_sep>/monk_handle_trust_peer.go package main import ( "bytes" "crypto/x509" "encoding/pem" "fmt" "io/ioutil" "github.com/reconquest/karma-go" ) func (monk *Monk) HandleTrustPeer(query Packet) (Packetable, error) { var toTrust PacketTrustPeer err := query.Bind(&toTrust) if err != nil { return nil, err } peer, err := monk.getPeer(toTrust.ID) if err != nil { return nil, err } address := fmt.Sprintf("%s:%d", peer.IP, monk.port) client := NewClient("tcp", address) err = client.Dial() if err != nil { return nil, karma.Format( err, "unable dial connection to the peer: %s", address, ) } defer client.Close() var certPEM PacketCertificate err = client.Query(PacketQueryCertificate{}, &certPEM) if err != nil { return nil, err } certBlock, _ := pem.Decode(certPEM.Data) if certBlock == nil { return nil, karma.Format( err, "unable to decode peer's certificate PEM data", ) } cert, err := x509.ParseCertificate(certBlock.Bytes) if err != nil { return nil, karma.Format( err, "unable to parse certificate PEM block", ) } fingerprint := getFingerprint(cert) if bytes.Compare(fingerprint, peer.Fingerprint) != 0 { return nil, karma. Describe("known", peer.Fingerprint.String()). Describe("got", fingerprint.String()). Format( err, "the peer provided certificate with different fingerprint", ) } err = ioutil.WriteFile( getPeerCertificatePath(monk.dataDir, fingerprint), certPEM.Data, 0600, ) if err != nil { return nil, karma.Format( err, "unable to save certificate PEM block in data dir", ) } return PacketPeer{peer}, nil } <file_sep>/client.go package main import ( "crypto/tls" "encoding/json" "net" "sync" "github.com/reconquest/karma-go" ) type Client struct { network string address string conn net.Conn encoder *json.Encoder decoder *json.Decoder secured net.Conn sync.Mutex } func NewClient(network, address string) *Client { client := &Client{} client.network = network client.address = address return client } func (client *Client) Close() error { return client.conn.Close() } func (client *Client) Dial() error { conn, err := net.Dial(client.network, client.address) if err != nil { return err } client.Lock() client.conn = conn client.decoder = json.NewDecoder(conn) client.encoder = json.NewEncoder(conn) client.Unlock() return nil } func (client *Client) Query(query Packetable, reply Packetable) error { err := client.encoder.Encode(makePacket(query)) if err != nil { return karma.Format( err, "unable to write packet", ) } var raw Packet err = client.decoder.Decode(&raw) if err != nil { return karma.Format( err, "unable to read daemon reply", ) } if raw.Signature == SignatureError { var replyErr PacketError err := raw.Bind(&replyErr) if err != nil { return karma.Format( err, "packet signature is error, but can't bind to error struct", ) } return karma.Format( replyErr.Error, "the daemon returned an error", ) } err = raw.Bind(reply) if err != nil { return karma.Format( err, "unable to bind reply as %s", reply.Signature(), ) } return nil } func (client *Client) Encrypt(id string, security *SecureLayer) error { var response PacketEncryptConnection err := client.Query(PacketEncryptConnection{ ID: id, Fingerprint: security.Fingerprint, }, &response) if err != nil { return karma.Format( err, "unable to query for encryption", ) } secured := tls.Client(client.conn, &tls.Config{ Certificates: []tls.Certificate{security.X509KeyPair}, InsecureSkipVerify: true, }) infof("stream: establishing tls encryption with %s", id) err = secured.Handshake() if err != nil { return karma.Format( err, "unable to complete handshake with remote server", ) } infof("stream: handshake completed with %s", id) client.secured = secured client.encoder = json.NewEncoder(secured) client.decoder = json.NewDecoder(secured) return nil } <file_sep>/handle_client_query.go package main import ( "fmt" "os" "text/tabwriter" ) func handleClientQuery(client *Client, withFingerprint bool) error { var peers PacketPeers err := client.Query(PacketQueryPeers{}, &peers) if err != nil { return err } formatting := "%s\t%s\t%s\t%s\n" if withFingerprint { formatting = "%s\t%s\t%s\t%s\t%s\n" } writer := tabwriter.NewWriter(os.Stdout, 0, 1, 2, ' ', 0) for _, peer := range peers { values := []interface{}{ peer.Machine, peer.IP, peer.Latency, } if withFingerprint { values = append(values, peer.Fingerprint) } lastSeen := peer.LastSeen.Format("2006-01-02T15:04:05") if peer.Trusted { lastSeen += " [trusted]" } values = append(values, lastSeen) fmt.Fprintf(writer, formatting, values...) } err = writer.Flush() if err != nil { return err } return nil } <file_sep>/utils.go package main import ( "fmt" "strconv" ) func argInt(args map[string]interface{}, flag string) int { defer func() { tears := recover() if tears != nil { panic(fmt.Sprintf("invalid docopt for %s", flag)) } }() number, err := strconv.Atoi(args[flag].(string)) if err != nil { fatalh(err, "unable to parse %s value as integer", flag) } return number } <file_sep>/handle_client_fingerprint.go package main import ( "fmt" "github.com/reconquest/karma-go" ) func handleClientFingerprint(dataDir string) error { err := ensureDataDir(dataDir) if err != nil { return karma.Format( err, "unable to ensure data dir exists", ) } security, err := getSecureLayer(dataDir, false) if err != nil { return err } fmt.Println(security.Fingerprint.String()) return nil }
96dc5e38688aa6df2e83df458c018f178c2094ab
[ "Go", "Shell" ]
33
Go
reconquest/monk
c8c9e4abbdfe01d3adfb90f22e47463d49c61d28
93aee2993264409e1b963c101f16cbf32ad5404c
refs/heads/master
<file_sep># andevlib android develop library <file_sep>package com.android.andevlib.view.fragment; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.android.andevlib.app.util.Logger; import de.greenrobot.event.EventBus; /** * fragment基类<br/> * <ul> * fragment生命周期: * <li>onAttach->onCreate->onCreateView->onActivityCreated->onStart->onResume</li> * <li>onPause->onStop->onDestoryView->onDestory->onDetach</li> * </ul> * * @author willchyis * */ public abstract class TFragment extends Fragment { private static final String TAG = TFragment.class.getSimpleName(); public Context mContext; /** 是否需要注册EventBus */ private boolean mNeedEventBus = false; @Override public void onAttach(Activity activity) { super.onAttach(activity); Logger.i(TAG, "onAttach"); mContext = activity; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Logger.i(TAG, "onCreate"); onInit(); if (mNeedEventBus) { EventBus.getDefault().register(this); } } protected abstract void onInit(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Logger.i(TAG, "onCreateView"); if (getUserVisibleHint()) {// fragment可见则显示视图 showView(); } return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Logger.i(TAG, "onActivityCreated"); } @Override public void onStart() { super.onStart(); Logger.i(TAG, "onStart"); } @Override public void onResume() { super.onResume(); Logger.i(TAG, "onResume"); } @Override public void onPause() { super.onPause(); Logger.i(TAG, "onPause"); } @Override public void onStop() { super.onStop(); Logger.i(TAG, "onStop"); if (mNeedEventBus) { EventBus.getDefault().unregister(this); } } @Override public void onDestroyView() { super.onDestroyView(); Logger.i(TAG, "onDestroyView"); } /** * 摧毁该Fragment,一般是FragmentActivity被摧毁的时候伴随着摧毁 */ @Override public void onDestroy() { super.onDestroy(); Logger.i(TAG, "onDestroy"); } @Override public void onDetach() { super.onDetach(); Logger.i(TAG, "onDetach"); } public void onBackPressed() { Logger.i(TAG, "onBackPressed"); if (mNeedEventBus) { EventBus.getDefault().register(this); } } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); Logger.i(TAG, "setUserVisibleHint:" + isVisibleToUser); if (isVisibleToUser) {// fragment可见时加载数据 showView(); } } public abstract void showView(); public void setNeedEventBus(boolean mNeedEventBus) { this.mNeedEventBus = mNeedEventBus; } } <file_sep>package com.android.andevlib.app.util; import java.util.ArrayList; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import com.android.andevlib.R; import com.android.andevlib.controller.util.JudgeMultiMediaType; /** * 系统分享 */ public final class SystemShareUtil { /** * 系统分享 */ private static void shareSystem(Context context, String content, ArrayList<Uri> imageUris, String pkg, String cls) { Intent share = new Intent(); if (imageUris != null && !imageUris.isEmpty()) { boolean isVideo = false; if (imageUris.size() == 1) { Uri uri = imageUris.get(0); if (new JudgeMultiMediaType().isVideoFile(uri.getPath())) { isVideo = true; share.setAction(Intent.ACTION_SEND); share.setType("video/*"); share.putExtra(Intent.EXTRA_STREAM, uri); } } if (!isVideo) { share.setAction(Intent.ACTION_SEND_MULTIPLE); share.setType("image/*"); share.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris); } } share.setComponent(new ComponentName(pkg, cls)); // share.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(Intent.createChooser(share, context.getString(R.string.title_share))); } public final static String PKG_WX = "com.tencent.mm"; public final static String PKG_SINA = "com.sina.weibo"; public final static String PKG_QQ = "com.tencent.mobileqq"; public final static String PKG_QZONE = "com.qzone"; public final static String PKG_FB = "com.facebook.katana"; /** * 朋友圈 */ public static boolean shareImagesToTimeLine(Context context, ArrayList<Uri> imageUris) { if (AppUtil.isAppInstalled(PKG_WX)) { shareSystem(context, null, imageUris, PKG_WX, "com.tencent.mm.ui.tools.ShareToTimeLineUI"); return true; } return false; } public static boolean shareImagesToWx(Context context, ArrayList<Uri> imageUris) { if (AppUtil.isAppInstalled(PKG_WX)) { shareSystem(context, null, imageUris, PKG_WX, "com.tencent.mm.ui.tools.ShareImgUI"); return true; } return false; } public static boolean shareImagesToSina(Context context, ArrayList<Uri> imageUris) { if (AppUtil.isAppInstalled(PKG_SINA)) { shareSystem(context, null, imageUris, PKG_SINA, "com.sina.weibo.ComposerDispatchActivity"); return true; } return false; } public static boolean shareImagesToQq(Context context, ArrayList<Uri> imageUris) { if (AppUtil.isAppInstalled(PKG_QQ)) { shareSystem(context, null, imageUris, PKG_QQ, "com.tencent.mobileqq.activity.JumpActivity"); return true; } return false; } public static boolean shareImagesToQzone(Context context, ArrayList<Uri> imageUris) { if (AppUtil.isAppInstalled(PKG_QZONE)) { shareSystem(context, null, imageUris, PKG_QZONE, "com.qzonex.module.operation.ui.QZonePublishMoodActivity"); return true; } return false; } public static boolean shareImagesToFb(Context context, ArrayList<Uri> imageUris) { if (AppUtil.isAppInstalled(PKG_QZONE)) { shareSystem(context, null, imageUris, PKG_FB, "com.facebook.composer.shareintent.ImplicitShareIntentHandler"); return true; } return false; } } <file_sep>package com.android.andevlib.model.listener; import com.android.andevlib.model.event.TEvent; public interface OnUpdateViewListener { /** * 更新视图 */ public void onUpdateView(TEvent event); }
258bcd24059638decae9486cc46ca26e807fa721
[ "Markdown", "Java" ]
4
Markdown
willchyis/andevlib
cf5101322fc4a3b45fff49bcf07f32287ef172f7
8e1b34d949fd819c477c9c71f4723f8e99afa9a1
refs/heads/master
<file_sep># dotfiles My dotfiles, usually for ubuntu Filenames do not have the leading dot. <file_sep># Use the default ~/.bashrc but with # Modifications: Uncomment the force_color_prompt=yes line # Additions: # git clone https://github.com/magicmonty/bash-git-prompt ~/.bash-git-prompt GIT_PROMPT_ONLY_IN_REPO=1 source ~/.bash-git-prompt/gitprompt.sh export PIP_REQUIRE_VIRTUALENV=true
db979bdf32e172cdfd9405243161b773504035ce
[ "Markdown", "Shell" ]
2
Markdown
matthewbeckler/dotfiles
facaf73a693c8461f41a2b35625626f497485d9b
0700ef0f141c03e2ef51034d4065a9f870595f8e
refs/heads/master
<file_sep>import { API_CONFIG } from "./../../config/api.config"; import { StorageService } from "./../../services/storage.service"; import { Component, NgZone } from "@angular/core"; import { IonicPage, NavController, NavParams, Events, PopoverController, Platform } from "ionic-angular"; import { UsuarioService } from "../../services/domain/usuario.service"; import { CameraOptions, Camera } from "@ionic-native/camera"; import { NotificacoesService } from "../../services/domain/notificacoes.service"; import { DomSanitizer } from "@angular/platform-browser"; import { PhotoViewer, PhotoViewerOptions } from "../../../node_modules/@ionic-native/photo-viewer"; import { PopoverMeuPerfilPage } from "../../popovers/popover-meu-perfil/popover-meu-perfil"; @IonicPage() @Component({ selector: "page-meu-perfil", templateUrl: "meu-perfil.html" }) export class MeuPerfilPage { paciente; picture: string; apertouOpcaoFoto = false; tocouFoto = false; carregou = false; constructor( public navCtrl: NavController, public usuarioService: UsuarioService, public storageService: StorageService, public camera: Camera, public sanitazer: DomSanitizer, public events: Events, public notificacoesService: NotificacoesService, public popoverCtrl: PopoverController, public platform: Platform, private zone: NgZone ) { platform.ready().then(() => { this.events.subscribe("foto:meu-perfil", picture => { this.paciente.profileImage = picture }); }); } ionViewDidLoad() { this.findPessoaByPessoaCpf(); } findPessoaByPessoaCpf() { return this.usuarioService .findPacienteByPessoaCpf() .then(paciente => { this.paciente = paciente; this.pegarFotoUser() this.carregou = true; }) .catch(() => { this.carregou = true; }); } presentPopover(myEvent) { let popover = this.popoverCtrl.create(PopoverMeuPerfilPage,{navCtrl:this.navCtrl}); popover.present({ ev: myEvent }); } viewFoto() { if(this.paciente.profileImage.changingThisBreaksApplicationSecurity !=undefined){ const photoViewer = new PhotoViewer(); let options: PhotoViewerOptions = { share: true // default is false }; photoViewer.show( `${API_CONFIG.bucketBaseUrl}/${ this.storageService.getUser().pessoa.urlFoto }`, "Minha Foto de Perfil", options ); } } pegarFotoUser(){ if(this.storageService.getUser().imageDataUrl != undefined) { this.paciente.profileImage = this.sanitazer.bypassSecurityTrustUrl( this.storageService.getUser().imageDataUrl) }else{ this.paciente.profileImage = "assets/imgs/avatar-blank.png" } } doRefresh(refresher){ this.findPessoaByPessoaCpf().then(()=>{ refresher.complete(); }); } } <file_sep>import { AlertController } from 'ionic-angular/components/alert/alert-controller'; import { MedicamentoService } from './../../services/domain/medicamento.service'; import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, Alert, PopoverController } from 'ionic-angular'; import { NotificacoesService } from '../../services/domain/notificacoes.service'; import { PopoverDefaultPage } from '../../popovers/popover-default/popover-default'; @IonicPage() @Component({ selector: 'page-medicamento', templateUrl: 'medicamento.html', }) export class MedicamentoPage { medicamentos; constructor( public navCtrl: NavController, public navParams: NavParams, public service:MedicamentoService, public alertCtrl:AlertController, public notificaoesService:NotificacoesService, public popoverCtrl: PopoverController) { } ionViewDidLoad() { this.obterMedicamentosAtivos() } obterMedicamentosAtivos(){ this.service.findMedicamentosAtivosByPacienteId() .then(res=>{ this.medicamentos = res; }) } atualizar(medicamento){ this.navCtrl.push('FormMedicamentoPage',{medicamento:medicamento}) } setInativo(medicamento){ this.service.setInativo(medicamento.id) .then(res=>{ this.obterMedicamentosAtivos(); this.notificaoesService.presentToast('Medicamento mandado para a lista de histórico','default',4000,'middle') }) } presentPopover(myEvent,item) { const popover = this.popoverCtrl.create(PopoverDefaultPage,{page:this,item:item}); popover.present({ ev: myEvent }); } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { FormExamePage } from './form-exame'; @NgModule({ declarations: [ FormExamePage, ], imports: [ IonicPageModule.forChild(FormExamePage), ], }) export class FormExamePageModule {} <file_sep>import { Component, ViewChild } from '@angular/core'; import { NavController, IonicPage, Events, Slides } from 'ionic-angular'; import { StorageService } from '../../services/storage.service'; import { MedicamentoService } from '../../services/domain/medicamento.service'; @IonicPage() @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { @ViewChild(Slides) slides: Slides; carregou: boolean; medicamentos; dataAtual = new Date() constructor( public navCtrl: NavController, public storageService: StorageService, public medicamentoService: MedicamentoService ) { } ionViewDidLoad() { console.log(this.dataAtual.getDate()) this.obterMedicamentosAtivos() } handleSlide() { if (this.slides.isBeginning()) { this.slides.lockSwipeToPrev(true); } else { this.slides.lockSwipeToPrev(false); } if (this.slides.isEnd()) { this.slides.lockSwipeToNext(true); } else { this.slides.lockSwipeToNext(false); } } obterMedicamentosAtivos() { this.medicamentoService.findMedicamentosAtivosByPacienteId() .then(medicamentos => { this.calcularHoraProximoMedicamento(medicamentos) }) } // Método que calcula o horário da dosagem mais próximo calcularHoraProximoMedicamento(medicamentos) { medicamentos.forEach(medicamento => { const horasRemedio: Date[] = [] const data = new Date() data.setHours(medicamento.horaInicial.substr(0, 2), medicamento.horaInicial.substr(3, 5)) const comparadorMedicamentoHoraInicial = new Date() comparadorMedicamentoHoraInicial.setHours(medicamento.horaInicial.substr(0, 2), medicamento.horaInicial.substr(3, 5)) do { horasRemedio.push(new Date(data.setTime(data.getTime() + (medicamento.intervaloTempo * 60 * 60 * 1000)) - 86400000)) } while ((data.getHours() !== comparadorMedicamentoHoraInicial.getHours())) const dataAtual = new Date() console.log(horasRemedio) for (let i = 0; i < horasRemedio.length; i++) { if (horasRemedio[i + 1].getTime() > dataAtual.getTime()) { medicamento.proximaHoraMedicamento = horasRemedio[i + 1] break; }else{ medicamento.proximaHoraMedicamento = horasRemedio[i] break; } } }); this.medicamentos = medicamentos this.calcularDiasRestantesMedicamento() } // new Date("dateString") is browser-dependent and discouraged, so we'll write // a simple parse function for U.S. date format (which does no error checking) parseDate(data) { data = data.substr(0,10) const dataTratada = data.split('/'); return new Date(dataTratada[2], dataTratada[1] - 1, dataTratada[0]); } calcularDiasRestantesMedicamento() { // Take the difference between the dates and divide by milliseconds per day. // Round to nearest whole number to deal with DST. const oneDay = 24*60*60*1000 let diasRestantes this.medicamentos.forEach(medicamento => { if(this.parseDate(medicamento.dataFim).getDate() > this.dataAtual.getDate()){ medicamento.diasRestantes = 'Medicamento já acabou' return } if(this.parseDate(medicamento.dataInicio).getDate() === this.dataAtual.getDate()){ medicamento.diasRestantes = 'Medicamento acaba hoje' return } diasRestantes = Math.round(Math.abs((this.dataAtual.getTime() - this.parseDate(medicamento.dataFim).getTime())/(oneDay))) medicamento.diasRestantes = `Medicamento acaba em ${diasRestantes} dias` }); } } <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { UsuarioService } from '../../services/domain/usuario.service'; import { NotificacoesService } from '../../services/domain/notificacoes.service'; /** * Generated class for the FormEsqueceuSenhaPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-form-esqueceu-senha', templateUrl: 'form-esqueceu-senha.html', }) export class FormEsqueceuSenhaPage { formGroup:FormGroup; constructor(public navCtrl: NavController, public navParams: NavParams, public formBuilder:FormBuilder, public usuarioService:UsuarioService, public notificacoesService:NotificacoesService) { this.formGroup = this.formBuilder.group({ pessoaEmail: ['', [Validators.required, Validators.email,]], novaSenha: ['', [Validators.required,Validators.minLength(6), Validators.maxLength(60)]], confirmacaoNovaSenha: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(60)]] }); } verificarSenhas(){ if(this.formGroup.value.novaSenha != this.formGroup.value.confirmacaoNovaSenha){ this.notificacoesService.presentToast('As senhas devem ser iguais','toast-error',2000,'middle') return true } return false } enviarSenhaNova(){ if(this.verificarSenhas()){ return } const objNovaSenha = { pessoaEmail:this.formGroup.value.pessoaEmail, novaSenha:this.formGroup.value.novaSenha } this.usuarioService.esqueceuSenha(objNovaSenha) .then(()=>{ this.notificacoesService.presentAlertJustMessage('Sucesso!!!','Verifique seu email para confirmar sua nova senha'); this.navCtrl.pop(); }) .catch((error)=>{ this.notificacoesService.presentAlertJustMessage('Falha!!!','Não foi possível encontrar alguém com esse email') }) } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { HistoricoMedicamentoPage } from './historico-medicamento'; @NgModule({ declarations: [ HistoricoMedicamentoPage, ], imports: [ IonicPageModule.forChild(HistoricoMedicamentoPage), ], }) export class HistoricoMedicamentoPageModule {} <file_sep> import { NotificacoesService } from './../services/domain/notificacoes.service'; import { LocalExameService } from './../services/domain/localExame.service'; import { LoginPage } from './../pages/login/login'; import { NgModule, ErrorHandler } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { MyApp } from './app.component'; import { TabsPage } from '../pages/tabs/tabs'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { UsuarioService } from '../services/domain/usuario.service'; import { AuthService } from '../services/auth.service'; import { StorageService } from '../services/storage.service'; import { HttpClientModule } from '@angular/common/http'; import { HttpModule } from '@angular/http'; import { ImageUtilService } from '../services/image-util.service'; import { MedicamentoService } from '../services/domain/medicamento.service'; import { ExameService } from '../services/domain/exame.service'; import { UtilsService } from '../services/domain/utils.service'; import { KeychainTouchId } from '@ionic-native/keychain-touch-id'; import { SecureStorageService } from '../services/secure-storage.service.'; import { SecureStorage } from '@ionic-native/secure-storage'; import { HandlerResponseProvider } from '../services/handler-response/handler-response'; import { Camera } from '@ionic-native/camera'; import { ExtractTwoWords } from '../pipes/extract-two-words'; import { PopoverMeuPerfilPage } from '../popovers/popover-meu-perfil/popover-meu-perfil'; import { PopoverExamesPage } from '../popovers/popover-exames/popover-exames'; import { PopoverDefaultPage } from '../popovers/popover-default/popover-default'; @NgModule({ declarations: [ MyApp, TabsPage, LoginPage, ExtractTwoWords, PopoverMeuPerfilPage, PopoverExamesPage, PopoverDefaultPage ], imports: [ BrowserModule, IonicModule.forRoot(MyApp), HttpClientModule, HttpModule ], bootstrap: [IonicApp], entryComponents: [ MyApp, TabsPage, LoginPage, PopoverMeuPerfilPage, PopoverExamesPage, PopoverDefaultPage ], providers: [ StatusBar, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler}, AuthService, StorageService, UsuarioService, ImageUtilService, MedicamentoService, LocalExameService, ExameService, NotificacoesService, UtilsService, KeychainTouchId, SecureStorageService, SecureStorage, HandlerResponseProvider, Camera ] }) export class AppModule {} <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, PopoverController } from 'ionic-angular'; import { LocalExameService } from '../../services/domain/localExame.service'; import { AlertController } from 'ionic-angular/components/alert/alert-controller'; import { PopoverDefaultPage } from '../../popovers/popover-default/popover-default'; /** * Generated class for the LocaisExamePage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-local-exame', templateUrl: 'local-exame.html', }) export class LocalExamePage { locaisExame; constructor( public navCtrl: NavController, public navParams: NavParams, public service:LocalExameService, public alertCtrl:AlertController, public popoverCtrl: PopoverController) { } ionViewDidLoad() { this.obterLocaisExame() } obterLocaisExame(){ this.service.findAllLocaisExameByPacienteId() .then(res=>{ this.locaisExame = res }) } atualizar(localExame){ this.navCtrl.push('FormLocalExamePage',{localExame:localExame}) } alertApagar(localExame) { let alert = this.alertCtrl.create({ title: "Atenção!", message: "Esta ação irá apagar este local de exame e todos exames nele associados, tem certeza disso ?", enableBackdropDismiss: false, buttons: [ { text: "Sim", handler: () => { this.apagar(localExame) } }, { text: "Não" } ] }); alert.present(); } apagar(localExame){ this.service.delete(localExame.id) .then(res => { this.obterLocaisExame(); }) } presentPopover(myEvent,item) { const popover = this.popoverCtrl.create(PopoverDefaultPage,{page:this,item:item}); popover.present({ ev: myEvent }); } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { LocalExamePage } from './local-exame'; @NgModule({ declarations: [ LocalExamePage, ], imports: [ IonicPageModule.forChild(LocalExamePage), ], providers:[ ] }) export class LocalExamePageModule {} <file_sep>import { Component, ViewChild, ElementRef } from "@angular/core"; import { IonicPage, NavController, NavParams } from "ionic-angular"; import { MapsProvider } from "../../services/google-maps/maps"; import { Geolocation } from '@ionic-native/geolocation'; import { LatLng } from "@ionic-native/google-maps"; import { ExameService } from "../../services/domain/exame.service"; import { StorageService } from "../../services/storage.service"; import { GoogleMapsService } from "../../services/google-maps/google.maps.service"; /** * Generated class for the MapaLocalizacaoExamesPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-mapa-localizacao-exames', templateUrl: 'mapa-localizacao-exames.html', }) export class MapaLocalizacaoExamesPage { exame; location: { latitude: number; longitude: number; }; markerOptions ; @ViewChild("map") mapElement: ElementRef; constructor( public navCtrl: NavController, public navParams:NavParams, public geolocation: Geolocation, public mapsProvider: MapsProvider, public exameService:ExameService, public storageService:StorageService, public googleMapsService:GoogleMapsService ) { this.exame = this.navParams.get('exame') console.log(this.exame) this.criaObjetoMarksBaseadoExame() } findUserLocation() { let options = { enableHighAccuracy: true, timeout: 25000 }; this.geolocation.getCurrentPosition(options).then((position) => { this.location = { latitude: position.coords.latitude, longitude: position.coords.longitude }; this.mapsProvider.init(this.location, this.mapElement,this.markerOptions); }).catch((error) => { console.log('Error getting location', error); }); } criaObjetoMarksBaseadoExame(){ let latLng; latLng = new LatLng(this.exame.localExameLatitude, this.exame.localExameLongitude); this.markerOptions = { title:`${this.exame.nome}`, position:latLng, icon: 'red', animation: 'DROP', } this.findUserLocation(); } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { MapaLocalizacaoExamesPage } from './mapa-localizacao-exames'; import { MapsProvider } from '../../services/google-maps/maps'; import { Geolocation } from '@ionic-native/geolocation'; import { GoogleMapsService } from '../../services/google-maps/google.maps.service'; @NgModule({ declarations: [ MapaLocalizacaoExamesPage, ], imports: [ IonicPageModule.forChild(MapaLocalizacaoExamesPage), ], providers:[ Geolocation, MapsProvider, GoogleMapsService ] }) export class MapaLocalizacaoExamesPageModule {} <file_sep> import {Events, NavController, NavParams, ViewController} from 'ionic-angular'; import { UsuarioService } from '../../services/domain/usuario.service'; import { StorageService } from '../../services/storage.service'; import { Camera, CameraOptions } from '@ionic-native/camera'; import { DomSanitizer } from '@angular/platform-browser'; import { NotificacoesService } from '../../services/domain/notificacoes.service'; import { Component } from '@angular/core'; @Component({ templateUrl: 'popover-meu-perfil.html', }) export class PopoverMeuPerfilPage { picture; navCtrl; constructor( public navParams:NavParams, public viewCtrl:ViewController, public usuarioService:UsuarioService, public storageService:StorageService, public camera: Camera, public sanitazer:DomSanitizer, public events: Events, public notificacoesService:NotificacoesService ) { this.navCtrl = this.navParams.get('navCtrl'); } close() { this.viewCtrl.dismiss(); } getCameraPicture() { this.close(); const options: CameraOptions = { quality: 65, targetWidth: 720, targetHeight: 720, correctOrientation:true, allowEdit: true, destinationType: this.camera.DestinationType.DATA_URL, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE } this.camera.getPicture(options).then((imageData) => { this.picture = 'data:image/png;base64,' + imageData; this.events.publish('foto:meu-perfil',this.picture) this.sendPicture() }, (err) => { }); } getGalleryPicture() { this.close(); const options: CameraOptions = { quality: 65, targetWidth: 720, targetHeight: 720, allowEdit: true, correctOrientation:true, sourceType:this.camera.PictureSourceType.PHOTOLIBRARY, destinationType: this.camera.DestinationType.DATA_URL, encodingType: this.camera.EncodingType.PNG, mediaType: this.camera.MediaType.PICTURE } this.camera.getPicture(options).then((imageData) => { this.picture = 'data:image/png;base64,' + imageData; this.events.publish('foto:meu-perfil',this.picture) this.sendPicture() }, (err) => { }); } sendPicture() { this.usuarioService.uploadPicture(this.picture) .then(response => { this.events.publish('buscar:foto') }, ).catch(()=>{ this.notificacoesService .presentToast('Ocorreu Algum erro na tentiva de envio da foto, Desculpe, tente novamente','toast-error',3000,'middle'); this.events.publish('foto:meu-perfil',"assets/imgs/avatar-blank.png") }); } alterarSenha(){ this.close() this.navCtrl.push('FormAlterarSenhaPage') } } <file_sep>import { HandlerResponseProvider } from './../handler-response/handler-response'; import { Injectable } from "@angular/core"; import { API_CONFIG } from "../../config/api.config"; import { StorageService } from "../storage.service"; import { Http, Headers } from '@angular/http'; @Injectable() export class GoogleMapsService { constructor( public http: Http, public storage: StorageService, public storageService: StorageService, public handlerResponseService: HandlerResponseProvider ) { } findLocationByCep(cep) { return this.handlerResponseService.handlerResponse( "get", `${API_CONFIG.urlGeolocation}address=${cep.substr(0,5)}-${cep.substr(5,8)}&sensor=false&key=${API_CONFIG.apiKeyGeolocation}`, null, null ); } } <file_sep>import { AlertController } from 'ionic-angular/components/alert/alert-controller'; import { ExameService } from './../../services/domain/exame.service'; import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, PopoverController } from 'ionic-angular'; import { PopoverExamesPage } from '../../popovers/popover-exames/popover-exames'; /** * Generated class for the ExamesPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-exames', templateUrl: 'exames.html', }) export class ExamesPage { exames; carregou = false; constructor( public navCtrl: NavController, public navParams: NavParams, public exameService:ExameService, public alertCtrl:AlertController, public popoverCtrl: PopoverController) { } ionViewDidLoad() { this.obterExames() } obterExames(){ return this.exameService.findExamesByPacienteId() .then(res=>{ this.exames = res; this.carregou = true; }) .catch(() =>{ this.carregou = true; }) } atualizar(exame){ this.navCtrl.push('FormExamePage',{exame:exame}) } alertApagarExame(exame) { let alert = this.alertCtrl.create({ title: "Atenção!", message: "Esta ação irá apagar esse exame, Tem certeza disso ?", enableBackdropDismiss: false, buttons: [ { text: "Sim", handler: () => { this.apagarExame(exame) } }, { text: "Não" } ] }); alert.present(); } apagarExame(exame){ this.exameService.delete(exame.id) .then(res =>{ this.obterExames() }) } doRefresh(refresher){ this.obterExames().then(()=>{ refresher.complete(); }); } presentPopover(myEvent,exame) { const popover = this.popoverCtrl.create(PopoverExamesPage,{examePage:this,exame:exame}); popover.present({ ev: myEvent }); } } <file_sep>import { HandlerResponseProvider } from './../handler-response/handler-response'; import { Injectable } from "@angular/core"; import { API_CONFIG } from "../../config/api.config"; import { StorageService } from "../storage.service"; import { ImageUtilService } from "../image-util.service"; import { Headers} from '@angular/http'; import { HttpClient, HttpHeaders } from '../../../node_modules/@angular/common/http'; @Injectable() export class UsuarioService { perfis; email; constructor( public http: HttpClient, public storage: StorageService, public imageUtilService: ImageUtilService, public storageService: StorageService, public handlerResponseService:HandlerResponseProvider ) { } // findPacienteByPessoaEmail(email: string) { // let headers = new Headers(); // headers.append("Authorization", `Bearer ${this.storage.getUserCredentials().token}`); // return this.handlerResponseService.handlerResponse( // "get", // `${API_CONFIG.baseUrl}/pacientes/pessoaEmail=${email}`, // null, // headers // ); // } findPacienteByPessoaCpf() { let headers = new Headers(); return this.storage.getUserCredentials() .then(userCredentials=>{ if(!userCredentials){ return; } headers.append('Authorization', `Bearer ${userCredentials['token']}`) return this.handlerResponseService.handlerResponse( "get", `${API_CONFIG.baseUrl}/pacientes/pessoaCpf?cpf=${userCredentials.cpf}`, null, headers ); }) } findAll() { let headers = new Headers(); return this.storage.getUserCredentials() .then(userCredentials=>{ if(!userCredentials){ return; } headers.append('Authorization', `Bearer ${userCredentials['token']}`) return this.handlerResponseService.handlerResponse( "get", `${API_CONFIG.baseUrl}/usuarios`, null, headers ); }); } findByEmail(email: string) { let headers = new Headers(); return this.storage.getUserCredentials() .then(userCredentials=>{ if(!userCredentials){ return; } headers.append('Authorization', `Bearer ${userCredentials['token']}`) return this.handlerResponseService.handlerResponse( "get", `${API_CONFIG.baseUrl}/usuarios/email?value=${email}`, null, headers ); }); } getImageFromBucket(urlFoto = this.storageService.getUser().pessoa.urlFoto ) { let headers = new HttpHeaders(); headers = headers .set("Cache-Control", "no-cache, no-store, must-revalidate") .set("Pragma", "no-cache") .set("Expires", "0"); let url = `${API_CONFIG.bucketBaseUrl}/${urlFoto}` return this.http.get(url, {headers:headers,responseType:'blob'}); } getImageFromBucketFromUsers(urlFoto) { let url = `${API_CONFIG.bucketBaseUrl}/${urlFoto}` return this.http.get(url, { responseType: 'blob' }); } uploadPicture(picture) { return this.storage.getUserCredentials() .then(userCredentials =>{ if(!userCredentials){ return; } let headers = new Headers(); headers.append('Authorization', `Bearer ${userCredentials['token']}`) let pictureBlob = this.imageUtilService.dataUriToBlob(picture); let formData: FormData = new FormData(); formData.set('file', pictureBlob, 'file.png'); return this.handlerResponseService.handlerResponseFoto( "post", `${API_CONFIG.baseUrl}/pessoas/picture`, formData, headers ); }); } alterarSenha(objNovaSenha) { let headers = new Headers(); return this.storage.getUserCredentials() .then(userCredentials=>{ if(!userCredentials){ return; } headers.append('Authorization', `Bearer ${userCredentials['token']}`) return this.handlerResponseService.handlerResponse( "put", `${API_CONFIG.baseUrl}/pessoas/alterarSenha`, objNovaSenha, headers ); }); } esqueceuSenha(objNovaSenha) { return this.handlerResponseService.handlerResponse( "post", `${API_CONFIG.baseUrl}/esqueceuSenha`, objNovaSenha, null ); } // getImageFromBucket(): Observable<any> { // let url = `${API_CONFIG.bucketBaseUrl}/${this.storageService.getUserUrlFoto()}` // return this.http.get(url, { responseType: 'blob' }); // } // getImageFromBucketFromUsers(urlFoto): Observable<any> { // let url = `${API_CONFIG.bucketBaseUrl}/${urlFoto}` // return this.http.get(url, { responseType: 'blob' }); // } // insert(obj: UsuarioDTO) { // return this.http.post( // `${API_CONFIG.baseUrl}/usuarios`, // obj, // { // observe: 'response', // responseType: 'text' // } // ); // } // uploadPicture(picture) { // let pictureBlob = this.imageUtilService.dataUriToBlob(picture); // let formData: FormData = new FormData(); // formData.set('file', pictureBlob, 'file.png'); // return this.http.post( // `${API_CONFIG.baseUrl}/usuarios/picture`, // formData, // { // observe: 'response', // responseType: 'text' // } // ); // } } <file_sep>import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { API_CONFIG } from "../../config/api.config"; @Injectable() export class ViaCepService { constructor( public http: HttpClient ) { } findEnderecoByCep(cep) { return this.http.get(`${API_CONFIG.viaCepUrl}/${cep}/json`); } } <file_sep>import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { AlertController } from 'ionic-angular/components/alert/alert-controller'; import { API_CONFIG } from "../../config/api.config"; import { StorageService } from "../storage.service"; import { Observable } from "rxjs/Observable"; import { ToastController,NavController } from "ionic-angular"; @Injectable() export class UtilsService { brazilianTimeToDate(data:string){ // Pega Mês // data.substr(data.indexOf('/')+1,data.lastIndexOf('/')-3) // Pega dia // data.substr(0,data.indexOf('/')) // Pega Ano // data.substr(data.lastIndexOf('/')+1,data.length -1 ) let dataFormatada = new Date(parseInt(data.substr(data.lastIndexOf('/')+1,data.length -1 )), parseInt(data.substr(data.indexOf('/')+1,data.lastIndexOf('/')-3)) -1, parseInt(data.substr(0,data.indexOf('/'))) ); return dataFormatada.toISOString().substr(0, 10).split('/').reverse().join('-'); } dateTimeToTime(data:string){ return data.substr(data.indexOf(':')-2,data.length-1) } } <file_sep>import { LocalUser } from './../models/local_user'; import { Injectable } from '@angular/core'; import { STORAGE_KEYS } from '../config/storage_keys.config'; import { SecureStorage, SecureStorageObject } from '../../node_modules/@ionic-native/secure-storage'; import { Platform } from '../../node_modules/ionic-angular/platform/platform'; @Injectable() export class SecureStorageService { constructor(private secureStorage: SecureStorage, private platform:Platform) { } setSenha(password) { return this.platform.ready().then(() => { return this.secureStorage.create('password_user') .then((storage: SecureStorageObject) => { return storage.set(STORAGE_KEYS.password, password).catch(err => err); }, err => err) }) } getSenha() { return this.platform.ready().then(() => { return this.secureStorage.create('password_user') .then((storage: SecureStorageObject) => { return storage.get(STORAGE_KEYS.password); }, err => err) }) } } <file_sep>import { SplashScreen } from '@ionic-native/splash-screen'; import { Component, ViewChild } from '@angular/core'; import { Nav, NavParams, Tabs, Events, Platform } from 'ionic-angular'; declare var window; @Component({ selector: 'page-tabs', templateUrl: 'tabs.html', }) export class TabsPage { @ViewChild('tabs') tabs: Tabs; child; pagina; from; static index; constructor( public navCtrl: Nav, public navParams: NavParams, private events: Events, private splashScreen: SplashScreen, private platform: Platform ) { this.events.subscribe('tabs:reset', () => this.resetTabs()); } ngOnInit() { this.pagina = this.navParams.get('pagina'); this.from = this.navParams.get('from'); } ionViewDidLoad() { this.platform.ready().then(() => { setTimeout(() => { this.splashScreen.hide(); }, 1000) }) if (this.pagina) { this.tabs.selectedIndex = TabsPage.index; this.child = this.tabs.getByIndex(TabsPage.index); const params = this.navParams.get('params'); const from = this.from; if (params) { this.child.push(this.pagina, {from: from, params}); } else { this.child.push(this.pagina, {from: from}); } this.pagina = undefined; } } getIndex() { return TabsPage.index; } resetTabs() { for (let i = 0; i < this.tabs.length(); i++) { let tempTab = this.tabs.getByIndex(i); if (tempTab.getViews()) if (tempTab.getViews().length > 0) tempTab.goToRoot({}); } } onTabsChange(index) { TabsPage.index = index; } } <file_sep>import { AlertController } from 'ionic-angular/components/alert/alert-controller'; import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, PopoverController } from 'ionic-angular'; import { MedicamentoService } from '../../services/domain/medicamento.service'; import { PopoverDefaultPage } from '../../popovers/popover-default/popover-default'; @IonicPage() @Component({ selector: 'page-historico-medicamento', templateUrl: 'historico-medicamento.html', }) export class HistoricoMedicamentoPage { medicamentos; constructor( public navCtrl: NavController, public navParams: NavParams, public service:MedicamentoService, public alertCtrl:AlertController, public popoverCtrl: PopoverController) { } ionViewDidLoad() { this.obterMedicamentosInativos() } obterMedicamentosInativos(){ this.service.findMedicamentosInativosByPacienteId() .then(res=>{ this.medicamentos = res; }) } alertApagar(medicamento) { let alert = this.alertCtrl.create({ title: "Atenção!", message: "Esta ação irá apagar o medicamento, tem certeza disso ?", enableBackdropDismiss: false, buttons: [ { text: "Sim", handler: () => { this.apagar(medicamento) } }, { text: "Não" } ] }); alert.present(); } apagar(medicamento){ this.service.delete(medicamento.id) .then(res =>{ this.obterMedicamentosInativos() }) } setAtivo(medicamento){ this.service.setAtivo(medicamento.id) .then(res=>{ this.obterMedicamentosInativos(); }) } presentPopover(myEvent,item) { const popover = this.popoverCtrl.create(PopoverDefaultPage,{page:this,item:item}); popover.present({ ev: myEvent }); } } <file_sep>import { UtilsService } from './../../services/domain/utils.service'; import { NotificacoesService } from './../../services/domain/notificacoes.service'; import { StorageService } from './../../services/storage.service'; import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular'; import { ExameService } from '../../services/domain/exame.service'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { LocalExameService } from '../../services/domain/localExame.service'; /** * Generated class for the FormExamePage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-form-exame', templateUrl: 'form-exame.html', }) export class FormExamePage { exame; locaisExame: Object; pacienteId: any; formGroup:FormGroup; constructor( public navCtrl: NavController, public navParams: NavParams, public storageService:StorageService, public formBuilder:FormBuilder, public notificacoesService:NotificacoesService, public exameService:ExameService, public localExameService:LocalExameService, public utilsService:UtilsService ) { this.exame = this.navParams.get('exame'); this.pacienteId = this.storageService.getUser().id; this.formGroup = this.formBuilder.group({ nome: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(60)]], descricao: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(140)]], exameDia: ['', [Validators.required]], exameHora: ['',], data: ['', ], localExameId: [null, [Validators.required]], pacienteId: [this.pacienteId] }); } ionViewDidLoad() { this.obterLocaisExame(); } obterLocaisExame(){ this.localExameService.findAllLocaisExameByPacienteId() .then(res=>{ this.locaisExame = res; this.verificaUpdate(); }) } adicionarExame(){ if(!this.exame){ this.salvarExame() }else{ this.atualizarExame() } } salvarExame(){ this.formGroup.controls.data .setValue(this.formGroup.value.data.concat(this.formGroup.value.exameDia,' ',this.formGroup.value.exameHora)); this.formGroup.removeControl('exameDia'); this.formGroup.removeControl('exameHora'); this.exameService.insert(this.formGroup.value).then(res=>{ this.notificacoesService.presentAlertDefault('Sucesso!','Exame Adicionado',null,this.navCtrl) }) } atualizarExame(){ this.formGroup.controls.data .setValue(this.formGroup.value.data.concat(this.formGroup.value.exameDia,' ',this.formGroup.value.exameHora)); this.formGroup.removeControl('exameDia'); this.formGroup.removeControl('exameHora'); this.exameService.update(this.formGroup.value,this.exame.id).then(res=>{ this.notificacoesService.presentAlertDefault('Sucesso!','Exame Atualizado',null,this.navCtrl) }) } verificaUpdate(){ if(this.exame){ this.formGroup.controls.nome.setValue(this.exame.nome); this.formGroup.controls.descricao.setValue(this.exame.descricao); this.formGroup.controls.exameDia .setValue(this.utilsService.brazilianTimeToDate(this.exame.data)); this.formGroup.controls.exameHora .setValue(this.utilsService.dateTimeToTime(this.exame.data)); this.formGroup.controls.localExameId.setValue(this.exame.localExameId); this.formGroup.controls.pacienteId.setValue(this.exame.pacienteId); } } } <file_sep>import { TabsPage } from './../tabs/tabs'; import { Component } from '@angular/core'; import { NavController, NavParams, MenuController, AlertController, LoadingController, Events } from 'ionic-angular'; import { AuthService } from '../../services/auth.service'; import { CreadenciaisDTO } from '../../models/credenciais.dto'; import { UsuarioService } from '../../services/domain/usuario.service'; import { StorageService } from '../../services/storage.service'; import { SecureStorageService } from '../../services/secure-storage.service.'; import { KeychainTouchId } from '@ionic-native/keychain-touch-id'; import { NotificacoesService } from '../../services/domain/notificacoes.service'; /** * Generated class for the LoginPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @Component({ selector: 'page-login', templateUrl: 'login.html', }) export class LoginPage { email; perfis = []; creds : CreadenciaisDTO = { cpf: "", senha: "" }; DECIMAL_SEPARATOR="."; GROUP_SEPARATOR=","; pureResult: any; maskedId: any; val: any; v: any; cpfValido; hasFingerprint; typeSenha: any = '<PASSWORD>'; constructor( public navCtrl: NavController, public menu: MenuController, public auth: AuthService, public usuarioService:UsuarioService, public storageService:StorageService, public alertCtrl:AlertController, public loadingCtrl:LoadingController, public events: Events, public secureStorageService:SecureStorageService, public keychainService:KeychainTouchId, public notificacoesService:NotificacoesService) { this.creds.cpf = storageService.getCpf(); this.creds.cpf = this.format(this.creds.cpf) } ionViewWillEnter() { this.menu.swipeEnable(false); } ionViewDidLeave() { this.menu.swipeEnable(true); } ionViewDidLoad() { this.keychainService.isAvailable() .then((res: any) => { this.keychainService.setLocale('pt'); this.hasFingerprint = true }) .catch(err => this.hasFingerprint = false); } exibirSenhaInput(){ if(this.typeSenha == 'password'){ this.typeSenha = 'text' return; } this.typeSenha = '<PASSWORD>'; } // ionViewDidEnter() { // this.auth.refreshToken() // .subscribe(response => { // this.auth.successfulLogin(response.headers.get('Authorization')); // this.navCtrl.setRoot(TabsPage); // }, // error => {}); // } login() { const loading = this.presentLoadingDefault() this.creds.cpf = this.retirarFormatacao(this.creds.cpf) this.auth.authenticate(this.creds) .subscribe(response => { loading.dismiss() this.auth.successfulLogin(response.headers.get('Authorization')) .then(()=>{ this.secureStorageService.setSenha(this.creds.senha) this.alertSalvarLogin(this.creds.cpf); this.usuarioService .findPacienteByPessoaCpf() .then(() => { this.events.publish('buscar:foto') }) this.navCtrl.setRoot(TabsPage); }); }, error => { console.log('Chegou aqui') this.creds.cpf = this.format(this.creds.cpf) loading.dismiss(); this.tratarErro(error); }) } tratarErro(error){ if(error.status==401){ this.notificacoesService.presentAlertJustMessage('Login ou senha incorreto','Favor, Verifique suas credenciais') } else if(error.status == 404 || error.status == 500){ this.notificacoesService.presentAlertJustMessage('Servidor indisponível','Contate a equipe de suporte') }else if (error.status == 0){ this.notificacoesService.presentAlertJustMessage('Problema na conexão','Verifique sua conexão com a internet') } } showAlert(){ let alert = this.alertCtrl.create({ title:'Falha!', message:'Falha na conexão, tente novamente...', enableBackdropDismiss:false, buttons:[ { text:'Ok', handler:() =>{ } } ] }); alert.present(); } salvarLogin(cpf){ this.storageService.setCpf(cpf) } alertSalvarLogin(cpf){ let alert = this.alertCtrl.create({ title:'Salvar Login!', message:'Deseja Salvar o Seu CPF ?', buttons:[ { text:'Sim', handler:() =>{ this.salvarLogin(cpf) } }, { text:'Não', handler:()=> { this.storageService.setEmail(null) } } ] }); alert.present(); } presentLoadingDefault() { let loading = this.loadingCtrl.create({ content: 'Autenticando...' }); loading.present(); return loading; } retirarFormatacao(cpfFormatado) { return cpfFormatado.replace(/(\.|\/|\-)/g,""); } format(valString) { if (!valString) { return ''; } let val = valString.toString(); const parts = this.unFormat(val).split(this.DECIMAL_SEPARATOR); this.pureResult = parts; if(parts[0].length <= 11){ this.maskedId = this.cpf_mask(parts[0]); this.cpfValido = this.pureResult; return this.maskedId; }else{ return this.cpfValido; } }; cpf_mask(v) { v = v.replace(/\D/g, ''); //Remove tudo o que não é dígito v = v.replace(/(\d{3})(\d)/, '$1.$2'); //Coloca um ponto entre o terceiro e o quarto dígitos v = v.replace(/(\d{3})(\d)/, '$1.$2'); //Coloca um ponto entre o terceiro e o quarto dígitos //de novo (para o segundo bloco de números) v = v.replace(/(\d{3})(\d{1,2})$/, '$1-$2'); //Coloca um hífen entre o terceiro e o quarto dígitos return v; } unFormat(val) { if (!val) { return ''; } val = val.replace(/\D/g, ''); if (this.GROUP_SEPARATOR === ',') { return val.replace(/,/g, ''); } else { return val.replace(/\./g, ''); } } focusPasswordInput() { if(this.hasFingerprint){ const cpfUsuario = String(this.retirarFormatacao(this.creds.cpf)) this.keychainService.verify(cpfUsuario,"Coloque o Dedo no leitor") .then(password_user=>{ this.creds.senha = <PASSWORD>; this.login(); this.events.publish('assinatura:adicionada') }) .catch(error=>error) } } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { FormEsqueceuSenhaPage } from './form-esqueceu-senha'; @NgModule({ declarations: [ FormEsqueceuSenhaPage, ], imports: [ IonicPageModule.forChild(FormEsqueceuSenhaPage), ], }) export class FormEsqueceuSenhaPageModule {} <file_sep>import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { AlertController } from 'ionic-angular/components/alert/alert-controller'; import { API_CONFIG } from "../../config/api.config"; import { StorageService } from "../storage.service"; import { Observable } from "rxjs/Observable"; import { ToastController,NavController } from "ionic-angular"; @Injectable() export class NotificacoesService { constructor( public http: HttpClient, public storage: StorageService, public alertCtrl:AlertController, public toastCtrl:ToastController ) { } presentToast(message:string,css:string,duration:number,position:string) { let toast = this.toastCtrl.create({ message: message, duration: duration, position: position, cssClass:css }); toast.present(); } presentAlertDefault(title,message,page?,navCtrl?:NavController){ let alert = this.alertCtrl.create({ title:title, message:message, enableBackdropDismiss:false, buttons:[ { text:'Ok', handler:() =>{ if(page){ navCtrl.setRoot(page) }else{ navCtrl.pop() } } } ] }); alert.present(); } presentAlertJustMessage(title,message){ let alert = this.alertCtrl.create({ title:title, message:message, enableBackdropDismiss:false, buttons:[ { text:'Ok', } ] }); alert.present(); } } <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular'; import { StorageService } from '../../services/storage.service'; import { Validators, FormGroup, FormBuilder } from '@angular/forms'; import { MedicamentoService } from '../../services/domain/medicamento.service'; import { UtilsService } from '../../services/domain/utils.service'; /** * Generated class for the FormMedicamentoPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-form-medicamento', templateUrl: 'form-medicamento.html', }) export class FormMedicamentoPage { pacienteId; formGroup: FormGroup; medicamento; constructor( public navCtrl: NavController, public navParams: NavParams, public storageService: StorageService, public formBuilder: FormBuilder, public medicamentoService:MedicamentoService, public alertCtrl:AlertController, public utilsService:UtilsService) { this.medicamento = this.navParams.get('item'); this.pacienteId = this.storageService.getUser().id; this.formGroup = this.formBuilder.group({ nome: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(60)]], descricao: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(200)]], intervaloTempo: ['', [Validators.required]], dataInicio: ['', [Validators.required]], dataFim: ['', [Validators.required]], horaInicial: ['', [Validators.required]], pacienteId: [this.pacienteId] }); } ionViewDidLoad() { this.verificaUpdate(); } adicionarMedicamento(){ if(!this.medicamento){ this.salvarMedicamento(); }else{ this.atualizarMedicamento(); } } salvarMedicamento(){ this.medicamentoService.insert(this.formGroup.value).then(res=>{ this.showAlertSucesso('Medicamento Adicionado a Lista'); }) } atualizarMedicamento(){ this.medicamentoService.update(this.formGroup.value,this.medicamento.id).then(res=>{ this.showAlertSucesso('Medicamento atualizado'); }) } showAlertSucesso(message){ let alert = this.alertCtrl.create({ title:'Sucesso!', message:message, enableBackdropDismiss:false, buttons:[ { text:'Ok', handler:() =>{ this.navCtrl.pop() } } ] }); alert.present(); } verificaUpdate(){ if(this.medicamento){ this.formGroup.controls.nome.setValue(this.medicamento.nome); this.formGroup.controls.descricao.setValue(this.medicamento.descricao); this.formGroup.controls.intervaloTempo.setValue(this.medicamento.intervaloTempo); this.formGroup.controls.dataInicio .setValue(this.utilsService.brazilianTimeToDate(this.medicamento.dataInicio)); this.formGroup.controls.dataFim .setValue(this.utilsService.brazilianTimeToDate(this.medicamento.dataFim)); this.formGroup.controls.horaInicial.setValue(this.medicamento.horaInicial); this.formGroup.controls.pacienteId.setValue(this.medicamento.pacienteId); } } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { FormMedicamentoPage } from './form-medicamento'; @NgModule({ declarations: [ FormMedicamentoPage, ], imports: [ IonicPageModule.forChild(FormMedicamentoPage), ], }) export class FormMedicamentoPageModule {} <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule, IonicApp } from 'ionic-angular'; import { MeuPerfilPage } from './meu-perfil'; import { PhotoViewer } from '@ionic-native/photo-viewer'; @NgModule({ declarations: [ MeuPerfilPage, ], imports: [ IonicPageModule.forChild(MeuPerfilPage), ], providers:[ PhotoViewer ] }) export class MeuPerfilPageModule {} <file_sep>import { ViaCepService } from './../../services/domain/viaCep.service'; import { StorageService } from './../../services/storage.service'; import { CidadeService } from './../../services/domain/cidade.service'; import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, AlertController, ToastController } from 'ionic-angular'; import { CidadeDTO } from '../../models/cidade.dto'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { LocalExameService } from '../../services/domain/localExame.service'; import { GoogleMapsService } from '../../services/google-maps/google.maps.service'; /** * Generated class for the FormLocalExamePage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-form-local-exame', templateUrl: 'form-local-exame.html', }) export class FormLocalExamePage { pacienteId: any; localExame; cidadeEncontrada; cidades = []; formGroup:FormGroup; constructor( public navCtrl: NavController, public navParams: NavParams, public cidadeService:CidadeService, public formBuilder:FormBuilder, public storageService:StorageService, public localExameService:LocalExameService, public alertCtrl:AlertController, public toastCtrl:ToastController, public viaCepService:ViaCepService, public googleMapsService:GoogleMapsService) { this.localExame = this.navParams.get('item') console.log(this.localExame) this.pacienteId = this.storageService.getUser().id; this.formGroup = this.formBuilder.group({ nome: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(60)]], enderecoNumero: ['', [Validators.required]], enderecoLogradouro: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(60)]], enderecoBairro: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(60)]], enderecoLatitude: [null], enderecoLongitude: [null], enderecoCep: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(60)]], cidadeId: [null, [Validators.required]], enderecoId: [null], pacienteId: [this.pacienteId] }); } ionViewDidLoad() { this.obterCidades(); } obterCidades(){ this.cidadeService.findAll() .then(res=>{ this.cidades = res; this.cidadeEncontrada = null; this.verificaUpdate(); }) } adicionarLocal(){ if(!this.localExame){ this.salvarLocalExame() }else{ this.atualizarLocalExame() } } showAlertSucesso(message){ let alert = this.alertCtrl.create({ title:'Sucesso!', message:message, enableBackdropDismiss:false, buttons:[ { text:'Ok', handler:() =>{ this.navCtrl.pop() } } ] }); alert.present(); } salvarLocalExame(){ this.formGroup.removeControl('enderecoId') this.localExameService.insert(this.formGroup.value).then(res=>{ this.showAlertSucesso('Local de Exame adicionado'); }) } atualizarLocalExame(){ this.localExameService.update(this.formGroup.value,this.localExame.id).then(res=>{ this.showAlertSucesso('Local de Exame atualizado'); }) } buscarViaCep() { this.viaCepService.findEnderecoByCep(this.formGroup.value.enderecoCep) .subscribe(res=>{ this.exibirToastEnderecoEncontrado(); this.formGroup.controls.enderecoBairro.setValue(res['bairro']); this.formGroup.controls.enderecoLogradouro.setValue(res['logradouro']); this.cidadeEncontrada = this.cidades.find(el=>el.nome === res['localidade']); this.buscarLatLong() if(this.cidadeEncontrada){ this.formGroup.controls.cidadeId.setValue(this.cidadeEncontrada.id); } },error=>this.exibirToastCepInvalido()); } buscarLatLong(){ this.googleMapsService.findLocationByCep(this.formGroup.value.enderecoCep) .then(location =>{ this.formGroup.controls.enderecoLatitude.setValue(location.results[0].geometry.location.lat); this.formGroup.controls.enderecoLongitude.setValue(location.results[0].geometry.location.lng); }) } verificaUpdate(){ if(this.localExame){ console.log('localExame',this.localExame) this.formGroup.controls.nome.setValue(this.localExame.nome); this.formGroup.controls.enderecoNumero.setValue(this.localExame.enderecoNumero); this.formGroup.controls.enderecoLogradouro.setValue(this.localExame.enderecoLogradouro); this.formGroup.controls.enderecoCep.setValue(this.localExame.enderecoCep); this.formGroup.controls.enderecoLatitude.setValue(this.localExame.enderecoLatitude); this.formGroup.controls.enderecoLongitude.setValue(this.localExame.enderecoLongitude); this.formGroup.controls.enderecoBairro.setValue(this.localExame.enderecoBairro); this.formGroup.controls.cidadeId.setValue(this.localExame.cidadeId); this.formGroup.controls.pacienteId.setValue(this.localExame.pacienteId); this.formGroup.controls.enderecoId.setValue(this.localExame.enderecoId); this.cidadeEncontrada = this.cidades.find(el=>el.id === this.localExame.cidadeId); this.formGroup.controls.cidadeId.setValue(this.cidadeEncontrada.id); } } exibirToastCepInvalido() { let toast = this.toastCtrl.create({ message: 'CEP Inválido', cssClass: "toast-error", duration: 3000, position: 'middle' }); toast.present(); } exibirToastEnderecoEncontrado() { let toast = this.toastCtrl.create({ message: 'Endereço Encontrado 😁', duration: 3000, position: 'bottom' }); toast.present(); } } <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, Events } from 'ionic-angular'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { NotificacoesService } from '../../services/domain/notificacoes.service'; import { UsuarioService } from '../../services/domain/usuario.service'; import { KeychainTouchId } from '@ionic-native/keychain-touch-id'; import { StorageService } from '../../services/storage.service'; /** * Generated class for the FormAlterarSenhaPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-form-alterar-senha', templateUrl: 'form-alterar-senha.html', }) export class FormAlterarSenhaPage { formGroup:FormGroup; constructor( public navCtrl: NavController, public navParams: NavParams, public formBuilder:FormBuilder, public notificacoesService:NotificacoesService, public usuarioService:UsuarioService, public keychainService:KeychainTouchId, public storageService:StorageService, public events: Events ) { this.formGroup = this.formBuilder.group({ senhaAtual: ['', [Validators.required]], novaSenha: ['', [Validators.required,Validators.minLength(6), Validators.maxLength(60)]], confirmacaoNovaSenha: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(60)]] }); this.keychainService.isAvailable() .then(()=>{ this.keychainService.has((String(this.storageService.getUser().pessoa.cpf))) .then(()=>{ this.notificacoesService.presentToast('Sua Biometria será removida, caso altere sua senha','toast-attention',3000,'top') }) .catch(error=>error) }) .catch(error=>error) } verificarSenhas(){ if(this.formGroup.value.novaSenha != this.formGroup.value.confirmacaoNovaSenha){ return true } return false } enviarNovaSenha(){ if(this.verificarSenhas()){ this.notificacoesService.presentToast('As senhas devem ser iguais','toast-error',2000,'middle') return } const objNovaSenha = { senhaAtual:this.formGroup.value.senhaAtual, novaSenha:this.formGroup.value.confirmacaoNovaSenha } this.usuarioService.alterarSenha(objNovaSenha) .then(()=>{ this.removerBiometria() this.notificacoesService.presentToast('Senha Alterada!','default',2000,'middle') this.navCtrl.pop() }) .catch(()=>{ this.notificacoesService.presentToast('Senhal atual é diferente da registrada no sistema','toast-error',2000,'middle') }) } removerBiometria(){ this.keychainService.isAvailable() .then(()=>{ this.keychainService.has((String(this.storageService.getUser().pessoa.cpf))) .then(()=>{ const userCpf = (String(this.storageService.getUser().pessoa.cpf)) return this.keychainService.delete(userCpf) .then(() => { this.events.publish('biometria:removida') }, err => err); }) .catch(error=>error) }) .catch(error=>error) } } <file_sep> import {NavParams, ViewController} from 'ionic-angular'; import { Component } from '@angular/core'; @Component({ templateUrl: 'popover-exames.html', }) export class PopoverExamesPage { navCtrl; exame; examePage: any; constructor( public navParams:NavParams, public viewCtrl:ViewController, ) { this.examePage = this.navParams.get('examePage'); this.exame = this.navParams.get('exame') } close() { this.viewCtrl.dismiss(); } editarExame(){ this.close() this.examePage.navCtrl.push('FormExamePage',{exame:this.exame}) } deletarExame(){ this.examePage.alertApagarExame(this.exame) } localizarExame(){ this.close() this.examePage.navCtrl.push('MapaLocalizacaoExamesPage',{exame:this.exame}) } } <file_sep>import { HandlerResponseProvider } from './../handler-response/handler-response'; import { Injectable } from "@angular/core"; import { API_CONFIG } from "../../config/api.config"; import { StorageService } from "../storage.service"; import { Http, Headers } from '@angular/http'; @Injectable() export class MedicamentoService { constructor( public http: Http, public storage: StorageService, public storageService: StorageService, public handlerResponseService:HandlerResponseProvider ) { } findMedicamentosAtivosByPacienteId() { let headers = new Headers(); return this.storage.getUserCredentials() .then(userCredentials=>{ if(!userCredentials){ return; } let pacienteId = this.storage.getUser().id headers.append('Authorization', `Bearer ${userCredentials['token']}`) return this.handlerResponseService.handlerResponse( "get", `${API_CONFIG.baseUrl}/medicamentos/ativos?idPaciente=${pacienteId}`, null, headers ); }); } findMedicamentosInativosByPacienteId() { let headers = new Headers(); return this.storage.getUserCredentials() .then(userCredentials=>{ if(!userCredentials){ return; } let pacienteId = this.storage.getUser().id headers.append('Authorization', `Bearer ${userCredentials['token']}`) return this.handlerResponseService.handlerResponse( "get", `${API_CONFIG.baseUrl}/medicamentos/inativos?idPaciente=${pacienteId}`, null, headers ); }); } insert(medicamento) { let headers = new Headers(); return this.storage.getUserCredentials() .then(userCredentials=>{ if(!userCredentials){ return; } headers.append('Authorization', `Bearer ${userCredentials['token']}`) return this.handlerResponseService.handlerResponse( "post", `${API_CONFIG.baseUrl}/medicamentos`, medicamento, headers ); }); } delete(id){ let headers = new Headers(); return this.storage.getUserCredentials() .then(userCredentials=>{ if(!userCredentials){ return; } headers.append('Authorization', `Bearer ${userCredentials['token']}`) return this.handlerResponseService.handlerResponse( "delete", `${API_CONFIG.baseUrl}/medicamentos/${id}`, null, headers ); }); } update(medicamento,id) { let headers = new Headers(); return this.storage.getUserCredentials() .then(userCredentials=>{ if(!userCredentials){ return; } headers.append('Authorization', `Bearer ${userCredentials['token']}`) return this.handlerResponseService.handlerResponse( "put", `${API_CONFIG.baseUrl}/medicamentos/${id}`, medicamento, headers ); }); } setAtivo(id) { let headers = new Headers(); return this.storage.getUserCredentials() .then(userCredentials=>{ if(!userCredentials){ return; } headers.append('Authorization', `Bearer ${userCredentials['token']}`) return this.handlerResponseService.handlerResponse( "put", `${API_CONFIG.baseUrl}/medicamentos/setAtivo/${id}`, null, headers ); }); } setInativo(id) { let headers = new Headers(); return this.storage.getUserCredentials() .then(userCredentials=>{ if(!userCredentials){ return; } headers.append('Authorization', `Bearer ${userCredentials['token']}`) return this.handlerResponseService.handlerResponse( "put", `${API_CONFIG.baseUrl}/medicamentos/setInativo/${id}`, null, headers ); }); } } <file_sep> import { NavParams, ViewController } from 'ionic-angular'; import { Component } from '@angular/core'; @Component({ templateUrl: 'popover-default.html', }) export class PopoverDefaultPage { navCtrl; page; // Page Genérica a ser usada item: any; // Item genérico a ser usado nomePage; constructor( public navParams: NavParams, public viewCtrl: ViewController, ) { this.page = this.navParams.get('page'); this.item = this.navParams.get('item'); this.nomePage = this.page.constructor.name console.log(this.nomePage) } close() { this.viewCtrl.dismiss(); } editar() { this.close() this.page.navCtrl.push(`Form${this.nomePage}`, { item: this.item }) } deletar() { this.close() this.page.alertApagar(this.item) } ativarMedicamento() { this.close() this.page.setAtivo(this.item) } deletarMedicamento() { this.close() this.page.alertApagar(this.item) } desativarMedicamento() { this.close() this.page.setInativo(this.item) } } <file_sep>import { ViaCepService } from './../../services/domain/viaCep.service'; import { CidadeService } from './../../services/domain/cidade.service'; import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { FormLocalExamePage } from './form-local-exame'; import { GoogleMapsService } from '../../services/google-maps/google.maps.service'; @NgModule({ declarations: [ FormLocalExamePage, ], imports: [ IonicPageModule.forChild(FormLocalExamePage), ], providers:[ CidadeService, ViaCepService, GoogleMapsService ] }) export class FormLocalExamePageModule {}
83d04d29b643e30a4f39d241723bd026f44e1639
[ "TypeScript" ]
33
TypeScript
kelvi-ribeiro/app-info-saude-paciente
4a48a955de941668312bc3606485875014cbbf1f
611406231cd6243e20261cc85a74d128f189fd1d
refs/heads/master
<file_sep>#include<stdio.h> #include<conio.h> #include<stdlib.h> #include<windows.h> #include<time.h> #define WIDTH 15 #define HEIGHT 30 #define DOWN 1 //一个随机函数 获得砖的高度 //根据输入,飞行 void updateWithInput(void); void updateWithoutInput(void); void show(void); void menu(void); void starts(void); int random(int min, int max); int arr[WIDTH][HEIGHT] = {0}; int brid_x, brid_y; int brick_x[4], brick_y[2]; int xueko[2], hinder[2]; int brick_width; int random(int min, int max){ time_t t; srand((unsigned int)time(&t)); return rand()%max+min; } void gotoxy(int x, int y){ HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE); COORD pos; pos.X = x; pos.Y = y; SetConsoleCursorPosition(handle, pos); } void updateWithInput(){ char ch; if(kbhit()){ ch = getch(); switch(ch){ case ' ': arr[brid_x][brid_y] = 0; brid_x -= 2; arr[brid_x][brid_y] = 1; break; default: break; } } } void starts(){ int i; brick_y[0] = HEIGHT-1; brick_y[1] = brick_y[0]-10; brid_x = 1; brid_y = HEIGHT/20; xueko[0] = random(2, 5); xueko[1] = random(2, 5); hinder[1] = random(0, WIDTH-xueko[0]); hinder[0] = random(0, WIDTH-xueko[0]); for(i = 0; i<WIDTH; i++){ if(i<hinder[0] || i>hinder[0]+xueko[0]){ arr[i][brick_y[0]] = 2; } if(i<hinder[1] || i>hinder[1]+xueko[1]){ arr[i][brick_y[1]] = 2; } } arr[brid_x][brid_y] = 1; } void updateWithoutInput(){ int i; static int speed = 0; if(brick_y[0] >= 0){ for(i = 0; i<WIDTH; i++){ if(i<hinder[0] || i>hinder[0]+xueko[0]){ arr[i][brick_y[0]] = 0; } } brick_y[0] -= 1; for(i = 0; i<WIDTH; i++){ if(i<hinder[0] || i>hinder[0]+xueko[0]){ arr[i][brick_y[0]] = 2; } } }else{ brick_y[0] = HEIGHT-1; xueko[0] = random(2, 5); hinder[0] = random(0, WIDTH-xueko[0]); for(i = 0; i<WIDTH; i++){ if(i<hinder[0] || i>hinder[0]+xueko[0]){ arr[i][brick_y[0]] = 2; } } } if(brid_x <= 0){ printf("\a"); arr[brid_x][brid_y] = 0; brid_x = 1; arr[brid_x][brid_y] = 1; } else if(brid_x >= 14 ){ gotoxy(0, 0); printf("游戏失败"); exit(0); } else{ if(speed < 5){ speed++; } if(speed == 5){ arr[brid_x][brid_y] = 0; brid_x += DOWN; arr[brid_x][brid_y] = 1; speed = 0; } } } int main(){ //初始化数据 menu(); starts(); while(1){ show(); updateWithInput(); updateWithoutInput(); } return 0; } void menu(){ } void show(){ int i, j; gotoxy(0, 0); for(i = 0; i<WIDTH; i++){ for(j = 0; j<HEIGHT; j++){ if(arr[i][j] == 0){ printf(" "); } else if(arr[i][j] == 1){ printf("@"); } else if(arr[i][j] == 2){ printf("|"); } } printf("|\n"); } for(i = 0; i<HEIGHT; i++){ printf("-"); } printf("\n"); Sleep(30); }
34c4a62c3837ae9911bec4ce9f9775b19cf2d744
[ "C" ]
1
C
tutenglele/nowrepos
b7bda29680491229d756af2f0d3e252cf9492715
a3cff23abd6c62829e982382c4f7390926653cf6
refs/heads/main
<file_sep>def shell_sort(nums): sub_list_count = len(nums)//2 while sub_list_count > 0: for start_position in range(sub_list_count): gap_insertion_sort(nums, start_position, sub_list_count) yield nums sub_list_count = sub_list_count // 2 def gap_insertion_sort(nlist, start, gap): for i in range(start + gap, len(nlist), gap): current_value = nlist[i] position = i while position >= gap and nlist[position-gap] > current_value: nlist[position] = nlist[position-gap] position = position-gap nlist[position] = current_value <file_sep># sort_visualizer Visualizer for sorting algorithms main.py calls sorting funcitons from different files. Visualizer animates each step algorithm makes while sorting. Currently implemented sorting algorithms: Bubble sort, Heap Sort, Shell Sort, Insertion Sort, Selection Sort, Merge Sort, Quick Sort. <file_sep>def swap(A, i, j): A[i], A[j] = A[j], A[i] def merge_sort(nums, left, right): if(right <= left): return elif(left < right): mid = (left + right)//2 yield from merge_sort(nums, left, mid) yield from merge_sort(nums, mid+1, right) yield from merge(nums, left, mid, right) yield nums def merge(nums, left, mid, right): new = [] i = left j = mid+1 while(i <= mid and j <= right): if(nums[i] < nums[j]): new.append(nums[i]) i += 1 else: new.append(nums[j]) j += 1 if(i > mid): while(j <= right): new.append(nums[j]) j += 1 else: while(i <= mid): new.append(nums[i]) i += 1 for i, val in enumerate(new): nums[left+i] = val yield nums <file_sep>def swap(A, i, j): A[i], A[j] = A[j], A[i] def quick_sort(nums, lo, hi): if(lo >= hi): return # pivot piv = nums[hi] pivindx = lo for i in range(lo, hi): if(nums[i] < piv): swap(nums, i, pivindx) pivindx += 1 yield nums swap(nums, hi, pivindx) yield nums yield from quick_sort(nums, lo, pivindx-1) yield from quick_sort(nums, pivindx+1, hi) <file_sep>import random import matplotlib.pyplot as plt import matplotlib.animation as anim from bubble_s import bubble_sort from heap_s import heap_sort from shell_s import shell_sort from insertion_s import insertion_sort from selection_s import selection_sort from merge_s import merge_sort from quick_s import quick_sort n_elements = int(input('Enter number of elements: ')) alg_choice = int(input('Choose algorithm: \n 1. Bubble Sort ' '\n 2. Heapify Sort \n 3. Shell Sort \n 4. Insertion Sort' '\n 5. Selection Sort \n 6. Merge Sort \n 7. Quick Sort \n')) array = [i + 1 for i in range(n_elements)] random.shuffle(array) if(alg_choice == 1): title = 'Bubble Sort' algo = bubble_sort(array) elif(alg_choice == 2): title = 'Heapify Sort' algo = heap_sort(array) elif(alg_choice == 3): title = 'Shell Sort' algo = shell_sort(array) elif(alg_choice == 4): title = 'Insertion Sort' algo = insertion_sort(array) elif(alg_choice == 5): title = 'Selection Sort' algo = selection_sort(array) elif(alg_choice == 6): title = 'Merge Sort' algo = merge_sort(array, 0, n_elements-1) elif(alg_choice == 7): title = 'Merge Sort' algo = quick_sort(array, 0, n_elements-1) fig, ax = plt.subplots() ax.set_title(title) bar_rec = ax.bar(range(len(array)), array, align='edge') ax.set_xlim(0, n_elements) ax.set_ylim(0, int(n_elements * 1.1)) text = ax.text(0.02, 0.95, "", transform=ax.transAxes) epochs = [0] def update_plot(array, rec, epochs): for rec, val in zip(rec, array): rec.set_height(val) epochs[0] += 1 text.set_text("No.of operations :{}".format(epochs[0])) anima = anim.FuncAnimation(fig, func=update_plot, fargs=(bar_rec, epochs), frames=algo, interval=1, repeat=False) plt.show()
07739c32dd98c7cd3de33eeeba1605b058b05058
[ "Markdown", "Python" ]
5
Python
iaslyk/sort_visualizer
1bf97e3500dd2758574bef145c99c4e8ddfdd12f
476e168863d076c5d628b54a90870b1a88e60622
refs/heads/master
<repo_name>akshaymnair/CurrencyConverter<file_sep>/src/LiveExchangeRates.java public class LiveExchangeRates extends Currency { private int convertFrom_CurrencyID = 0; private int convertTo_CurrencyID = 1; private Currency currency; private CurrencyConverter currencyConverter; public double calculateExchangeRate() { return 0; } }
5fc83926272d12a64833572acbf43a8171256516
[ "Java" ]
1
Java
akshaymnair/CurrencyConverter
b3646cadbd64619e64f12f2fd4b7ce849fb0fe87
19b0898bd3edbd00b8d0e6f4f116eef3c95155e0
refs/heads/master
<file_sep>const sizeUp = document.querySelector('.size-up'); const sizeDown = document.querySelector('.size-down'); const color = document.querySelector('.color'); const text = document.querySelector('p'); let i = 20; sizeUp.addEventListener('click', function () { i += 5; text.style.fontSize = i + 'px'; }) sizeDown.addEventListener('click', function () { i -= 5; text.style.fontSize = i + 'px'; }) color.addEventListener('click', function () { text.style.color = 'gold'; })<file_sep># js-text-resizing JavaScript text resizing exercise
16fdfc980392872581ceaa85a3538676c028c6a0
[ "JavaScript", "Markdown" ]
2
JavaScript
emzys/js-text-resizing
4c750e738c20dd9eb4fd79069a5c8ef509958684
061051220d75f823e446491ffb6e8193df6651ec
refs/heads/master
<repo_name>Ajeky/CRASINVENT<file_sep>/src/main/java/com/salesianostriana/damcrasinvent/servicios/UsuarioEmpresaServicio.java /** * */ package com.salesianostriana.damcrasinvent.servicios; import org.springframework.stereotype.Service; import com.salesianostriana.damcrasinvent.model.UsuarioEmpresa; import com.salesianostriana.damcrasinvent.repository.UsuarioEmpresaRepository; import com.salesianostriana.damcrasinvent.servicios.base.BaseService; /** * @author amarquez * */ @Service public class UsuarioEmpresaServicio extends BaseService<UsuarioEmpresa, Long, UsuarioEmpresaRepository> { public UsuarioEmpresa buscarPorEmail(String email) { return repositorio.findFirstByEmail(email); } } <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/controller/package-info.java /** * <h1>Clases Controller del proyecto</h1> * <p> * Clases que controlan el redireccionamiento de las peticiones de los usuarios * a las plantillas convenientes. Gestionan además las peticiones GET y PUSH de * los formularios. * </p> * * @author <NAME> */ package com.salesianostriana.damcrasinvent.controller;<file_sep>/src/main/java/com/salesianostriana/damcrasinvent/model/PayPal.java /** * */ package com.salesianostriana.damcrasinvent.model; import java.util.List; import javax.persistence.Entity; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; /** * Clase pojo del objeto PayPal. Para más información visitar la clase * MetodosPago {@link com.salesianostriana.damcrasinvent.model.MetodosPago} * * @author <NAME> * */ @Getter @Setter @NoArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) @Entity public class PayPal extends MetodosPago { /** * Correo asociado a la cuenta de PayPal */ private String correo; /** * Constructor con el único atributo de la clase. No debería hacer falta, está * como colchón de seguridad. */ public PayPal(String correo) { this.correo = correo; } } <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/model/package-info.java /** * <h1>Clases model del proyecto</h1> * <p> * Clases pojo de los objetos del proyecto. Se encargan de especificar el id, * las herencias y asociaciones de las entidades de la base de datos * </p> * * @author <NAME> */ package com.salesianostriana.damcrasinvent.model;<file_sep>/src/main/java/com/salesianostriana/damcrasinvent/servicios/ConceptosServicio.java /** * */ package com.salesianostriana.damcrasinvent.servicios; import org.springframework.stereotype.Service; import com.salesianostriana.damcrasinvent.model.Conceptos; import com.salesianostriana.damcrasinvent.repository.ConceptosRepository; import com.salesianostriana.damcrasinvent.servicios.base.BaseService; /** * @author amarquez * */ @Service public class ConceptosServicio extends BaseService<Conceptos, Long, ConceptosRepository>{ } <file_sep>/src/main/resources/static/js/registro.js $(document).ready(function() { $('.input').focus(function() { $(this).parent().find(".label-txt").addClass('label-active'); }); $(".input").focusout(function() { if ($(this).val() == '') { $(this).parent().find(".label-txt").removeClass('label-active'); } ; }); }); var password = document.getElementById("password"), confirm_password = document .getElementById("confirm_password"); var check = function() { if (document.getElementById('password').value == document .getElementById('confirm_password').value) { document.getElementById('message').style.color = 'green'; document.getElementById('message').innerHTML = 'matching'; } else { document.getElementById('message').style.color = 'red'; document.getElementById('message').innerHTML = 'not matching'; } } password.onchange = validatePassword; password.onkeyup = validatePassword; confirm_password.onchange = validatePassword; confirm_password.onkeyup = validatePassword;<file_sep>/src/main/java/com/salesianostriana/damcrasinvent/controller/InventController.java /** * */ package com.salesianostriana.damcrasinvent.controller; import java.security.Principal; import java.util.List; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import com.salesianostriana.damcrasinvent.formbeans.SearchBean; import com.salesianostriana.damcrasinvent.model.Campos; import com.salesianostriana.damcrasinvent.model.Conceptos; import com.salesianostriana.damcrasinvent.model.Invent; import com.salesianostriana.damcrasinvent.model.Pager; import com.salesianostriana.damcrasinvent.model.Usuario; import com.salesianostriana.damcrasinvent.model.ValoresCampos; import com.salesianostriana.damcrasinvent.servicios.CamposServicio; import com.salesianostriana.damcrasinvent.servicios.ConceptosServicio; import com.salesianostriana.damcrasinvent.servicios.InventServicio; import com.salesianostriana.damcrasinvent.servicios.UsuarioServicio; import com.salesianostriana.damcrasinvent.servicios.ValoresCamposServicio; /** * Clase que controla las peticiones GET y POST que tienen que ver con objetos * Invent {@link com.salesianostriana.damcrasinvent.model.Invent}. Los atributos * de la clase son los servicios necesarios para gestionar las peticiones que se * realizan. * * @author <NAME> * */ @Controller public class InventController { private InventServicio inventservicio; private UsuarioServicio usuarioservicio; private ConceptosServicio concepservi; private CamposServicio campservi; private ValoresCamposServicio valorservi; private static final int BUTTONS_TO_SHOW = 5; private static final int INITIAL_PAGE = 0; private static final int INITIAL_PAGE_SIZE = 5; private static final int[] PAGE_SIZES = { 5, 10, 20 }; public InventController(InventServicio servicio, UsuarioServicio usuarioservicio, ConceptosServicio concepservi, CamposServicio campservi, ValoresCamposServicio valorservi) { this.inventservicio = servicio; this.usuarioservicio = usuarioservicio; this.concepservi = concepservi; this.campservi = campservi; this.valorservi = valorservi; } /** * Método que gestiona las peticiones de recibir la lista de inventarios. Se * sustituyó a mitad de desarrollo por otro método que sólo muestra los * inventarios que pertenezcan al usuario que realiza la petición * * @deprecated * @param model Como modelo se le pasa la lista de inventarios a mostrar * @return La plantilla de listar inventarios */ @GetMapping({ "/inventList" }) public String listarTodo(Model model) { model.addAttribute("lista", inventservicio.findAll()); return "listas/listaInvent"; } /** * Método que controla la petición GET del formulario de creación de * Inventarios. * * @param model Se le pasan como modelos un inventario vacío al que se le * introducirán los datos en el formulario y y el Usuario al que * pertenece dicho Inventario * @param id ID del usuario al que pertenece el inventario * @return La plantilla de creación de Inventario */ @GetMapping("/newInvent/{id}") public String mostrarFormulario(Model model, @PathVariable("id") long id, HttpSession session, HttpServletRequest request, ModelMap modelMap) { Usuario u = usuarioservicio.findById(id); if (request.isUserInRole("ROLE_USER") && !u.getInvents().isEmpty()) { return "limiteInvents"; } else { model.addAttribute("usuario", u); model.addAttribute("invent", new Invent()); return "forms/crearInvent"; } } /** * Método que controla la petición POST de creación de inventarios. Dependiendo * del rol del usuario lo devuelve a una dirección u otra * * @param i Inventario a crear * @param id ID del usuario al que pertenece el inventario * @return Página en la que estaba el usuario al acceder al formulario */ @PostMapping("/newInvent/submit/{id}") public String procesarFormulario(@ModelAttribute("invent") Invent i, HttpSession session, HttpServletRequest request, ModelMap modelMap, @PathVariable("id") long id) { i.setUsuario(usuarioservicio.findById(id)); inventservicio.add(i); if (request.isUserInRole("ROLE_ADMIN")) { return "redirect:/admin/detalleUsuario/" + id; } else if (request.isUserInRole("ROLE_USER") || request.isUserInRole("ROLE_PREMIUMUSER")) { return "redirect:/user/inventList"; } else { return "redirect:/acceso-denegado"; } } /** * Método que gestiona la petición GET del formulario de edición del Inventario. * * @param id ID del inventario a editar * @param model Como modelo se pasa el inventario a editar * @return Si el inventario es nulo devuelve al usuario a la lista de * inventarios, si no, devuelve la plantilla de creación del inventario */ @GetMapping("/editInvent/{id}") public String editarPorID(@PathVariable("id") long id, Model model) { Invent invEdit = inventservicio.findById(id); Usuario usuario = invEdit.getUsuario(); if (invEdit != null) { model.addAttribute("invent", invEdit); model.addAttribute("usuario", usuario); return "forms/crearInvent"; } else { return "redirect:/user/inventList"; } } /** * Método que gestiona la petición POST de la edición de inventarios * * @param i inventario a editar * @param principal Objeto que devuelve el usuario que ha realizado la petición * @return La lista de inventarios del usuario */ @PostMapping("/editInvent/submit") public String procesarEdicion(@ModelAttribute("invent") Invent i, Principal principal) { i.setUsuario(usuarioservicio.buscarPorEmail(principal.getName())); inventservicio.edit(i); return "redirect:/user/inventList"; } /** * Método que maneja la plantilla de los detalles de un inventario. En ella se * ve el nombre del inventario y los conceptos que contiene. Se pueden añadir * conceptos nuevos. * * @param id ID del invent a mostrar. * @param model Como modelo se pasan el invent a mostrar y una lista con los * conceptos que contiene * @return Redirige al usuario a la página de detalles del inventario, o, en * caso de que se pase un inventario nulo, a la lista de inventarios. */ @GetMapping("/detalleInvent/{id}") public String detalleInventario(@PathVariable("id") long id, Model model) { Invent i = inventservicio.findById(id); List<Conceptos> c = i.getConceptos(); Usuario u = i.getUsuario(); if (i != null) { model.addAttribute("invent", i); model.addAttribute("conceptos", c); model.addAttribute("usuario", u); return "listas/inventarioDetalle"; } else { return "redirect:/user/inventList"; } } /** * Método que gestiona la petición de borrar un inventario. Borra todos los * conceptos, campos y valores que estuvieran relacionados con el inventario en * cuestión * * @param id ID del inventario a borrar * @return Dependiendo del rol del usuario lo redirige a la lista de inventarios * si es un usuario o al detalle del usuario al que pertenecía el * inventario borrado si es un admin */ @GetMapping("/deleteInvent/{id}") public String borrar(@PathVariable("id") long id, HttpSession session, HttpServletRequest request, ModelMap modelMap) { Invent invent = inventservicio.findById(id); long idUsuario = invent.getUsuario().getId(); for (Conceptos concepto : invent.getConceptos()) { for (Campos campo : concepto.getCampos()) { for (ValoresCampos valor : campo.getValoresCampos()) { valorservi.delete(valor); } campservi.delete(campo); } concepservi.delete(concepto); } inventservicio.delete(invent); if (request.isUserInRole("ADMIN")) { return "redirect:/admin/detalleUsuario/" + idUsuario; } else { return "redirect:/user/inventList"; } } /** * Método que gestiona la plantilla de lista de inventarios que pertenecen a un * usuario * * @param model como métodos se pasan un motor de búsqueda (inservible por * ahora), el usuario al que pertenecen los inventarios y la * lista de inventarios a mostrar * @param principal Objeto que devuelve los datos de login del usuario que * realiza la petición * @return La plantilla de la lista de inventarios */ /* * @GetMapping("/user/inventList") public String mostrarInventsUsuario(Model * model, Principal principal) { model.addAttribute("searchForm", new * SearchBean()); * * Usuario u = usuarioservicio.buscarPorEmail(principal.getName()); * * List<Invent> inventList = * inventservicio.encontrarInventariosDeUnUsuario(u.getId()); * * model.addAttribute("usuario", u); model.addAttribute("lista", inventList); * return "/listas/listaInvent"; } */ /** * Método que maneja la búsqueda de inventarios. Está en desarrollo, por lo que * por ahora es inservible */ @PostMapping("/search") public String searchProducto(@ModelAttribute("searchForm") SearchBean searchBean, Model model) { model.addAttribute("invent", new Invent()); model.addAttribute("lista", inventservicio.findByNombre(searchBean.getSearch())); return "/listas/listaInvent"; } /** * Método que se encarga de la paginación de inventarios. Es muy parecido al de * ejemplo excepto porque busca por usuario además de por nombre ya que solo * enseña los inventarios que pertenecen al usuario logeado en el momento */ @GetMapping({ "/inventsbuscados", "/user/inventList" }) public String mostrarInventsUsuario(@RequestParam("pageSize") Optional<Integer> pageSize, @RequestParam("page") Optional<Integer> page, @RequestParam("nombre") Optional<String> nombre, Model model, Principal principal) { Usuario u = usuarioservicio.buscarPorEmail(principal.getName()); if (u.isAdmin()) { return "redirect:/"; } // Evalúa el tamaño de página. Si el parámetro es "nulo", devuelve // el tamaño de página inicial. int evalPageSize = pageSize.orElse(INITIAL_PAGE_SIZE); // Calcula qué página se va a mostrar. Si el parámetro es "nulo" o menor // que 0, se devuelve el valor inicial. De otro modo, se devuelve el valor // del parámetro decrementado en 1. int evalPage = (page.orElse(0) < 1) ? INITIAL_PAGE : page.get() - 1; String evalNombre = nombre.orElse(null); Page<Invent> invents = null; // UserDetails u = (UserDetails) principal; if (evalNombre == null) { invents = inventservicio.findByUsuarioPageable(u, PageRequest.of(evalPage, evalPageSize)); } else { invents = inventservicio.findByUsuarioAndNombreIgnoreCasePageable(u, evalNombre, PageRequest.of(evalPage, evalPageSize)); } // Obtenemos la página definida por evalPage y evalPageSize de objetos de // nuestro modelo // Page<Producto> products = // productService.findAllPageable(PageRequest.of(evalPage, evalPageSize)); // Creamos el objeto Pager (paginador) indicando los valores correspondientes. // Este sirve para que la plantilla sepa cuantas páginas hay en total, cuantos // botones // debe mostrar y cuál es el número de objetos a dibujar. Pager pager = new Pager(invents.getTotalPages(), invents.getNumber(), BUTTONS_TO_SHOW); model.addAttribute("usuario", u); model.addAttribute("lista", invents); model.addAttribute("selectedPageSize", evalPageSize); model.addAttribute("pageSizes", PAGE_SIZES); model.addAttribute("pager", pager); return "listas/listaInvent"; } } <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/controller/ValoresCamposController.java /** * */ package com.salesianostriana.damcrasinvent.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import com.salesianostriana.damcrasinvent.model.ValoresCampos; import com.salesianostriana.damcrasinvent.servicios.CamposServicio; import com.salesianostriana.damcrasinvent.servicios.ValoresCamposServicio; /** * Clase que controla las peticiones GET y POST que tienen que ver con objetos * ValoresCampos {@link com.salesianostriana.damcrasinvent.model.ValoresCampos}. * Los atributos de la clase son los servicios necesarios para gestionar las * peticiones que se realizan. * * @author <NAME> * */ @Controller public class ValoresCamposController { private ValoresCamposServicio valorservi; private CamposServicio campservi; public ValoresCamposController(ValoresCamposServicio valorservi, CamposServicio campservi) { this.valorservi = valorservi; this.campservi = campservi; } /** * Método que controla la petición GET del formulario de creación de valores. * * @param model Se le pasan como modelos un valor vacío al que se le * introducirán los datos en el formulario y y el campo al que * pertenece dicho valor * @param id ID del campo al que pertenece el valor * @return La plantilla de creación de Valores */ @GetMapping("/newValor/{id}") public String nuevoValor(Model model, @PathVariable("id") long id) { String fecha = "Date"; String integer = "Integer"; String string ="String"; model.addAttribute("valorCampo", new ValoresCampos()); model.addAttribute("campo", campservi.findById(id)); model.addAttribute("fecha", fecha); model.addAttribute("integer", integer); model.addAttribute("string", string); return "forms/crearValor"; } /** * Método que controla la petición POST de creación de un valor * * @param v Valor a editar * @param id ID del campo al que pertenece el valor * @return La plantilla de detalles del concepto */ @PostMapping("/newValor/submit/{id}") public String procesarNuevoValor(@ModelAttribute("valorCampo") ValoresCampos v, @PathVariable("id") long id) { v.setCampo(campservi.findById(id)); v.setConcepto(v.getCampo().getConcepto()); valorservi.add(v); return "redirect:/detalleCampo/" + id; } /** * Método que gestiona la petición GET del formulario de edición del valor. * * @param id ID del valor a editar * @param model Como modelo se pasan el valor a editar y el campo al que * pertenece * @return Si el valor es nulo devuelve al usuario a la portada, si no, devuelve * la plantilla de creación del valor */ @GetMapping("/editValor/{id}") public String editarValor(@PathVariable("id") long id, Model model) { ValoresCampos v = valorservi.findById(id); if (v != null) { model.addAttribute("valorCampo", v); model.addAttribute("campo", v.getCampo()); return "forms/crearValor"; } else { return "redirect:/"; } } /** * Método que gestiona la petición POST de la edición de valores. * * @param v valor a editar * @param id ID del campo al que pertenece el campo * @return La plantilla de detalles del Campo */ @PostMapping("/editValor/submit/{id}") public String procesarEdicionCampo(@ModelAttribute("valorCampo") ValoresCampos v, @PathVariable("id") long id) { v.setCampo(campservi.findById(id)); v.setConcepto(v.getCampo().getConcepto()); valorservi.edit(v); return "redirect:/detalleCampo/" + id; } /** * Método que gestiona la petición de borrar un valor. * * @param id ID del valor a borrar * @return La plantilla de detalles del campo al que pertenecía el valor */ @GetMapping("/deleteValor/{id}") public String borrarValor(@PathVariable("id") long id) { long campoID = valorservi.findById(id).getCampo().getId(); valorservi.deleteById(id); return "redirect:/detalleCampo/" + campoID; } } <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/servicios/CamposServicio.java /** * */ package com.salesianostriana.damcrasinvent.servicios; import org.springframework.stereotype.Service; import com.salesianostriana.damcrasinvent.model.Campos; import com.salesianostriana.damcrasinvent.repository.CamposRepository; import com.salesianostriana.damcrasinvent.servicios.base.BaseService; /** * @author amarquez * */ @Service public class CamposServicio extends BaseService<Campos, Long, CamposRepository>{ } <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/controller/MetodosPagoController.java /** * */ package com.salesianostriana.damcrasinvent.controller; import java.security.Principal; import java.time.LocalDate; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import com.salesianostriana.damcrasinvent.excepciones.ExcepcionCaducidad; import com.salesianostriana.damcrasinvent.model.PayPal; import com.salesianostriana.damcrasinvent.model.Tarjeta; import com.salesianostriana.damcrasinvent.model.Transferencia; import com.salesianostriana.damcrasinvent.model.UsuarioEmpresa; import com.salesianostriana.damcrasinvent.servicios.MetodosPagoServicio; import com.salesianostriana.damcrasinvent.servicios.UsuarioEmpresaServicio; /** * @author <NAME> * */ @Controller public class MetodosPagoController { private MetodosPagoServicio metodosservicio; private UsuarioEmpresaServicio empresaservi; public MetodosPagoController(MetodosPagoServicio metodosservicio, UsuarioEmpresaServicio empresaservi) { this.metodosservicio = metodosservicio; this.empresaservi = empresaservi; } @GetMapping("/tarjeta") public String nuevaTarjeta(Model model) { model.addAttribute("tarjeta", new Tarjeta()); return "forms/crearTarjeta"; } @PostMapping("/tarjeta/submit") public String submitTarjeta(@ModelAttribute("tarjeta") Tarjeta t, HttpSession session, HttpServletRequest request, ModelMap modelMap) throws ExcepcionCaducidad { UsuarioEmpresa u = empresaservi.buscarPorEmail(request.getUserPrincipal().getName()); LocalDate hoy = LocalDate.now(); if (t.getFechaCad().isBefore(hoy)) { throw new ExcepcionCaducidad("Fecha anterior a la actual"); } else { t.getUsuarios().add(u); u.getMetodosPago().add(t); metodosservicio.add(t); if (request.isUserInRole("ROLE_PREMIUMUSER")) { return "redirect:/"; } else { return "redirect:/logout"; } } } @GetMapping("/transferencia") public String nuevaTransferencia(Model model) { model.addAttribute("transferencia", new Transferencia()); return "forms/crearTransferencia"; } @PostMapping("/transferencia/submit") public String submitTransferencia(@ModelAttribute("transferencia") Transferencia t, HttpSession session, HttpServletRequest request, ModelMap modelMap) { UsuarioEmpresa u = empresaservi.buscarPorEmail(request.getUserPrincipal().getName()); t.getUsuarios().add(u); u.getMetodosPago().add(t); metodosservicio.add(t); if (request.isUserInRole("ROLE_PREMIUMUSER")) { return "redirect:/"; } else { return "redirect:/logout"; } } @GetMapping("/paypal") public String nuevoPayPal(Model model) { model.addAttribute("paypal", new PayPal()); return "forms/crearPayPal"; } @PostMapping("/paypal/submit") public String submitPayPal(@ModelAttribute("paypal") PayPal p, HttpSession session, HttpServletRequest request, ModelMap modelMap) { UsuarioEmpresa u = empresaservi.buscarPorEmail(request.getUserPrincipal().getName()); p.getUsuarios().add(u); u.getMetodosPago().add(p); metodosservicio.add(p); if (request.isUserInRole("ROLE_PREMIUMUSER")) { return "redirect:/"; } else { return "redirect:/logout"; } } @GetMapping("/elegirMetodoPago") public String elegirMetodo() { return "/forms/elegirMetodoPago"; } } <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/servicios/InventServicio.java /** * */ package com.salesianostriana.damcrasinvent.servicios; import java.util.ArrayList; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import com.salesianostriana.damcrasinvent.model.Invent; import com.salesianostriana.damcrasinvent.model.Usuario; import com.salesianostriana.damcrasinvent.repository.InventRepository; import com.salesianostriana.damcrasinvent.servicios.base.BaseService; /** * @author amarquez * */ @Service public class InventServicio extends BaseService<Invent, Long, InventRepository>{ public List<Invent> encontrarInventariosDeUnUsuario(long id) { List<Invent> todas = repositorio.findAll(); List<Invent> i = new ArrayList<Invent>(); for (Invent invent : todas) { if (invent.getUsuario().getId() == id) { i.add(invent); } } return i; } public List<Invent> findByNombre(String nombre){ return repositorio.findByNombreContainingIgnoreCase(nombre); } public Page<Invent> findAllPageable(Pageable pageable) { return repositorio.findAll(pageable); } public Page<Invent> findByNombreContainingIgnoreCasePageable(String nombre, Pageable pageable) { return repositorio.findByNombreContainingIgnoreCase(nombre, pageable); } public Page<Invent> findByUsuarioPageable(Usuario usuario, Pageable pageable) { return repositorio.findByUsuario(usuario, pageable); } public Page<Invent> findByUsuarioAndNombreIgnoreCasePageable(Usuario usuario, String nombre, Pageable pageable) { return repositorio.findByUsuarioAndNombreContainingIgnoreCase(usuario, nombre, pageable); } } <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/CrasinventApplication.java package com.salesianostriana.damcrasinvent; import java.util.List; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import com.salesianostriana.damcrasinvent.model.Usuario; import com.salesianostriana.damcrasinvent.servicios.UsuarioServicio; @SpringBootApplication public class CrasinventApplication { public static void main(String[] args) { SpringApplication.run(CrasinventApplication.class, args); } @Bean public CommandLineRunner init(UsuarioServicio servicio, BCryptPasswordEncoder passwordEncoder) { return args -> { List<Usuario> usuarios = servicio.findAll(); for (Usuario u : usuarios) { u.setPassword(passwordEncoder.encode(u.getPassword())); servicio.add(u); } }; } } <file_sep>/doc/com/salesianostriana/damcrasinvent/controller/CamposController.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="es"> <head> <!-- Generated by javadoc (1.8.0_211) on Mon May 27 14:18:21 CEST 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=utf8"> <title>CamposController</title> <meta name="date" content="2019-05-27"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="CamposController"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/CamposController.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/salesianostriana/damcrasinvent/controller/AdminController.html" title="class in com.salesianostriana.damcrasinvent.controller"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../com/salesianostriana/damcrasinvent/controller/ConceptosController.html" title="class in com.salesianostriana.damcrasinvent.controller"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/salesianostriana/damcrasinvent/controller/CamposController.html" target="_top">Frames</a></li> <li><a href="CamposController.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.salesianostriana.damcrasinvent.controller</div> <h2 title="Class CamposController" class="title">Class CamposController</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.salesianostriana.damcrasinvent.controller.CamposController</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>@Controller public class <span class="typeNameLabel">CamposController</span> extends java.lang.Object</pre> <div class="block">Clase que controla las peticiones GET y POST que tienen que ver con objetos Campos <a href="../../../../com/salesianostriana/damcrasinvent/model/Campos.html" title="class in com.salesianostriana.damcrasinvent.model"><code>Campos</code></a>. Los atributos de la clase son los servicios necesarios para gestionar las peticiones que se realizan.</div> <dl> <dt><span class="simpleTagLabel">Author:</span></dt> <dd><NAME>árquez</dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>private <a href="../../../../com/salesianostriana/damcrasinvent/servicios/CamposServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios">CamposServicio</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/salesianostriana/damcrasinvent/controller/CamposController.html#camposservicio">camposservicio</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>private <a href="../../../../com/salesianostriana/damcrasinvent/servicios/ConceptosServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios">ConceptosServicio</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/salesianostriana/damcrasinvent/controller/CamposController.html#concepservi">concepservi</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>private <a href="../../../../com/salesianostriana/damcrasinvent/servicios/ValoresCamposServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios">ValoresCamposServicio</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/salesianostriana/damcrasinvent/controller/CamposController.html#valorservicio">valorservicio</a></span></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../com/salesianostriana/damcrasinvent/controller/CamposController.html#CamposController-com.salesianostriana.damcrasinvent.servicios.CamposServicio-com.salesianostriana.damcrasinvent.servicios.ValoresCamposServicio-com.salesianostriana.damcrasinvent.servicios.ConceptosServicio-">CamposController</a></span>(<a href="../../../../com/salesianostriana/damcrasinvent/servicios/CamposServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios">CamposServicio</a>&nbsp;camposservicio, <a href="../../../../com/salesianostriana/damcrasinvent/servicios/ValoresCamposServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios">ValoresCamposServicio</a>&nbsp;valorservicio, <a href="../../../../com/salesianostriana/damcrasinvent/servicios/ConceptosServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios">ConceptosServicio</a>&nbsp;concepservi)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/salesianostriana/damcrasinvent/controller/CamposController.html#borrarCampo-long-">borrarCampo</a></span>(long&nbsp;id)</code> <div class="block">Método que gestiona la petición de borrar un campo.</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/salesianostriana/damcrasinvent/controller/CamposController.html#detalleConcepto-long-org.springframework.ui.Model-">detalleConcepto</a></span>(long&nbsp;id, org.springframework.ui.Model&nbsp;model)</code> <div class="block">Método que maneja la plantilla de los detalles de un campo.</div> </td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/salesianostriana/damcrasinvent/controller/CamposController.html#editarCampo-long-org.springframework.ui.Model-">editarCampo</a></span>(long&nbsp;id, org.springframework.ui.Model&nbsp;model)</code> <div class="block">Método que gestiona la petición GET del formulario de edición del campo.</div> </td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/salesianostriana/damcrasinvent/controller/CamposController.html#nuevoCampo-org.springframework.ui.Model-long-">nuevoCampo</a></span>(org.springframework.ui.Model&nbsp;model, long&nbsp;id)</code> <div class="block">Método que controla la petición GET del formulario de creación de campos.</div> </td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/salesianostriana/damcrasinvent/controller/CamposController.html#procesarEdicionCampo-com.salesianostriana.damcrasinvent.model.Campos-long-">procesarEdicionCampo</a></span>(<a href="../../../../com/salesianostriana/damcrasinvent/model/Campos.html" title="class in com.salesianostriana.damcrasinvent.model">Campos</a>&nbsp;c, long&nbsp;id)</code> <div class="block">Método que gestiona la petición POST de la edición de campos.</div> </td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/salesianostriana/damcrasinvent/controller/CamposController.html#procesarNuevoCampo-com.salesianostriana.damcrasinvent.model.Campos-long-">procesarNuevoCampo</a></span>(<a href="../../../../com/salesianostriana/damcrasinvent/model/Campos.html" title="class in com.salesianostriana.damcrasinvent.model">Campos</a>&nbsp;c, long&nbsp;id)</code> <div class="block">Método que controla la petición POST de creación de un campo</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="camposservicio"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>camposservicio</h4> <pre>private&nbsp;<a href="../../../../com/salesianostriana/damcrasinvent/servicios/CamposServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios">CamposServicio</a> camposservicio</pre> </li> </ul> <a name="valorservicio"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>valorservicio</h4> <pre>private&nbsp;<a href="../../../../com/salesianostriana/damcrasinvent/servicios/ValoresCamposServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios">ValoresCamposServicio</a> valorservicio</pre> </li> </ul> <a name="concepservi"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>concepservi</h4> <pre>private&nbsp;<a href="../../../../com/salesianostriana/damcrasinvent/servicios/ConceptosServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios">ConceptosServicio</a> concepservi</pre> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="CamposController-com.salesianostriana.damcrasinvent.servicios.CamposServicio-com.salesianostriana.damcrasinvent.servicios.ValoresCamposServicio-com.salesianostriana.damcrasinvent.servicios.ConceptosServicio-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>CamposController</h4> <pre>public&nbsp;CamposController(<a href="../../../../com/salesianostriana/damcrasinvent/servicios/CamposServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios">CamposServicio</a>&nbsp;camposservicio, <a href="../../../../com/salesianostriana/damcrasinvent/servicios/ValoresCamposServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios">ValoresCamposServicio</a>&nbsp;valorservicio, <a href="../../../../com/salesianostriana/damcrasinvent/servicios/ConceptosServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios">ConceptosServicio</a>&nbsp;concepservi)</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="detalleConcepto-long-org.springframework.ui.Model-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>detalleConcepto</h4> <pre>@GetMapping(value="/detalleCampo/{id}") public&nbsp;java.lang.String&nbsp;detalleConcepto(@PathVariable(value="id") long&nbsp;id, org.springframework.ui.Model&nbsp;model)</pre> <div class="block">Método que maneja la plantilla de los detalles de un campo. En ella se ve el nombre del campo y los valores que contiene. Se pueden añadir valores nuevos.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>id</code> - ID del campo a mostrar.</dd> <dd><code>model</code> - Como modelo se pasan el campo a mostrar y una lista con los valores que contiene</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>Redirige al usuario a la página de detalles del campo, o, en caso de que se pase un campo nulo, a la lista de inventarios.</dd> </dl> </li> </ul> <a name="nuevoCampo-org.springframework.ui.Model-long-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>nuevoCampo</h4> <pre>@GetMapping(value="/newCampo/{id}") public&nbsp;java.lang.String&nbsp;nuevoCampo(org.springframework.ui.Model&nbsp;model, @PathVariable(value="id") long&nbsp;id)</pre> <div class="block">Método que controla la petición GET del formulario de creación de campos.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>model</code> - Se le pasan como modelos un campo vacío al que se le introducirán los datos en el formulario y y el Concepto al que pertenece dicho campo</dd> <dd><code>id</code> - ID del concepto al que pertenece el campo</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>La plantilla de creación de Campo</dd> </dl> </li> </ul> <a name="procesarNuevoCampo-com.salesianostriana.damcrasinvent.model.Campos-long-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>procesarNuevoCampo</h4> <pre>@PostMapping(value="/newCampo/submit/{id}") public&nbsp;java.lang.String&nbsp;procesarNuevoCampo(@ModelAttribute(value="campo") <a href="../../../../com/salesianostriana/damcrasinvent/model/Campos.html" title="class in com.salesianostriana.damcrasinvent.model">Campos</a>&nbsp;c, @PathVariable(value="id") long&nbsp;id)</pre> <div class="block">Método que controla la petición POST de creación de un campo</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>c</code> - Campo a editar</dd> <dd><code>id</code> - ID del concepto al que pertenece el campo</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>La plantilla de detalles del concepto</dd> </dl> </li> </ul> <a name="editarCampo-long-org.springframework.ui.Model-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>editarCampo</h4> <pre>@GetMapping(value="/editCampo/{id}") public&nbsp;java.lang.String&nbsp;editarCampo(@PathVariable(value="id") long&nbsp;id, org.springframework.ui.Model&nbsp;model)</pre> <div class="block">Método que gestiona la petición GET del formulario de edición del campo.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>id</code> - ID del campo a editar</dd> <dd><code>model</code> - Como modelo se pasan el campo a editar y el concepto al que pertenece</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>Si el campo es nulo devuelve al usuario a la portada, si no, devuelve la plantilla de creación del campo</dd> </dl> </li> </ul> <a name="procesarEdicionCampo-com.salesianostriana.damcrasinvent.model.Campos-long-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>procesarEdicionCampo</h4> <pre>@PostMapping(value="/editCampo/submit/{id}") public&nbsp;java.lang.String&nbsp;procesarEdicionCampo(@ModelAttribute(value="campo") <a href="../../../../com/salesianostriana/damcrasinvent/model/Campos.html" title="class in com.salesianostriana.damcrasinvent.model">Campos</a>&nbsp;c, @PathVariable(value="id") long&nbsp;id)</pre> <div class="block">Método que gestiona la petición POST de la edición de campos.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>c</code> - campo a editar</dd> <dd><code>id</code> - ID del concepto al que pertenece el campo</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>La plantilla de detalles del concepto</dd> </dl> </li> </ul> <a name="borrarCampo-long-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>borrarCampo</h4> <pre>@GetMapping(value="/deleteCampo/{id}") public&nbsp;java.lang.String&nbsp;borrarCampo(@PathVariable(value="id") long&nbsp;id)</pre> <div class="block">Método que gestiona la petición de borrar un campo. Borra todos los valores que estuvieran relacionados con el campo en cuestión</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>id</code> - ID del campo a borrar</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>La plantilla de detalles del concepto al que pertenecía el campo</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/CamposController.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/salesianostriana/damcrasinvent/controller/AdminController.html" title="class in com.salesianostriana.damcrasinvent.controller"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../com/salesianostriana/damcrasinvent/controller/ConceptosController.html" title="class in com.salesianostriana.damcrasinvent.controller"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/salesianostriana/damcrasinvent/controller/CamposController.html" target="_top">Frames</a></li> <li><a href="CamposController.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html> <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/repository/MetodosPagoRepository.java /** * */ package com.salesianostriana.damcrasinvent.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.salesianostriana.damcrasinvent.model.MetodosPago; /** * @author <NAME> * */ public interface MetodosPagoRepository extends JpaRepository<MetodosPago, Long> { } <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/model/Campos.java /** * */ package com.salesianostriana.damcrasinvent.model; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import lombok.Data; import lombok.NoArgsConstructor; /** * Clase pojo del objeto Campos. Cada campo será una columna de una tabla * {@link com.salesianostriana.damcrasinvent.model.Conceptos} de una base de * datos o inventario {@link com.salesianostriana.damcrasinvent.model.Invent}. * Los valores de las columnas se especifican en la clase Valores Campos * {@link com.salesianostriana.damcrasinvent.model.ValoresCampos} * * @author <NAME> * */ @Data @NoArgsConstructor @Entity public class Campos { /** * ID que identifica a cada Campo en la base de datos. Se autogenera con una * secuencia. */ @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; /** * Nombre de la columna */ private String nombre; /** * Tipo de dato que tendrán los valores de la columna */ private String tipo; /** * Tabla a la que pertenece la columna */ @ManyToOne private Conceptos concepto; /** * Lista de valores que contiene la columna */ @OneToMany(mappedBy = "campo") private List<ValoresCampos> valoresCampos; // Métodos Helper public void addValorCampo(ValoresCampos v) { this.valoresCampos.add(v); } public void removeValorCampo(ValoresCampos v) { this.valoresCampos.remove(v); v.setCampo(null); } } <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/model/Conceptos.java /** * */ package com.salesianostriana.damcrasinvent.model; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import lombok.Data; import lombok.NoArgsConstructor; /** * Clase pojo del objeto Conceptos. Cada concepto será una tabla dentro de un * inventario o base de datos * {@link com.salesianostriana.damcrasinvent.model.Invent}. Las columnas de la * tabla se especifican en la clase Campos * {@link com.salesianostriana.damcrasinvent.model.Campos}, y los valores de * cada campo en la clase ValoresCampos * {@link com.salesianostriana.damcrasinvent.model.ValoresCampos} * * @author <NAME> * */ @Data @NoArgsConstructor @Entity public class Conceptos { /** * ID que identifica cada Concepto en la base de datos. Se autogenera con una * secuencia. */ @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; /** * Nombre de la tabla */ private String nombre; /** * Lista de las columnas que contiene la tabla */ @OneToMany(mappedBy = "concepto") private List<Campos> campos; // Métodos Helper public void addCampo(Campos c) { this.campos.add(c); } public void removeCampo(Campos c) { this.campos.remove(c); c.setConcepto(null); } /** * Lista de los valores que contienen las columnas de la tabla. */ @OneToMany(mappedBy = "concepto") private List<ValoresCampos> valoresCampos; // Métodos Helper public void addValorCampo(ValoresCampos v) { this.valoresCampos.add(v); } public void removeValorCampo(ValoresCampos v) { this.valoresCampos.remove(v); v.setConcepto(null); } /** * Inventario al que pertenece la tabla */ @ManyToOne private Invent invent; } <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/repository/InventRepository.java package com.salesianostriana.damcrasinvent.repository; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import com.salesianostriana.damcrasinvent.model.Invent; import com.salesianostriana.damcrasinvent.model.Usuario; /** * Clase que gestiona las operaciones relacionadas con la clase Invent * {@link com.salesianostriana.damcrasinvent.model.Invent} * * @author <NAME> * */ public interface InventRepository extends JpaRepository<Invent, Long> { /** * Método que busca un inventario a partir de su nombre, ignorando las * mayúsculas. De momento no está implementado, por lo que es inservible. * * @param nombre Nombre del inventario a buscar * @return Lista de usuarios cuyo nombre coincide con la búsqueda. */ public List<Invent> findByNombreContainingIgnoreCase(String nombre); public Page<Invent> findByNombreContainingIgnoreCase(String nombre, Pageable pageable); public Page<Invent> findByUsuario(Usuario usuario, Pageable pageable); public Page<Invent> findByUsuarioAndNombreContainingIgnoreCase(Usuario usuario, String nombre, Pageable pageable); } <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/controller/AdminController.java /** * */ package com.salesianostriana.damcrasinvent.controller; import java.util.List; import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.salesianostriana.damcrasinvent.formbeans.SearchBean; import com.salesianostriana.damcrasinvent.model.Campos; import com.salesianostriana.damcrasinvent.model.Conceptos; import com.salesianostriana.damcrasinvent.model.HistoricoUsuarios; import com.salesianostriana.damcrasinvent.model.Invent; import com.salesianostriana.damcrasinvent.model.Pager; import com.salesianostriana.damcrasinvent.model.Usuario; import com.salesianostriana.damcrasinvent.model.ValoresCampos; import com.salesianostriana.damcrasinvent.servicios.CamposServicio; import com.salesianostriana.damcrasinvent.servicios.ConceptosServicio; import com.salesianostriana.damcrasinvent.servicios.HistoricoUsuariosServicio; import com.salesianostriana.damcrasinvent.servicios.InventServicio; import com.salesianostriana.damcrasinvent.servicios.UsuarioEmpresaServicio; import com.salesianostriana.damcrasinvent.servicios.UsuarioServicio; import com.salesianostriana.damcrasinvent.servicios.ValoresCamposServicio; /** * Clase que controla las peticiones GET y POST que realizan los * administradores. Los atributos de la clase son todos los servicios necesarios * para gestionar las peticiones que se realizan. * * @author <NAME> * */ @Controller @RequestMapping("/admin") public class AdminController { private UsuarioServicio userServi; private UsuarioEmpresaServicio empServi; private InventServicio invServi; private ConceptosServicio concepservi; private CamposServicio campservi; private ValoresCamposServicio valorservi; private HistoricoUsuariosServicio histoServi; private static final int BUTTONS_TO_SHOW = 5; private static final int INITIAL_PAGE = 0; private static final int INITIAL_PAGE_SIZE = 5; private static final int[] PAGE_SIZES = { 5, 10, 20 }; public AdminController(UsuarioServicio userServi, UsuarioEmpresaServicio empServi, InventServicio invServi, ConceptosServicio concepservi, CamposServicio campservi, ValoresCamposServicio valorservi, HistoricoUsuariosServicio histoServi) { this.userServi = userServi; this.empServi = empServi; this.invServi = invServi; this.concepservi = concepservi; this.campservi = campservi; this.valorservi = valorservi; this.histoServi = histoServi; } /** * Método que maneja la portada que verán los admins al logearse o pulsar la * tecla inicio. * * @param model Se le pasa como modelo una lista con todos los usuarios * existentes en la base de datos * @return La plantilla de la portada para los admins */ @GetMapping({"/", "/buscarUser"}) public String portada(@RequestParam("pageSize") Optional<Integer> pageSize, @RequestParam("page") Optional<Integer> page, @RequestParam("email") Optional<String> email, Model model) { // Evalúa el tamaño de página. Si el parámetro es "nulo", devuelve // el tamaño de página inicial. int evalPageSize = pageSize.orElse(INITIAL_PAGE_SIZE); // Calcula qué página se va a mostrar. Si el parámetro es "nulo" o menor // que 0, se devuelve el valor inicial. De otro modo, se devuelve el valor // del parámetro decrementado en 1. int evalPage = (page.orElse(0) < 1) ? INITIAL_PAGE : page.get() - 1; String evalNombre = email.orElse(null); Page<Usuario> usuarios = null; if (evalNombre == null) { usuarios = userServi.findAllPageable(PageRequest.of(evalPage, evalPageSize)); } else { usuarios = userServi.findByEmailPageable(evalNombre, PageRequest.of(evalPage, evalPageSize)); } Pager pager = new Pager(usuarios.getTotalPages(), usuarios.getNumber(), BUTTONS_TO_SHOW); model.addAttribute("usuarios", usuarios); model.addAttribute("selectedPageSize", evalPageSize); model.addAttribute("pageSizes", PAGE_SIZES); model.addAttribute("pager", pager); return "admin/portada"; } @PostMapping("") public String searchUsuario(@ModelAttribute("searchForm") SearchBean searchBean, Model model) { model.addAttribute("usuarios", userServi.findByEmail(searchBean.getSearch())); return "admin/portada"; } /** * Método que maneja el formulario de edición de un usuario. * * @param model Se le pasa como modelo el usuario a editar * @param id ID del usuario a editar * @return En caso de que el usuario cuyo id se ha pasado sea nulo, devuelve al * admin a la portada. Si no, devuelve la plantilla del formulario de * edición. */ @GetMapping("/editarUsuario/{id}") public String editarUsuario(Model model, @PathVariable("id") long id) { Usuario aEditar = userServi.findById(id); if (aEditar != null) { model.addAttribute("usuario", aEditar); return "admin/editarUsuario"; } else { return "redirect:/admin/"; } } /** * Método que controla la petición POST de la edición de usuarios * * @param u El usuario a editar * @return Devuelve al admin a la portada */ @PostMapping("/editarUsuario/submit") public String procesarEdicion(@ModelAttribute("usuario") Usuario u) { userServi.edit(u); return "redirect:/admin/"; } /** * Método que controla la plantilla de los detalles de un usuario. En ella se * ven los datos del usuario y una lista de sus inventarios. Se puede editar y * borrar al usuario y crear nuevos inventarios pertenecientes al usuario. * También se pueden borrar inventarios ya existentes. * * @param id ID del usuario a mostrar. * @param model Se le pasan como parámetros el usuario a mostrar y una lista de * sus inventarios * @return Si el usuario es nulo devuelve al admin a la portada, si no, devuelve * la plantilla de los detalles del usuario */ @GetMapping("/detalleUsuario/{id}") public String detalleUsuario(@PathVariable("id") long id, Model model) { Usuario u = userServi.findById(id); List<Invent> i = u.getInvents(); if (u != null) { model.addAttribute("usuario", u); model.addAttribute("invents", i); return "admin/detalleUsuario"; } else { return "redirect:/admin/"; } } /** * Método que controla la petición de borrar un usuario. Guarda todos los datos * del usuario a borrar en un objeto de la tabla * HistoricoUsuarios{@link com.salesianostriana.damcrasinvent.model.HistoricoUsuarios} * * @param id ID del usuario a borrar * @return Devuelve al admin a la portada */ @GetMapping("/borrarUsuario/{id}") public String borrarUsuario(@PathVariable("id") long id) { Usuario aBorrar = userServi.findById(id); HistoricoUsuarios anadir = new HistoricoUsuarios(); anadir.setId(aBorrar.getId()); anadir.setNombre(aBorrar.getNombre()); anadir.setApellidos(aBorrar.getApellidos()); anadir.setEmail(aBorrar.getEmail()); anadir.setNickname(aBorrar.getNickname()); anadir.setPassword(aBor<PASSWORD>()); anadir.setTelefono(aBorrar.getTelefono()); anadir.setAdmin(aBorrar.isAdmin()); anadir.setCuentaCaducada(aBorrar.isCuentaCaducada()); anadir.setCuentaBloqueada(aBorrar.isCuentaBloqueada()); anadir.setCredencialesCaducadas(aBorrar.isCredencialesCaducadas()); histoServi.add(anadir); for (Invent invent : aBorrar.getInvents()) { for (Conceptos concepto : invent.getConceptos()) { for (Campos campo : concepto.getCampos()) { for (ValoresCampos valor : campo.getValoresCampos()) { valorservi.delete(valor); } campservi.delete(campo); } concepservi.delete(concepto); } invServi.delete(invent); } userServi.delete(aBorrar); return "redirect:/admin/"; } /** * Método que maneja la petición get de editar un inventario de un usuario. * * @param id ID del inventario a editar * @param idUsuario ID del usuario al que pertenece el inventario. Lo utiliza * para redirigir al admin de vuelta a la página de detalles * del usuario en caso de que se intente acceder a un invent * nulo * @param model Se le pasan como parámetros el inventario a editar y el * usuario al que pertenece * @return Si el inventario es nulo devuelve al admin a la página de detalles * del usuario, si no, devuelve la plantilla de editar el inventario */ @GetMapping("/editInvent/{id}/{idUsuario}") public String editarInventario(@PathVariable("id") long id, @PathVariable("idUsuario") long idUsuario, Model model) { Invent aEditar = invServi.findById(id); Usuario pertenece = userServi.findById(idUsuario); if (aEditar != null) { model.addAttribute("invent", aEditar); model.addAttribute("usuario", pertenece); return "admin/editarInvent"; } else { return "redirect:/admin/detalleUsuario/" + idUsuario; } } /** * Método que maneja la petición POST de edición de inventarios. * * @param i Inventario a editar * @param id ID del usuario al que pertenece el inventario. Se utiliza para * redirigir al admin a la página de detalles del usuario. * @return Devuelve al admin a la página de detalles del usuario. */ @PostMapping("/editarInventario/submit/{id}") public String procesarEdicion(@ModelAttribute("invent") Invent i, @PathVariable("id") long id) { i.setUsuario(userServi.findById(id)); invServi.edit(i); return "redirect:/admin/detalleUsuario/" + id; } } <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/controller/ExcepcionCaducidadController.java /** * */ package com.salesianostriana.damcrasinvent.controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import com.salesianostriana.damcrasinvent.excepciones.ExcepcionCaducidad; /** * @author pedom * */ @ControllerAdvice public class ExcepcionCaducidadController { @ExceptionHandler (ExcepcionCaducidad.class) public String excepcioncaducidad (Model model, ExcepcionCaducidad ec) { model.addAttribute("excepcion", ec); return "excepcionCaducidad"; } } <file_sep>/doc/index-files/index-17.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="es"> <head> <!-- Generated by javadoc (1.8.0_211) on Mon May 27 14:18:23 CEST 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=utf8"> <title>U-Index</title> <meta name="date" content="2019-05-27"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <script type="text/javascript" src="../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="U-Index"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-16.html">Prev Letter</a></li> <li><a href="index-18.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-17.html" target="_top">Frames</a></li> <li><a href="index-17.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">L</a>&nbsp;<a href="index-11.html">M</a>&nbsp;<a href="index-12.html">N</a>&nbsp;<a href="index-13.html">P</a>&nbsp;<a href="index-14.html">R</a>&nbsp;<a href="index-15.html">S</a>&nbsp;<a href="index-16.html">T</a>&nbsp;<a href="index-17.html">U</a>&nbsp;<a href="index-18.html">V</a>&nbsp;<a name="I:U"> <!-- --> </a> <h2 class="title">U</h2> <dl> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/seguridad/SecurityConfig.html#userDetailsService">userDetailsService</a></span> - Variable in class com.salesianostriana.damcrasinvent.seguridad.<a href="../com/salesianostriana/damcrasinvent/seguridad/SecurityConfig.html" title="class in com.salesianostriana.damcrasinvent.seguridad">SecurityConfig</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/salesianostriana/damcrasinvent/seguridad/UserDetailsServiceImpl.html" title="class in com.salesianostriana.damcrasinvent.seguridad"><span class="typeNameLink">UserDetailsServiceImpl</span></a> - Class in <a href="../com/salesianostriana/damcrasinvent/seguridad/package-summary.html">com.salesianostriana.damcrasinvent.seguridad</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/seguridad/UserDetailsServiceImpl.html#UserDetailsServiceImpl-com.salesianostriana.damcrasinvent.servicios.UsuarioServicio-">UserDetailsServiceImpl(UsuarioServicio)</a></span> - Constructor for class com.salesianostriana.damcrasinvent.seguridad.<a href="../com/salesianostriana/damcrasinvent/seguridad/UserDetailsServiceImpl.html" title="class in com.salesianostriana.damcrasinvent.seguridad">UserDetailsServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/controller/AdminController.html#userServi">userServi</a></span> - Variable in class com.salesianostriana.damcrasinvent.controller.<a href="../com/salesianostriana/damcrasinvent/controller/AdminController.html" title="class in com.salesianostriana.damcrasinvent.controller">AdminController</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/InventServicioTests.html#userServi">userServi</a></span> - Variable in class com.salesianostriana.damcrasinvent.<a href="../com/salesianostriana/damcrasinvent/InventServicioTests.html" title="class in com.salesianostriana.damcrasinvent">InventServicioTests</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/model/Invent.html#usuario">usuario</a></span> - Variable in class com.salesianostriana.damcrasinvent.model.<a href="../com/salesianostriana/damcrasinvent/model/Invent.html" title="class in com.salesianostriana.damcrasinvent.model">Invent</a></dt> <dd> <div class="block">Usuario al que pertenece el inventario</div> </dd> <dt><a href="../com/salesianostriana/damcrasinvent/model/Usuario.html" title="class in com.salesianostriana.damcrasinvent.model"><span class="typeNameLink">Usuario</span></a> - Class in <a href="../com/salesianostriana/damcrasinvent/model/package-summary.html">com.salesianostriana.damcrasinvent.model</a></dt> <dd> <div class="block">Clase POJO del objeto Usuario.</div> </dd> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/model/Usuario.html#Usuario-java.lang.String-java.lang.String-java.lang.String-java.lang.String-java.lang.String-java.lang.String-boolean-">Usuario(String, String, String, String, String, String, boolean)</a></span> - Constructor for class com.salesianostriana.damcrasinvent.model.<a href="../com/salesianostriana/damcrasinvent/model/Usuario.html" title="class in com.salesianostriana.damcrasinvent.model">Usuario</a></dt> <dd> <div class="block">Constructor que especifica todos los atributos menos los generados automáticamente (id, cuentaCaducada, cuentaBloqueada y credencialesCaducadas, además de la lista de inventarios</div> </dd> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/model/Usuario.html#Usuario-long-java.lang.String-java.lang.String-java.lang.String-java.lang.String-java.lang.String-java.lang.String-java.util.List-">Usuario(long, String, String, String, String, String, String, List&lt;Invent&gt;)</a></span> - Constructor for class com.salesianostriana.damcrasinvent.model.<a href="../com/salesianostriana/damcrasinvent/model/Usuario.html" title="class in com.salesianostriana.damcrasinvent.model">Usuario</a></dt> <dd> <div class="block">Constructor poco utilizado.</div> </dd> <dt><a href="../com/salesianostriana/damcrasinvent/controller/UsuarioController.html" title="class in com.salesianostriana.damcrasinvent.controller"><span class="typeNameLink">UsuarioController</span></a> - Class in <a href="../com/salesianostriana/damcrasinvent/controller/package-summary.html">com.salesianostriana.damcrasinvent.controller</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/controller/UsuarioController.html#UsuarioController-com.salesianostriana.damcrasinvent.servicios.UsuarioServicio-com.salesianostriana.damcrasinvent.servicios.HistoricoUsuariosServicio-">UsuarioController(UsuarioServicio, HistoricoUsuariosServicio)</a></span> - Constructor for class com.salesianostriana.damcrasinvent.controller.<a href="../com/salesianostriana/damcrasinvent/controller/UsuarioController.html" title="class in com.salesianostriana.damcrasinvent.controller">UsuarioController</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/salesianostriana/damcrasinvent/model/UsuarioEmpresa.html" title="class in com.salesianostriana.damcrasinvent.model"><span class="typeNameLink">UsuarioEmpresa</span></a> - Class in <a href="../com/salesianostriana/damcrasinvent/model/package-summary.html">com.salesianostriana.damcrasinvent.model</a></dt> <dd> <div class="block">Clase POJO del objeto UsuarioEmpresa.</div> </dd> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/model/UsuarioEmpresa.html#UsuarioEmpresa-java.lang.String-java.lang.String-java.lang.String-java.lang.String-java.lang.String-java.lang.String-boolean-java.lang.String-java.lang.String-java.lang.String-java.lang.String-java.lang.String-">UsuarioEmpresa(String, String, String, String, String, String, boolean, String, String, String, String, String)</a></span> - Constructor for class com.salesianostriana.damcrasinvent.model.<a href="../com/salesianostriana/damcrasinvent/model/UsuarioEmpresa.html" title="class in com.salesianostriana.damcrasinvent.model">UsuarioEmpresa</a></dt> <dd> <div class="block">Constructor con todos los atributos de la clase.</div> </dd> <dt><a href="../com/salesianostriana/damcrasinvent/repository/UsuarioEmpresaRepository.html" title="interface in com.salesianostriana.damcrasinvent.repository"><span class="typeNameLink">UsuarioEmpresaRepository</span></a> - Interface in <a href="../com/salesianostriana/damcrasinvent/repository/package-summary.html">com.salesianostriana.damcrasinvent.repository</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/salesianostriana/damcrasinvent/servicios/UsuarioEmpresaServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios"><span class="typeNameLink">UsuarioEmpresaServicio</span></a> - Class in <a href="../com/salesianostriana/damcrasinvent/servicios/package-summary.html">com.salesianostriana.damcrasinvent.servicios</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/servicios/UsuarioEmpresaServicio.html#UsuarioEmpresaServicio--">UsuarioEmpresaServicio()</a></span> - Constructor for class com.salesianostriana.damcrasinvent.servicios.<a href="../com/salesianostriana/damcrasinvent/servicios/UsuarioEmpresaServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios">UsuarioEmpresaServicio</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/servicios/UsuarioServicio.html#usuarioLogeado-org.springframework.ui.Model-java.security.Principal-">usuarioLogeado(Model, Principal)</a></span> - Method in class com.salesianostriana.damcrasinvent.servicios.<a href="../com/salesianostriana/damcrasinvent/servicios/UsuarioServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios">UsuarioServicio</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/salesianostriana/damcrasinvent/repository/UsuarioRepository.html" title="interface in com.salesianostriana.damcrasinvent.repository"><span class="typeNameLink">UsuarioRepository</span></a> - Interface in <a href="../com/salesianostriana/damcrasinvent/repository/package-summary.html">com.salesianostriana.damcrasinvent.repository</a></dt> <dd> <div class="block">Clase que gestiona las operaciones relacionadas con la clase Usuario <a href="../com/salesianostriana/damcrasinvent/model/Usuario.html" title="class in com.salesianostriana.damcrasinvent.model"><code>Usuario</code></a></div> </dd> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/model/MetodosPago.html#usuarios">usuarios</a></span> - Variable in class com.salesianostriana.damcrasinvent.model.<a href="../com/salesianostriana/damcrasinvent/model/MetodosPago.html" title="class in com.salesianostriana.damcrasinvent.model">MetodosPago</a></dt> <dd> <div class="block">Lista de empresas <a href="../com/salesianostriana/damcrasinvent/model/UsuarioEmpresa.html" title="class in com.salesianostriana.damcrasinvent.model"><code>UsuarioEmpresa</code></a> que utilizan un método de pago en concreto.</div> </dd> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/controller/InventController.html#usuarioservicio">usuarioservicio</a></span> - Variable in class com.salesianostriana.damcrasinvent.controller.<a href="../com/salesianostriana/damcrasinvent/controller/InventController.html" title="class in com.salesianostriana.damcrasinvent.controller">InventController</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/controller/PortadaController.html#usuarioServicio">usuarioServicio</a></span> - Variable in class com.salesianostriana.damcrasinvent.controller.<a href="../com/salesianostriana/damcrasinvent/controller/PortadaController.html" title="class in com.salesianostriana.damcrasinvent.controller">PortadaController</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/controller/UsuarioController.html#usuarioServicio">usuarioServicio</a></span> - Variable in class com.salesianostriana.damcrasinvent.controller.<a href="../com/salesianostriana/damcrasinvent/controller/UsuarioController.html" title="class in com.salesianostriana.damcrasinvent.controller">UsuarioController</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/seguridad/UserDetailsServiceImpl.html#usuarioServicio">usuarioServicio</a></span> - Variable in class com.salesianostriana.damcrasinvent.seguridad.<a href="../com/salesianostriana/damcrasinvent/seguridad/UserDetailsServiceImpl.html" title="class in com.salesianostriana.damcrasinvent.seguridad">UserDetailsServiceImpl</a></dt> <dd>&nbsp;</dd> <dt><a href="../com/salesianostriana/damcrasinvent/servicios/UsuarioServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios"><span class="typeNameLink">UsuarioServicio</span></a> - Class in <a href="../com/salesianostriana/damcrasinvent/servicios/package-summary.html">com.salesianostriana.damcrasinvent.servicios</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/salesianostriana/damcrasinvent/servicios/UsuarioServicio.html#UsuarioServicio--">UsuarioServicio()</a></span> - Constructor for class com.salesianostriana.damcrasinvent.servicios.<a href="../com/salesianostriana/damcrasinvent/servicios/UsuarioServicio.html" title="class in com.salesianostriana.damcrasinvent.servicios">UsuarioServicio</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">L</a>&nbsp;<a href="index-11.html">M</a>&nbsp;<a href="index-12.html">N</a>&nbsp;<a href="index-13.html">P</a>&nbsp;<a href="index-14.html">R</a>&nbsp;<a href="index-15.html">S</a>&nbsp;<a href="index-16.html">T</a>&nbsp;<a href="index-17.html">U</a>&nbsp;<a href="index-18.html">V</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-16.html">Prev Letter</a></li> <li><a href="index-18.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-17.html" target="_top">Frames</a></li> <li><a href="index-17.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html> <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/repository/package-info.java /** * Paquete que contiene las clases repository. Todas las clases extienden la * interfaz JpaRepository, que proporciona muchos métodos predefinidos muy * útiles * * @author <NAME> */ package com.salesianostriana.damcrasinvent.repository;<file_sep>/src/main/java/com/salesianostriana/damcrasinvent/servicios/ValoresCamposServicio.java /** * */ package com.salesianostriana.damcrasinvent.servicios; import org.springframework.stereotype.Service; import com.salesianostriana.damcrasinvent.model.ValoresCampos; import com.salesianostriana.damcrasinvent.repository.ValoresCamposRepository; import com.salesianostriana.damcrasinvent.servicios.base.BaseService; /** * @author amarquez * */ @Service public class ValoresCamposServicio extends BaseService<ValoresCampos, Long, ValoresCamposRepository> { } <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/model/UsuarioEmpresa.java /** * */ package com.salesianostriana.damcrasinvent.model; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinTable; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; /** * Clase POJO del objeto UsuarioEmpresa. Extiende a la clase Usuario * {@link com.salesianostriana.damcrasinvent.model.Usuario}. Está pensado para * que sólo empresas puedan ser usuarios premium, pero no está implementado que * tengan ninguna ventaja en el proyecto por falta de tiempo, por lo que por * ahora a efectos prácticos es inservible. * * @author <NAME> * */ @Getter @Setter @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) @NoArgsConstructor @Entity public class UsuarioEmpresa extends Usuario { /** * CIF de la empresa */ @Column(nullable = false) private String CIF; /** * Nombre de la empresa */ private String nombreEmpresa; /** * Teléfono profesional de la empresa */ private String telefonoEmpresa; /** * campo profesional al que pertenece la empresa */ private String campoEmpresa; /** * Dirección de facturación de la empresa */ private String direccionFacturacion; /** * Lista de Métodos de * Pago{@link com.salesianostriana.damcrasinvent.model.MetodosPago} que tiene * registrados la empresa. Es una lista en lugar de un objeto individual por si * la empresa quiere tener varios registrados en caso de que uno falle. */ @EqualsAndHashCode.Exclude @ToString.Exclude @ManyToMany @JoinTable(joinColumns = @JoinColumn(name = "usuario_id"), inverseJoinColumns = @JoinColumn(name = "metPago_id")) private List<MetodosPago> metodosPago = new ArrayList<>(); public void addMetodoPago(MetodosPago m) { metodosPago.add(m); m.getUsuarios().add(this); } public void deleteMetodoPago(MetodosPago m) { metodosPago.remove(m); m.getUsuarios().remove(this); } /** * Constructor con todos los atributos de la clase. No debería hacer falta, está * como colchón de seguridad en caso de que hiciera falta */ public UsuarioEmpresa(String nombre, String apellidos, String email, String nickname, String password, String telefono, boolean isAdmin, String cif, String nombreEmpresa, String telefonoEmpresa, String campoEmpresa, String direccionFacturacion) { super(nombre, apellidos, email, nickname, password, telefono, isAdmin); this.CIF = cif; this.nombreEmpresa = nombreEmpresa; this.telefonoEmpresa = telefonoEmpresa; this.campoEmpresa = campoEmpresa; this.direccionFacturacion = direccionFacturacion; } public UsuarioEmpresa(String cif, String nombreEmpresa, String telefonoEmpresa, String campoEmpresa, String direccionFacturacion) { this.CIF = cif; this.nombreEmpresa = nombreEmpresa; this.telefonoEmpresa = telefonoEmpresa; this.campoEmpresa = campoEmpresa; this.direccionFacturacion = direccionFacturacion; } /** * Método que otorga al usuario el rol de usuario premium */ @Override public Collection<? extends GrantedAuthority> getAuthorities() { return Arrays.asList(new SimpleGrantedAuthority("ROLE_PREMIUMUSER")); } } <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/repository/ValoresCamposRepository.java package com.salesianostriana.damcrasinvent.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.salesianostriana.damcrasinvent.model.ValoresCampos; public interface ValoresCamposRepository extends JpaRepository<ValoresCampos, Long> { } <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/servicios/HistoricoUsuariosServicio.java /** * */ package com.salesianostriana.damcrasinvent.servicios; import org.springframework.stereotype.Service; import com.salesianostriana.damcrasinvent.model.HistoricoUsuarios; import com.salesianostriana.damcrasinvent.repository.HistoricoUsuariosRepository; import com.salesianostriana.damcrasinvent.servicios.base.BaseService; /** * @author <NAME> * */ @Service public class HistoricoUsuariosServicio extends BaseService<HistoricoUsuarios, Long, HistoricoUsuariosRepository> { } <file_sep>/src/main/java/com/salesianostriana/damcrasinvent/model/Tarjeta.java /** * */ package com.salesianostriana.damcrasinvent.model; import java.time.LocalDate; import java.util.List; import javax.persistence.Entity; import org.springframework.format.annotation.DateTimeFormat; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; /** * Clase pojo del objeto Tarjeta. Para más información visitar la clase * MetodosPago {@link com.salesianostriana.damcrasinvent.model.MetodosPago} * * @author <NAME> * */ @Getter @Setter @NoArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) @Entity public class Tarjeta extends MetodosPago { /** * Número de la tarjeta */ private String numero; /** * Fecha de caducidad de la tarjeta */ @DateTimeFormat(pattern = "yyyy-MM-dd") private LocalDate fechaCad; /** * Nombre y apellidos del titular de la tarjeta */ private String titular; /** * Código de seguridad de la tarjeta */ private String CVV; /** * Constructor con todos los atributos de la clase. No debería hacer falta, está * como colchón de seguridad en caso de que hiciera falta */ public Tarjeta(String numero, LocalDate fechaCad, String titular, String cVV) { this.numero = numero; this.fechaCad = fechaCad; this.titular = titular; CVV = cVV; } }
cb206683125619e754f72d2d41cc156cc4ff299c
[ "JavaScript", "Java", "HTML" ]
26
Java
Ajeky/CRASINVENT
d760c984b10065c69b0d4879226774c3fa6a2c08
bade18a3a9798c2cc3a7aad7d8c7e0fc97d402fa
refs/heads/master
<repo_name>Sounder721/dcqvideo<file_sep>/src/main/java/com/sounder/dcqvideo/widgets/DcqVideoView.java package com.sounder.dcqvideo.widgets; import android.content.Context; import android.content.Intent; import android.graphics.SurfaceTexture; import android.support.v7.widget.AppCompatSeekBar; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.sounder.dcqvideo.FullActivity; import com.sounder.dcqvideo.MediaPlayerManager; import com.sounder.dcqvideo.OnStartPlayVideoListener; import com.sounder.dcqvideo.OnUpdateProgressListener; import com.sounder.dcqvideo.R; import com.sounder.dcqvideo.Utils; import tv.danmaku.ijk.media.player.IMediaPlayer; import tv.danmaku.ijk.media.player.IjkMediaPlayer; /** * Createed by Sounder on 2017/3/1 */ public class DcqVideoView extends FrameLayout implements TextureView.SurfaceTextureListener, View.OnClickListener,OnUpdateProgressListener, IjkMediaPlayer.OnPreparedListener,IjkMediaPlayer.OnCompletionListener, IjkMediaPlayer.OnErrorListener,IjkMediaPlayer.OnBufferingUpdateListener{ public static final String TAG = "DcqVideoView"; private ImageButton btnStart; private ImageButton btnFullScreen; private ProgressBar progressBarLoading; /**视频占位图,声明为public,根据各自图片加载方式加载*/ public ImageView imgThumb; private RelativeLayout rlControl; private TextView tvTimeNow; private TextView tvTimeAll; private AppCompatSeekBar seekBar; private RelativeLayout rlTitle; private ImageButton btnBack; private TextView tvTitle; private View mControlView; private TextureView mTextureView; private String mVideoUrl; private String mTitle; private boolean mControlsShow; private Surface mSurface; /**仅当在全屏页面才会设置该值为true*/ private boolean mFullScreenMode = false; /**当拖动进度条时是不能设置进度条的值的*/ private boolean mCanSeekBar = true; private OnStartPlayVideoListener mStartPlayVideoListener; public DcqVideoView(Context context) { super(context); init(context); } public DcqVideoView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public DcqVideoView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } /** * 重新设置监听器, * 否则在退出全屏返回上个页面时MediaPlayerManager里的各个监听是没有的,当然也不会存在进度条的更新的 * */ public void resume(){ initMediaPlayerListeners(); } public void init(Context context){ makeTextureView(); makeControlView(); initControlsView(); initMediaPlayerListeners(); initOthers(); mControlsShow = true; } public void setUp(String url,String title){ this.mVideoUrl = url; this.mTitle = title; tvTitle.setText(title); } /** * 实例化一个TextureView对象,使得IjkMediaplayer有画面可渲染 */ private void makeTextureView(){ TextureView textureView = new TextureView(getContext()); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); addView(textureView); textureView.setLayoutParams(params); textureView.setSurfaceTextureListener(this); } /** * 一系列控制的view */ private void makeControlView(){ mControlView = LayoutInflater.from(getContext()).inflate(R.layout.video_control,this); mControlView.setOnClickListener(this); FrameLayout.LayoutParams params = (LayoutParams) mControlView.getLayoutParams(); if(params == null){ params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); }else{ params.width = ViewGroup.LayoutParams.MATCH_PARENT; params.height = ViewGroup.LayoutParams.MATCH_PARENT; } mControlView.setLayoutParams(params); } private void initControlsView(){ btnStart = (ImageButton) mControlView.findViewById(R.id.btnPlay); btnStart.setOnClickListener(this); btnFullScreen = (ImageButton) mControlView.findViewById(R.id.btn_full_screen); btnFullScreen.setOnClickListener(this); imgThumb = (ImageView) mControlView.findViewById(R.id.imgThubm); rlControl = (RelativeLayout) mControlView.findViewById(R.id.rl_control); tvTimeAll = (TextView) mControlView.findViewById(R.id.tv_time_all); tvTimeNow = (TextView) mControlView.findViewById(R.id.tv_time_now); seekBar = (AppCompatSeekBar) findViewById(R.id.seekBar); progressBarLoading = (ProgressBar) mControlView.findViewById(R.id.loading); rlTitle = (RelativeLayout) mControlView.findViewById(R.id.rl_title); btnBack = (ImageButton) mControlView.findViewById(R.id.btn_back); tvTitle = (TextView) mControlView.findViewById(R.id.tv_title); btnBack.setOnClickListener(this); rlTitle.setVisibility(GONE); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { mCanSeekBar = false; } @Override public void onStopTrackingTouch(SeekBar seekBar) { if(MediaPlayerManager.getInstance().isPrepared()){ MediaPlayerManager.getInstance().seekTo(seekBar.getProgress()); } mCanSeekBar = true; } }); progressBarLoading.setVisibility(GONE); } private void initMediaPlayerListeners(){ MediaPlayerManager.getInstance().setOnBufferimgUpdateListener(this); MediaPlayerManager.getInstance().setOnCompletionListener(this); MediaPlayerManager.getInstance().setOnErrorListener(this); MediaPlayerManager.getInstance().setOnPreparedListener(this); MediaPlayerManager.getInstance().setUpdateProgressListener(this); if(mSurface != null){ MediaPlayerManager.getInstance().setSurface(mSurface); } } /** * 根据当前播放器的状态设置UI布局 * 特别是播放状态进入全屏页面时 */ private void initOthers(){ /* 默认情况下只显示开始按钮和占位图 */ if(MediaPlayerManager.getInstance().isPlayed()){ imgThumb.setVisibility(GONE); }else{//还没有点击过播放按钮,就是默认情况 imgThumb.setVisibility(VISIBLE); rlControl.setVisibility(GONE); btnStart.setVisibility(VISIBLE); progressBarLoading.setVisibility(GONE); } if(MediaPlayerManager.getInstance().isPrepared()){ setDuration(); } if(MediaPlayerManager.getInstance().isPlaying()){ progressBarLoading.setVisibility(GONE); btnStart.setImageResource(R.drawable.ic_video_pause); showControls(true); } } @Override public void onClick(View v) { if(v == btnStart){ onBtnStartClick(); }else if(v == btnFullScreen){ onBtnFullScreenClick(); }else if(v == mControlView){ onControlViewClick(); }else if(v == btnBack){ onBtnFullScreenClick(); } } private void onBtnStartClick(){ imgThumb.setVisibility(GONE); if(!MediaPlayerManager.getInstance().isPlayed()){//没有播放过就开始播放 Log.i(TAG,"not played"); progressBarLoading.setVisibility(VISIBLE); imgThumb.setVisibility(GONE); showControls(false); MediaPlayerManager.getInstance().play(mVideoUrl); if(mStartPlayVideoListener != null){ mStartPlayVideoListener.onStartPlay(); } }else { if (!MediaPlayerManager.getInstance().isPrepared()) { Log.i(TAG,"not Prepared"); progressBarLoading.setVisibility(VISIBLE); showControls(false); MediaPlayerManager.getInstance().play(mVideoUrl); } if (MediaPlayerManager.getInstance().isPlaying()) { Log.i(TAG," playing"); MediaPlayerManager.getInstance().pause(); btnStart.setImageResource(R.drawable.ic_video_play); } else { Log.i(TAG," pause"); MediaPlayerManager.getInstance().start(); btnStart.setImageResource(R.drawable.ic_video_pause); } } } /** * 设置全屏标记 */ public void setFullScreen(){ mFullScreenMode = true; //修改全屏图标 btnFullScreen.setImageResource(R.drawable.ic_video_screen_normal); showControls(true); } private void onBtnFullScreenClick(){ if(mFullScreenMode){ Context context = getContext(); if(context instanceof FullActivity){ ((FullActivity) context).finish(); } }else { Intent intent = new Intent(getContext(),FullActivity.class); intent.putExtra("_video_url",mVideoUrl); intent.putExtra("_video_title",mTitle); getContext().startActivity(intent); } } private void onControlViewClick(){ if(!MediaPlayerManager.getInstance().isPlayed()){ onBtnStartClick(); }else{ showControls(!mControlsShow); } } private void showControls(boolean show){ if(show){ btnStart.setVisibility(VISIBLE); rlControl.setVisibility(VISIBLE); if(mFullScreenMode){ rlTitle.setVisibility(VISIBLE); } }else{ btnStart.setVisibility(GONE); rlControl.setVisibility(GONE); if(mFullScreenMode){ rlTitle.setVisibility(GONE); } } mControlsShow = show; } /** * 设置总时长信息 * 在mediaplayer的onPrepare后才会有信息 */ private void setDuration(){ tvTimeAll.setText(Utils.parseTime(MediaPlayerManager.getInstance().getDuration())); seekBar.setMax((int) MediaPlayerManager.getInstance().getDuration()); } @Override public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { mSurface = new Surface(surface); MediaPlayerManager.getInstance().setSurface(mSurface); } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {} @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { Log.i(TAG,"onSurfaceTextureDestroyed"); return true; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) {} @Override public void onBufferingUpdate(IMediaPlayer iMediaPlayer, int i) { Log.i(TAG,"onBufferingUpdate-->"+i); } @Override public void onCompletion(IMediaPlayer iMediaPlayer) { // onUpdateProgress(MediaPlayerManager.getInstance().getDuration()); // tvTimeNow.setText(tvTimeAll.getText()); btnStart.setImageResource(R.drawable.ic_video_play); imgThumb.setVisibility(VISIBLE); } @Override public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) { Log.e(TAG,"Mediaplayer onError ("+i+","+i1+"+)"); imgThumb.setVisibility(VISIBLE); btnStart.setVisibility(VISIBLE); progressBarLoading.setVisibility(GONE); rlControl.setVisibility(GONE); return false; } @Override public void onPrepared(IMediaPlayer iMediaPlayer) { MediaPlayerManager.getInstance().setPrepared(true); MediaPlayerManager.getInstance().start(); progressBarLoading.setVisibility(GONE); btnStart.setImageResource(R.drawable.ic_video_pause); showControls(true); setDuration(); MediaPlayerManager.getInstance().setSurface(mSurface); } @Override public void onUpdateProgress(long position) { tvTimeNow.setText(Utils.parseTime(position)); if(mCanSeekBar) { seekBar.setProgress((int) position); } } public void setStartPlayVideoListener(OnStartPlayVideoListener startPlayVideoListener) { mStartPlayVideoListener = startPlayVideoListener; } } <file_sep>/src/main/java/com/sounder/dcqvideo/OnUpdateProgressListener.java package com.sounder.dcqvideo; /** * Createed by Sounder on 2017/3/2 */ public interface OnUpdateProgressListener { void onUpdateProgress(long position); } <file_sep>/src/main/java/com/sounder/dcqvideo/MediaPlayerManager.java package com.sounder.dcqvideo; import android.media.AudioManager; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.view.Surface; import java.io.IOException; import tv.danmaku.ijk.media.player.IjkMediaPlayer; /** * 维持一个IjkMediaPlayer的单例 * Createed by Sounder on 2017/3/1 */ public class MediaPlayerManager { private static MediaPlayerManager sInstance; public static MediaPlayerManager getInstance() { if (sInstance == null) { sInstance = new MediaPlayerManager(); } return sInstance; } private MediaPlayerManager() { mPlayer = new IjkMediaPlayer(); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mPlayer.setLooping(true); //开启线程 new Thread(mProgressRunable).start(); } private IjkMediaPlayer mPlayer; private String mVideoUrl; private OnUpdateProgressListener mUpdateProgressListener; private boolean mPrepared; private Surface mSurface; /** * 是否播放过 */ private boolean mPlayed = false; /***/ private Handler mProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 2) { if (mUpdateProgressListener != null && mPlayer.isPlaying()) { mUpdateProgressListener.onUpdateProgress(getCurrentPosition()); } } } }; private boolean mRunning = true; /** * 更新进度的线程 */ private Runnable mProgressRunable = new Runnable() { @Override public void run() { while (mRunning) { if (mProgressHandler != null) { mProgressHandler.sendEmptyMessage(2); } try { Thread.sleep(600); } catch (InterruptedException e) { e.printStackTrace(); } } Log.i("MediaPlayerManager","update thread is stopped"); } }; public void play(String videoUrl) { if (TextUtils.isEmpty(videoUrl)) { throw new NullPointerException("video uri can not be NULL"); } mVideoUrl = videoUrl; try { mPlayer.reset(); mPlayer.setDataSource(mVideoUrl); mPlayer.prepareAsync(); mPlayed = true; } catch (IOException e) { e.printStackTrace(); } } public long getCurrentPosition() { try { return mPlayer.getCurrentPosition(); } catch (Exception e) { return 0L; } } public void start() { mPlayer.start(); } public void pause() { mPlayer.pause(); } public void setSurface(Surface surface) { this.mSurface = surface; mPlayer.setSurface(surface); } public void setOnCompletionListener(IjkMediaPlayer.OnCompletionListener listener) { mPlayer.setOnCompletionListener(listener); } public void setOnPreparedListener(IjkMediaPlayer.OnPreparedListener listener) { mPlayer.setOnPreparedListener(listener); } public void setOnErrorListener(IjkMediaPlayer.OnErrorListener listener) { mPlayer.setOnErrorListener(listener); } public void setOnBufferimgUpdateListener(IjkMediaPlayer.OnBufferingUpdateListener listener) { mPlayer.setOnBufferingUpdateListener(listener); } public void _release() { mRunning = false; mPlayed = false; mUpdateProgressListener = null; mProgressHandler = null; mPlayer.reset(); mPlayer.release(); } /** * 当不需要播放时释放资源 * 如果不释放,更新线程仍会继续执行 */ public static void release() { Log.i("MediaPlayerManager","release All Media"); sInstance._release(); sInstance = null; } public boolean isPlaying() { return mPlayer.isPlaying(); } public void setPrepared(boolean prepared) { mPrepared = prepared; } public boolean isPrepared() { return mPrepared; } public boolean isPlayed() { return mPlayed; } public void setPlayed(boolean played) { mPlayed = played; } public void setUpdateProgressListener(OnUpdateProgressListener listener){ this.mUpdateProgressListener = listener; } public long getDuration() { return mPlayer.getDuration(); } public void seekTo(int progress) { mPlayer.seekTo(progress); } } <file_sep>/README.md # dcqvideo Based on IjkPlayer and a simple UI controller #Getting start Clone the library to your project,and type the code into you layout file,like this:<br/> <com.sounder.dcqvideo.widgets.DcqVideoView<br/> android:id="@+id/video"<br/> android:layout_width="match_parent"<br/> android:layout_height="200dp"/><br/> In your Activity:<br/><br/> DcqVideoView mVideoView = (DcqVideoView) findViewById(R.id.video);<br/> mVideoView.setUp("your video url","title");<br/> add it to onResume method:<br/> mVideoView.resume();<br/><br/> when you need to close the activity,you had better to release the resourse by using MediaPlayerManager.release() in the onDestroy method. 当然你也可以看我的<a href="http://blog.csdn.net/u011146263/article/details/60324391">CSDN博客</a> #About I'm just a beginner of Android, if you get some bugs or you have some good ideas, please leave a message. My english is not good,i hope you can understand what i mean.
ea52c93d3f814e12876c72ef22c827cbf8d68018
[ "Markdown", "Java" ]
4
Java
Sounder721/dcqvideo
712d94170b65fdf1017b335d4134d7fabeaa2561
0c10388c51e119a530b0a7a054373a17b5812603
refs/heads/master
<file_sep>import React, { Component } from "react"; import { View, Button, Text, TextInput, StyleSheet, Platform, TouchableOpacity } from "react-native"; import { HeaderBackButton, NavigationActions, KeyboardAvoidingView } from "react-navigation"; import Toast, { DURATION } from "react-native-easy-toast"; import { addCardToDeck } from "../utils/api"; import { connect } from "react-redux"; import { addCard } from "../actions"; import { white, gray, blue } from "../utils/colors"; import AndroidBtn from "./AndroidBtn"; import IosBtn from "./IosBtn"; class NewCard extends Component { state = { question: "", answer: "" }; static navigationOptions = ({ navigation }) => { return { title: "Add Card", headerLeft: ( <HeaderBackButton onPress={() => navigation.navigate("Home")} /> ) }; }; handleChange(target, input) { if (target === "question") { this.setState({ question: input }); } else if (target === "answer") { this.setState({ answer: input }); } console.log(this.state); } submit = () => { const { dispatch, deckId, navigation } = this.props; const { question, answer } = this.state; const card = { question: question, answer: answer }; if (card) { if (question == "" || answer == "") { return alert("Fill both fields"); } else { addCardToDeck(deckId, card); dispatch(addCard(deckId, card)); this.setState(() => ({ question: "", answer: "" })); } } this.refs.toast.show("New Card successfully added"); }; render() { const { navigation } = this.props; return ( <View style={styles.container}> <View style={{ marginTop: 100 }}> <View style={styles.inputView}> <TextInput style={styles.input} onChangeText={input => this.handleChange("question", input)} placeholder={"Question"} value={this.state.question} /> </View> <View style={styles.inputView}> <TextInput style={styles.input} onChangeText={input => this.handleChange("answer", input)} placeholder={"Answer"} value={this.state.answer} /> </View> {Platform.OS === "ios" ? ( <View> <IosBtn style={{ marginTop: 230 }} onPress={() => this.submit()}> Create Card </IosBtn> <IosBtn onPress={() => this.props.navigation.pop(2)}> Cancel </IosBtn> </View> ) : ( <View> <AndroidBtn style={{ marginTop: 160 }} onPress={() => this.submit()} > Create Card </AndroidBtn> <AndroidBtn onPress={() => this.props.navigation.pop(2)}> Cancel </AndroidBtn> </View> )} </View> <Toast ref="toast" /> </View> ); } } function mapStateToProps(state, { navigation }) { const { deckId } = navigation.state.params; return { deckId }; } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: white, padding: 20 }, title: { marginTop: 50, fontSize: 40 }, input: { height: 40, borderColor: gray, borderWidth: 1, borderRadius: 10, marginTop: 10 }, inputView: { marginTop: 10 } }); export default connect(mapStateToProps)(NewCard); <file_sep># React-Project3-MobileFlashcards MobileFlashcards is a mobile application (Android and iOS) that allows users to study collections of flashcards. The app will allow users to create different categories of flashcards called "decks", add flashcards to those decks, then take quizzes on those decks. ### Install ```https://github.com/hraldur/React-Project3-MobileFlashcards.git cd React-Project3-MobileFlashcards yarn install yarn start ``` <file_sep>import { AsyncStorage } from "react-native"; import { DECK_STORAGE_KEY, formatDeckResults } from './_deck' export function getDecks () { return AsyncStorage.getItem(DECK_STORAGE_KEY) .then(formatDeckResults) } export function getDeck (id) { return AsyncStorage.getItem(DECK_STORAGE_KEY) .then((results) => { const data = JSON.parse(results) return data[id] }) } export function saveDeckTitle (title) { return AsyncStorage.mergeItem(DECK_STORAGE_KEY, JSON.stringify({ [title]: { title: title, questions: [] } })) } export function addCardToDeck (title, card) { return AsyncStorage.getItem(DECK_STORAGE_KEY) .then((results) => { const data = JSON.parse(results) data[title].questions.push(card) AsyncStorage.setItem(DECK_STORAGE_KEY, JSON.stringify(data)) }) } export function fetchDeckResults() { return AsyncStorage.getItem(DECK_STORAGE_KEY) .then(formatDeckResults) } <file_sep>export const gray = '#757575' export const white = '#fff' export const blue = '#18CBB0' export const yellow = '#EAD720' <file_sep>import React, { Component } from "react"; import { View, Text, TextInput, StyleSheet, Platform, KeyboardAvoidingView } from "react-native"; import { saveDeckTitle, fetchDeckResults } from "../utils/api"; import { connect } from "react-redux"; import { addDeck, receiveDecks } from "../actions"; import { white, gray, blue } from "../utils/colors"; import AndroidBtn from "./AndroidBtn"; import IosBtn from "./IosBtn"; class NewDeck extends Component { state = { title: "" }; handleChange(input) { this.setState({ title: input }); } submit = () => { const { dispatch, navigation } = this.props; const { title } = this.state; let deck = {}; if (title) { saveDeckTitle(title); deck["title"] = title; dispatch(addDeck(deck)); fetchDeckResults() .then(decks => dispatch(receiveDecks(decks))) .then(navigation.navigate("DeckDetail", { deckId: title })); this.setState(() => ({ title: "" })); } if (!title) { return alert("Please enter title"); } }; render() { return ( <KeyboardAvoidingView behavior="position" style={styles.container}> <Text style={styles.title}>What is the title of your new Deck?</Text> <View style={styles.inputView}> <TextInput style={styles.input} onChangeText={input => this.handleChange(input)} value={this.state.title} /> </View> {Platform.OS === "ios" ? ( <IosBtn onPress={() => this.submit()}>Create Deck</IosBtn> ) : ( <AndroidBtn onPress={() => this.submit()}>Create Deck</AndroidBtn> )} </KeyboardAvoidingView> ); } } function mapStateToProps(state) { return {}; } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: white, padding: 20 }, title: { marginTop: 30, fontSize: 30 }, input: { height: 40, borderColor: gray, borderWidth: 1, borderRadius: 10 }, inputView: { marginTop: 100 } }); export default connect(mapStateToProps)(NewDeck); <file_sep>import React, { Component } from "react"; import { Text, View, TouchableOpacity, Button, StyleSheet, Platform } from "react-native"; import { connect } from "react-redux"; import { HeaderBackButton, NavigationActions } from "react-navigation"; import { blue, white } from "../utils/colors"; import AndroidBtn from "./AndroidBtn"; import IosBtn from "./IosBtn"; class DeckDetail extends Component { static navigationOptions = ({ navigation }) => { const { deckId } = navigation.state.params; return { title: deckId, headerLeft: ( <HeaderBackButton onPress={() => navigation.navigate("Home")} /> ) }; }; render() { const { deck, navigation } = this.props; return ( <View style={styles.container}> {deck && ( <View style={{ marginTop: 100, width: "70%" }}> <Text style={styles.title}>{deck.title}</Text> <Text style={{ marginTop: 8 }}> {Object.values(deck.questions).length} Cards </Text> <View style={styles.groupButtons}> {Platform.OS === "ios" ? ( <View> <IosBtn style={{ backgroundColor: white, borderColor: blue, borderWidth: 1 }} textStyle={{ color: blue }} onPress={() => navigation.navigate("NewCard", { deckId: deck.title }) } > Add Card </IosBtn> </View> ) : ( <View> <AndroidBtn onPress={() => navigation.navigate("NewCard", { deckId: deck.title }) } > Add Card </AndroidBtn> </View> )} </View> {Object.values(deck.questions).length != 0 && Platform.OS === "ios" && ( <View> <IosBtn onPress={() => navigation.navigate("Quiz", { questions: deck.questions }) } > Start Quiz </IosBtn> </View> )} {Object.values(deck.questions).length != 0 && Platform.OS === "android" && ( <View> <AndroidBtn onPress={() => navigation.navigate("Quiz", { questions: deck.questions }) } > Start Quiz </AndroidBtn> </View> )} </View> )} </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center", backgroundColor: white }, title: { fontSize: 40 }, groupButtons: { marginTop: 10 } }); function mapStateToProps(state, { navigation }) { const { deckId } = navigation.state.params; return { deckId, deck: state[deckId] }; } export default connect(mapStateToProps)(DeckDetail);
1e503c5353171cd7c9e58998d20a27a2ec7bbb28
[ "JavaScript", "Markdown" ]
6
JavaScript
hraldur/React-Project3-MobileFlashcards
faa397728a1de6409e8fd708cd9bf09402d49ca0
33e0e74ac9bdf478ed1c62c22099923cdd1eb43d
refs/heads/master
<file_sep>import { useNavigation, useTheme } from "@react-navigation/native"; import React, { useEffect, useState } from "react"; import { SafeAreaView, ScrollView, StyleSheet, Text, TouchableOpacity, View, } from "react-native"; import { Button } from "react-native-elements"; import { HISTORY_PERIODS } from "../helpers/constants"; import Card from "./Card"; function HomeScreen() { const navigation = useNavigation(); const { colors } = useTheme(); const [selectedDate, setSelectedDate] = useState("week"); const [assets, setAssets] = useState(null); const [tokens, setTokens] = useState([]); const [fetchURI, setFetchURI] = useState(""); const styles = StyleSheet.create({ container: { flex: 1, flexDirection: "column", justifyContent: "flex-start", paddingLeft: 10, paddingRight: 10, backgroundColor: colors.primary, }, headerText: { fontSize: 18, lineHeight: 21, letterSpacing: 0, textAlign: "center", color: "#495162", }, timeControls: { flexDirection: "row", justifyContent: "space-between", }, tokenBox: {}, }); React.useLayoutEffect(() => { navigation.setOptions({ headerTitle: <Text style={{}}>Tracker</Text>, headerTitleStyle: { fontSize: 18, letterSpacing: 0, textAlign: "center", color: colors.mainFont, fontFamily: "Arial", }, }); }, [navigation]); useEffect(() => { setFetchURI("&period=" + selectedDate); }, [selectedDate]); // On page load, fetch tokens that have history useEffect(() => { async function fetchData() { const response = await fetch( "https://assets-api.sylo.io/v2/all?has_history_only=true" ).then((result) => result.json()); setAssets(response); } fetchData(); }, []); useEffect(() => { async function renderTokenCard() { setTokens([]); // Fetch token info for card render for (let i = 0; i < assets.length; i++) { let token = assets[i]; const tokenHistory = await fetch( `https://assets-api.sylo.io/v2/asset/id/${token.id}/rate?type=historic${fetchURI}` ).then((result) => result.json()); tokenHistory.assetIndex = i; setTokens((tokens) => [...tokens, tokenHistory]); } } assets !== null && renderTokenCard(); }, [assets, fetchURI]); const timeControlButtons = HISTORY_PERIODS.map((timeControl) => ( <Button title={timeControl} type="clear" key={HISTORY_PERIODS.indexOf(timeControl)} titleStyle={{ color: timeControl === selectedDate ? colors.selectedTime : colors.labelColor, fontSize: 15, }} onPress={() => setSelectedDate(HISTORY_PERIODS[HISTORY_PERIODS.indexOf(timeControl)]) } /> )); const tokenCards = tokens.map((token) => ( <TouchableOpacity onPress={() => navigation.navigate("TokenInfo", { token: token, asset: assets[token.assetIndex], selectedTime: selectedDate, }) } key={assets[token.assetIndex].id} > <Card asset={assets[token.assetIndex]} token={token} rate={token.rate} /> </TouchableOpacity> )); return ( <View style={styles.container}> <View style={styles.timeControls}>{timeControlButtons}</View> <SafeAreaView style={styles.tokenBox}> <ScrollView scrollEnabled={true}>{tokenCards}</ScrollView> </SafeAreaView> </View> ); } export default HomeScreen; <file_sep>import { useTheme } from "@react-navigation/native"; import React from "react"; import { Image, StyleSheet, Text, View } from "react-native"; import { LineChart } from "react-native-svg-charts"; const Card = (props) => { const { colors, dark } = useTheme(); const data = props.token.history.map((element) => element.rate); const lastRate = data[data.length - 1]; const firstRate = data[0]; const value = parseFloat(lastRate - firstRate).toFixed(4); const percentage = ((100 * (lastRate - firstRate)) / firstRate).toFixed(2); const styles = StyleSheet.create({ container: { display: "flex", borderWidth: 2, borderStyle: "solid", borderColor: colors.borderColor, borderRadius: 15, marginTop: 9, marginBottom: 9, }, infoBar: { display: "flex", flexDirection: "row", alignItems: "center", justifyContent: "space-between", }, tokenIdentifier: { display: "flex", flexDirection: "row", alignItems: "center", }, monetaryValues: { display: "flex", flexDirection: "column", textAlign: "right", alignItems: "flex-end", paddingRight: 12, }, }); return ( <View class="container" style={styles.container}> <View style={styles.infoBar}> <View style={styles.tokenIdentifier}> <Image source={{ uri: dark ? props.asset.icon_address_dark : props.asset.icon_address, }} style={{ height: 36, width: 36, margin: 10 }} ></Image> <Text style={{ fontSize: 15, color: colors.mainFont }}> {props.asset.name} </Text> </View> <View style={styles.monetaryValues}> <Text style={{ fontSize: 15, color: colors.mainFont }}> ${parseFloat(props.rate).toFixed(4)} </Text> <Text style={{ size: 12, color: "#33BB5D" }}> {value > 0 ? "+" : ""} {percentage}% (${Math.abs(value)}) </Text> </View> </View> <View class="graph"> <LineChart style={{ height: 66 }} data={data} svg={{ stroke: colors.selectedTime, strokeWidth: 3, strokeOpacity: 0.6, }} ></LineChart> </View> </View> ); }; export default Card; <file_sep>import { NavigationContainer } from "@react-navigation/native"; import { createStackNavigator } from "@react-navigation/stack"; import React from "react"; import { AppearanceProvider, useColorScheme } from "react-native-appearance"; import { Button, Icon } from "react-native-elements"; import HomeScreen from "./components/HomeScreen"; import TokenInfo from "./components/TokenInfo"; export default function App() { const Stack = createStackNavigator(); // const scheme = useColorScheme(); const scheme = "dark"; const searchButton = () => ( <Button icon={<Icon name="search" color={MyTheme.colors.mainFont} />} buttonStyle={{ backgroundColor: MyTheme.colors.primary, marginRight: 10 }} /> ); const backImage = () => ( <Icon name="angle-left" type="font-awesome" color={MyTheme.colors.mainFont} /> ); const MyTheme = scheme === "dark" ? { dark: true, colors: { primary: "#000", labelColor: "#8A96AA", rateChange: "#33BB5D", mainFont: "#F6F6F6", selectedTime: "#F15A29", borderColor: "#161616", }, } : { dark: false, colors: { primary: "#fff", labelColor: "#646464", rateChange: "#33BB5D", mainFont: "#495162", selectedTime: "#F15A29", borderColor: "#F6F6F6", }, }; return ( <AppearanceProvider> <NavigationContainer theme={MyTheme}> <Stack.Navigator initialRouteName="HomeScreen" screenOptions={{ cardStyle: { backgroundColor: MyTheme.colors.primary }, headerTitle: "Tracker", headerTitleAlign: "center", headerRight: searchButton, headerStyle: { elevation: 0, shadowOpacity: 0, borderBottomWidth: 0, }, }} > <Stack.Screen name="HomeScreen" component={HomeScreen} /> <Stack.Screen name="TokenInfo" component={TokenInfo} options={{ headerTitleAlign: "center", headerBackImage: backImage }} /> </Stack.Navigator> </NavigationContainer> </AppearanceProvider> ); } <file_sep>// Blockchain Codes export const BITCOIN = "bitcoin"; export const ETHEREUM = "ethereum"; export const TEZOS = "tezos"; export const CENNZNET = "cennznet"; export const OTHER = "other"; export const BLOCKCHAIN_CODES = [ "bitcoin", "ethereum", "tezos", "cennznet", "other", ]; export const NETWORK_CODES = [ "mainnet", "rinkeby", "kovan", "ropsten", "rimu", "bitocin_mainnet", "other", ]; export const CURRENCY_CODES = [ "USD", "EUR", "JPY", "AUD", "CAD", "NZD", "KRW", "SGD", "INR", "GBP", ]; export const HISTORY_PERIODS = ["all", "year", "month", "week", "day"]; <file_sep>import { useTheme } from "@react-navigation/native"; import * as shape from "d3-shape"; import React, { useEffect, useState } from "react"; import { Image, StyleSheet, Text, View } from "react-native"; import { Button } from "react-native-elements"; import { Defs, LinearGradient, Stop } from "react-native-svg"; import { LineChart } from "react-native-svg-charts"; import { HISTORY_PERIODS } from "../helpers/constants"; function TokenInfo({ route, navigation }) { const { colors, dark } = useTheme(); const { token } = route.params; const { asset } = route.params; const { selectedTime } = route.params; const [selectedDate, setSelectedDate] = useState(selectedTime); const [fetchURI, setFetchURI] = useState("&period=" + selectedTime); const [data, setData] = useState( token.history.map((history) => history.rate) ); const [value, setValue] = useState(); const [percentage, setPercentage] = useState(); const [tokenHistory, setTokenHistory] = useState(null); const styles = StyleSheet.create({ container: { flex: 1, flexDirection: "column", backgroundColor: colors.primary, justifyContent: "flex-start", paddingRight: 10, paddingLeft: 10, fontSize: 15, color: colors.mainFont, }, graphBox: { display: "flex", borderWidth: 2, borderStyle: "solid", borderColor: colors.borderColor, borderRadius: 15, height: 185, }, tokenIdentifier: { display: "flex", flexDirection: "row", alignItems: "center", }, tokenName: { fontSize: 18, color: colors.mainFont, }, monetaryValues: { display: "flex", flexDirection: "column", alignItems: "center", }, information: { justifyContent: "space-between", lineHeight: 21, margin: 20, }, tokenInfoFont: { fontSize: 15, color: colors.labelColor, flex: 2, }, tokenInfoFontLabel: { fontSize: 15, color: colors.labelColor, flex: 1, }, tokenInfoRow: { display: "flex", flexDirection: "row", justifyContent: "space-between", margin: 6, }, informationBody: { display: "flex", flexDirection: "row", justifyContent: "space-evenly", }, timeControls: { flexDirection: "row", justifyContent: "space-between", }, }); React.useLayoutEffect(() => { navigation.setOptions({ headerTitle: title, headerTitleStyle: { fontSize: 18, letterSpacing: 0, textAlign: "center", color: colors.mainFont, }, }); }, [navigation]); const title = () => ( <View style={styles.tokenIdentifier}> <Image source={{ uri: dark ? asset.icon_address_dark : asset.icon_address }} style={{ height: 36, width: 36, marginRight: 5 }} ></Image> <Text style={styles.tokenName}>{asset.name}</Text> </View> ); const Gradient = ({ index }) => ( <Defs key={index}> <LinearGradient id={"gradient"} x1={"0%"} y={"0%"} x2={"0%"} y2={"100%"}> <Stop offset={"0%"} stopColor={colors.primary} stopOpacity={1} /> <Stop offset={"100%"} stopColor={colors.selectedTime} stopOpacity={1} /> </LinearGradient> </Defs> ); useEffect(() => { let firstRate = data[0]; let lastRate = data[data.length - 1]; setValue(parseFloat(lastRate - firstRate).toFixed(4)); setPercentage(((100 * (lastRate - firstRate)) / firstRate).toFixed(2)); }, [data]); useEffect(() => { setFetchURI("&period=" + selectedDate); }, [selectedDate]); useEffect(() => { if (tokenHistory !== null) { setData(tokenHistory.history.map((element) => element.rate)); } }, [tokenHistory]); useEffect(() => { async function renderTokenCard() { const tokenHistory = await fetch( `https://assets-api.sylo.io/v2/asset/id/${asset.id}/rate?type=historic${fetchURI}` ).then((result) => result.json()); setTokenHistory(tokenHistory); } renderTokenCard(); }, [fetchURI]); function updateSelectedTime(timePeriod) { setSelectedDate(timePeriod); } const timeControlButtons = HISTORY_PERIODS.map((timeControl) => ( <Button title={timeControl} type="clear" key={HISTORY_PERIODS.indexOf(timeControl)} titleStyle={{ color: timeControl === selectedDate ? colors.selectedTime : colors.labelColor, fontSize: 15, }} onPress={() => updateSelectedTime( HISTORY_PERIODS[HISTORY_PERIODS.indexOf(timeControl)] ) } /> )); return ( <View style={styles.container}> <View style={styles.timeControls}>{timeControlButtons}</View> <View style={styles.graphBox}> <View style={styles.monetaryValues}> <Text style={{ fontSize: 18, color: colors.mainFont }}> ${parseFloat(token.rate).toFixed(4)} </Text> <Text style={{ fontSize: 12, color: colors.rateChange }}> {value > 0 ? "+" : ""} {percentage}% (${Math.abs(value)}) </Text> </View> <LineChart style={{ height: 66 }} data={data} curve={shape.curveBasis} svg={{ stroke: colors.selectedTime, strokeWidth: 3, strokeOpacity: 0.6, fill: "url(#gradient)", }} ></LineChart> </View> <View style={styles.information}> <Text style={{ fontSize: 15, color: colors.mainFont, textAlign: "center" }} > Information </Text> <View style={{}}> <View style={styles.tokenInfoLabel}> <View style={styles.tokenInfoRow}> <Text style={styles.tokenInfoFontLabel}>Symbol:</Text> <Text style={styles.tokenInfoFont}> {asset.name.toUpperCase()} </Text> </View> <View style={styles.tokenInfoRow}> <Text style={styles.tokenInfoFontLabel}>Market Cap:</Text> <Text style={styles.tokenInfoFont}> {token.market_cap} {token.fiat_symbol} </Text> </View> <View style={styles.tokenInfoRow}> <Text style={styles.tokenInfoFontLabel}>24h Volume:</Text> <Text style={styles.tokenInfoFont}> {token.volume_24h} {token.fiat_symbol} </Text> </View> </View> </View> </View> </View> ); } export default TokenInfo;
217f23c10d881af685b49f1723fe54bfb6a2a660
[ "JavaScript" ]
5
JavaScript
kcho9906/cryptoTracker
9499daf9bd0c9339554cec0c39e02028189774e5
d389d504dbf66aaab67bd385ab930ac3a6f999c5
refs/heads/master
<repo_name>zmanring/angular2-simple-ecommerce<file_sep>/src/app/search.service.ts import { Injectable } from '@angular/core'; import { Http } from "@angular/http"; import 'rxjs/add/operator/map'; let totalResults = 0; @Injectable() export class SearchService { constructor(private _http:Http) { } public getItems(from:number=0) { let getItems = 'https://search-fittery-challenge-pv7vc3ugoko5hngpgxdh4szuqm.us-east-1.es.amazonaws.com/items/_search?q=is_live:true&_source_include=id,item_price,item_name,image&size=12&from=' + from; return this._http.get(getItems) .map(res => { totalResults = res.json().hits.total; return res.json().hits.hits; }) } public getItemById(id:number): any { let getItemsByIdURL = 'https://search-fittery-challenge-pv7vc3ugoko5hngpgxdh4szuqm.us-east-1.es.amazonaws.com/items/_search?q=id:' + id; return this._http.get(getItemsByIdURL) .map(res => res.json().hits.hits); } public getTotalResults() { return totalResults; } } <file_sep>/src/app/items-grid.component.ts import { Component } from '@angular/core'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { OnInit } from '@angular/core'; import { SearchService } from './search.service'; // Component @Component({ moduleId: module.id, selector: 'items-grid', templateUrl: 'items-grid.component.html', styleUrls: [ 'items-grid.component.css' ], providers: [SearchService] }) export class ItemsGrid implements OnInit { private items:void[] = []; constructor( private route: ActivatedRoute, private searchService: SearchService, private router: Router ) {} ngOnInit() { this.route.params .map(params => params['page']) .subscribe( page => { this.searchService.getItems(page) .subscribe( items => { this.items = items; }) }); } gotoNextPage(): void { var params:any = this.route.params; var currentPageNum:number = parseInt(params.getValue().page); var totalItemCount = this.searchService.getTotalResults(); if (currentPageNum+12 < totalItemCount) { this.router.navigate(['/items', currentPageNum+12]); } else { this.router.navigate(['/items', totalItemCount-12]); } } gotoPrevPage(): void { var params:any = this.route.params; var currentPageNum:number = parseInt(params.getValue().page); if (currentPageNum-12 >= 0) { this.router.navigate(['/items', currentPageNum-12]); } else { this.router.navigate(['/items', 0]); } } } <file_sep>/src/app/items-detail.component.ts import { Component, Input, OnInit } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { SearchService } from './search.service'; import 'rxjs/add/operator/switchMap'; @Component({ moduleId: module.id, selector: 'items-detail-detail', templateUrl: 'items-detail.component.html', providers: [SearchService] }) export class ItemsDetail implements OnInit { private items = []; constructor( private route: ActivatedRoute, private searchService: SearchService ) {} ngOnInit() { this.route.params .map(params => params['id']) .subscribe( id => { this.searchService.getItemById(id) .subscribe( items => { this.items = items; }) }); } } <file_sep>/src/app/app.component.ts import { Component } from '@angular/core'; // Component @Component({ selector: 'my-app', template: ` <h1 class="text-center"><a [routerLink]="['/items', 0]">Billy-Bob's warehouse</a></h1> <router-outlet></router-outlet> ` }) export class AppComponent {}
e296de33b6a97d80d3ee756d7380292bfbdad96d
[ "TypeScript" ]
4
TypeScript
zmanring/angular2-simple-ecommerce
99ff3bf0401acb43460bd324ae98018255d90679
8a1682a6af5cee7ddf8da9a61ec8a177870590c4
refs/heads/master
<file_sep>package com.codingdojo.portfolio.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HomeController { @RequestMapping("/") public String index() { return "index.html"; } @RequestMapping("/about_me") public String about() { return "me.html"; } @RequestMapping("/my_projects") public String my_projects() { return "projects.html"; } @RequestMapping("/project_page") public String project_page() { return "projectpage.html"; } }
82dc6e01821b1c823405de49c1b4a9b7405af189
[ "Java" ]
1
Java
junottanchanco/Portfolio
234b1da9424e9cd2a5023e795a8bef127f943ae4
afc3f603ae3b92b82e158f047b456428f23edfd9
refs/heads/master
<repo_name>laosiaudi/leetcode<file_sep>/Contains_Duplicate_III.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Contains_Duplicate_III.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-06-01 16:48:08 // MODIFIED: 2015-06-01 17:04:20 #include <iostream> using namespace std; class Solution { public: //TLE bool containsNearbyAlmostDuplicate(vector<int> &nums, int k, int t) { for (int i = 0;i < nums.size(); i += 1) { for (int j = i + 1;j <= i + k && j < nums.size(); j ++) { int temp1 = nums[i]; int temp2 = nums[j]; int dis = temp1 - temp2; if (dis < 0) dis = -dis; if (dis <= t) return true; } } return false; } }; <file_sep>/Roman_To_Integer.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Roman_To_Integer.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-05 16:01:10 // MODIFIED: 2015-05-05 16:46:53 #include <iostream> using namespace std; class Solution { public: int romanToInt(string s) { int size = s.size(); if (size == 0) return 0; map<char, int>m; m['I'] = 1; m['V'] = 5; m['X'] = 10; m['L'] = 50; m['C'] = 100; m['D'] = 500; m['M'] = 1000; int res = m[s[size - 1]]; for (int i = size - 2; i >= 0; i --) { if (m[s[i]] >= m[s[i + 1]]) res += m[s[i]]; else res -= m[s[i]]; } return res; } }; <file_sep>/Next_Permutation.cpp // C/C++ File // AUTHOR: LaoSi // FILE: next_permutation.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2014-12-14 00:55:56 // MODIFIED: 2014-12-14 02:02:36 #include <iostream> #include <vector> using namespace std; class Solution { public: void nextPermutation(vector<int> &num) { int maxNum = num.size(); int com; for (int j = maxNum - 1;j >= 0; j --) { if (j == 0) { com = 0; } else{ com = num[j - 1]; } if (num[j] > com) { int i; for (i = maxNum - 1; i >= j; i --) { if (num[i] > num[j - 1]) break; } int key = num[i]; int len = maxNum - i; int dis = i - j; if (j == 0) num.insert(num.begin(), key); else num.insert(num.begin() + j - 1, key); int ii; for (ii = 0; ii < len - 1; ii ++) num.insert(num.begin() + j + ii, num[num.size() - ii - 1]); for (int i = 0;i < dis - 1; i ++) num.insert(num.begin() + j + ii + i + 1, num[num.size() - len - i - 1]); break; } } int dis = num.size() - maxNum; for (int i = 0; i< dis; i ++) num.erase(num.begin() + maxNum); } }; int main() { Solution ss; vector<int>v; v.push_back(2); v.push_back(2); v.push_back(7); v.push_back(5); v.push_back(4); v.push_back(3); v.push_back(2); v.push_back(2); v.push_back(1); ss.nextPermutation(v); for (int i = 0; i < v.size(); i ++) { cout << v[i] << " , "; } return 0; } <file_sep>/Maximum_Subarray.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Maximum_Subarray.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2014-12-14 13:27:04 // MODIFIED: 2014-12-14 15:20:00 #include <iostream> using namespace std; class Solution { //O(n) public: int maxSubArray(int A[], int n) { if (n == 0) return 0; if (n == 1) return A[0]; int sum = A[0]; int maxEle = A[0]; for (int i = 1; i < n; i ++) { if (sum >= 0) { if (A[i] > 0) { sum += A[i]; maxEle = sum; } else { maxEle = maxEle > sum ? maxEle : sum; sum += A[i]; } } else { if (A[i] <= 0) { sum = sum > A[i] ? sum : A[i]; maxEle = maxEle > sum ? maxEle : sum; } else { sum = A[i]; maxEle = maxEle > A[i] ? maxEle : A[i]; } } } return maxEle > sum ? maxEle : sum; /*more subtle way sum is for 局部最优(一定含A[i]) maxEle is for 全局最优 for (int i = 1; i < n; i ++) { sum = A[i] > (sum + A[i]) ? A[i] : (sum + A[i]); maxEle = sum > maxEle ? sum : maxEle; } return maxEle; */ } }; class Solution { //Divide and Conquer public: int maxSubArray(int A[], int n) { recursiveMaxSubArray(A, 0, n - 1); } int recursiveMaxSubArray(int A[], int start, int end) { if (start == end) return A[start]; int mid = (start + end) / 2; int maxLeft = recursiveMaxSubArray(A, start, mid); //max value appears in left part int maxRight = recursiveMaxSubArray(A, mid + 1, end); //max value appears in right part int leftHalf = 0, rightHalf = 0; int leftMax = -99999, rightMax = -99999; //start from the mid position, extends to left and right for (int i = mid; i >= start; i --) { leftHalf += A[i]; leftMax = leftMax > leftHalf ? leftMax : leftHalf; } for (int i = mid + 1; i <= end; i ++) { rightHalf += A[i]; rightMax = rightMax > rightHalf ? rightMax : rightHalf; } int max1 = maxLeft > maxRight ? maxLeft : maxRight; int max2 = leftMax + rightMax; return max1 > max2 ? max1 : max2; } }; <file_sep>/Climbing_Stairs.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Climbing_Stairs.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-20 17:28:37 // MODIFIED: 2015-05-20 17:36:56 #include <iostream> using namespace std; class Solution { public: int climbStairs(int n) { int size = n; vector<int>res(size, 0); res[0] = 1; res[1] = 2; for (int i = 2; i < size; i ++) { res[i] = (res[i - 1] + res[i - 2]); } return res[size - 1]; } }; <file_sep>/Binary_Tree_Maximum_Path_Sum.cpp /********************************************************************************* * File Name : Binary_Tree_Maximum_Path_Sum.cpp * Created By : laosiaudi * Creation Date : [2015-09-30 01:57] * Last Modified : [2015-09-30 11:15] * Description : **********************************************************************************/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; * */ class Solution { public: int maxPathSum(TreeNode* root) { int max_val = INT_MIN; int reval = recursiveMax(root, max_val); return max_val; } int recursiveMax(TreeNode* root, int &max_val) { if (root == NULL) { return 0; } int left_reval; left_reval = recursiveMax(root->left, max_val); int right_reval; right_reval = recursiveMax(root->right, max_val); int tmp = root->val; if (left_reval > 0) tmp += left_reval; if (right_reval > 0) tmp += right_reval; max_val = max_val > tmp ? max_val : tmp; return max(root->val, max(root->val + left_reval, root->val + right_reval)); } }; <file_sep>/Rotate_Array.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Rotate_Array.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-19 10:08:53 // MODIFIED: 2015-04-19 10:47:01 #include <iostream> using namespace std; class Solution { public: void rev(int nums[], int start, int end) { while (start < end) { int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start ++; end --; } } void rotate(int nums[], int n, int k) { k = k % n; if (k <= 0) return; rev(nums, 0, n - 1); rev(nums, 0, k - 1); rev(nums, k, n - 1); } }; <file_sep>/Subset_II.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Subset_II.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2014-12-13 22:11:50 // MODIFIED: 2014-12-14 00:13:15 #include <iostream> #include <vector> using namespace std; class Solution { public: vector<vector<int> > subsetsWithDup(vector<int> &S) { vector<vector<int> >subsets; if (S.size() == 0) return subsets; sort(S.begin(), S.end()); vector<int>ele; vector<int>time; int num = 1; bool flag = false; for (int i = 0;i < S.size();i ++) { if (i == 0) ele.push_back(S[i]); else { if (S[i] == S[i - 1]) { num ++; if (i == S.size() - 1) time.push_back(num); } else { flag = true; time.push_back(num); num = 1; ele.push_back(S[i]); if (i == S.size() - 1) time.push_back(1); } } } if (flag == false) time.push_back(num); for (int jj = 0; jj <= time[0]; jj ++) { vector<int>temp; for (int i = 0; i < jj; i ++) temp.push_back(ele[0]); insert(subsets, 1, ele, time, temp, ele.size()); } return subsets; } void insert(vector<vector<int> >&v, int index, vector<int>ele, vector<int>time, vector<int> temp, int length) { if (index == length) { v.push_back(temp); } else { for (int i = 0; i <= time[index]; i ++) { vector<int> t = temp; for (int j = 0; j < i;j ++) { t.push_back(ele[index]); } insert(v, index + 1, ele, time, t, length); } } } }; int main() { Solution ss; vector<int>v; v.push_back(1); v.push_back(3); v.push_back(3); vector<vector<int> >s = ss.subsetsWithDup(v); for (int i = 0; i < s.size(); i ++) { for (int j = 0; j< s[i].size(); j ++) cout << s[i][j] << " , "; cout << "\n"; } return 0; } <file_sep>/Reorder_List.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Reorder_List.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-28 13:10:11 // MODIFIED: 2015-04-28 13:49:29 #include <iostream> #include <stack> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: void reorderList(ListNode *head) { if(head == NULL || head->next == NULL) return ; ListNode* helper = new ListNode(0); helper->next = head; ListNode* walker = helper; ListNode* runner = helper; while (runner != NULL && runner->next != NULL) { walker = walker->next; runner = runner->next->next; } stack<ListNode*>s; while (walker->next != NULL) { walker = walker->next; s.push(walker); } walker = head; while (!s.empty()) { ListNode* newNode = s.top(); s.pop(); ListNode* temp = walker->next; walker->next = newNode; newNode->next = temp; walker = temp; } walker->next = NULL; delete helper; } }; //也可以找到链表中点后,将后半段链表发转,再合并两个链表 int main() { ListNode* n1 = new ListNode(1); ListNode* n2 = new ListNode(2); ListNode* n3 = new ListNode(3); ListNode* n4 = new ListNode(4); n1->next = n2; n2->next = n3; n3->next = n4; Solution s; s.reorderList(n1); ListNode* temp = n1; while (temp != NULL) { cout << temp->val << endl; temp = temp->next; } return 0; } <file_sep>/Largest_Number.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Largest_Number.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-06-04 16:52:02 // MODIFIED: 2015-06-04 17:54:57 #include <iostream> using namespace std; class Solution { public: struct Num { string val; bool operator < (const Num &num) const { if (val == "0" && num.val != "0") return true; if (val != "0" && num.val == "0") return false; return (val + num.val < num.val + val); } }; string largestNumber(vector<int> &nums) { int size = nums.size(); vector<Num>v; Num temp; for (int i = 0; i < nums.size(); i ++) { temp.val = to_string(nums[i]); v.push_back(temp); } sort(v.begin(), v.end()); string res; for (int i = v.size() - 1; i >= 0; i --) { if (res == "0" && v[i].val == "0") continue; res += v[i].val; } return res; } }; <file_sep>/Factorial_Trailing_Zeroes.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Factorial_Trailing_Zeroes.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-07 17:12:21 // MODIFIED: 2015-05-07 17:31:22 #include <iostream> using namespace std; //TLE when 2147483647 class Solution { public: int trailingZeroes(int n) { if (n < 0) return 0; int res = 0; int base = 5; while (n >= base) { res += n/base; base *= 5; } return res; } }; class BetterSolution { public: int trailingZeroes(int n) { if (n < 0) return 0; int res = 0; while (n > 0) { res += n/5; //每次除以5比每次除大数的时间少 n = n/5; } return res; } }; int main() { BetterSolution s; cout << s.trailingZeroes(2147483647); } <file_sep>/Merge_Two_Sorted_Lists.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Merge_Two_Sorted_Lists.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-28 14:15:48 // MODIFIED: 2015-04-28 15:02:21 #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; ListNode* head1 = l1; ListNode* head2 = l2; ListNode* helper = new ListNode(0); helper->next =l1; ListNode* pre = helper; while (head1 != NULL && head2 != NULL) { if (head1->val < head2 -> val) { head1 = head1->next; pre = pre->next; } else { pre->next = head2; ListNode* temp = head2->next; head2->next = head1; head2 = temp; pre = pre->next; } } if (head2 != NULL) pre->next = head2; l1 = helper->next; return l1; } }; <file_sep>/Merge_k_Sorted_Lists.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Merge_k_Sorted_Lists.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-28 15:00:26 // MODIFIED: 2015-04-28 15:46:18 #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: //使用merge_two_sorted_lists,两个两个合并 -- TLE ListNode* mergeKLists_TLE(vector<ListNode*>& lists) { int size = lists.size(); if (size == 0) return NULL; ListNode* pre = lists[0]; for (int i = 1;i < size; i ++) { pre = mergeTwoLists(pre, lists[i]); } return pre; } ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; ListNode* head1 = l1; ListNode* head2 = l2; ListNode* helper = new ListNode(0); helper->next =l1; ListNode* pre = helper; while (head1 != NULL && head2 != NULL) { if (head1->val < head2 -> val) { head1 = head1->next; pre = pre->next; } else { pre->next = head2; ListNode* temp = head2->next; head2->next = head1; head2 = temp; pre = pre->next; } } if (head2 != NULL) pre->next = head2; l1 = helper->next; return l1; } //use priority_queue(head) to contain the first element of each list, every time take the smallest one //from the heap to be inserted into the long list, and take its next element into the heap struct cmp { bool operator ()(const ListNode *a, const ListNode *b) {             return a->val > b->val;      } }; ListNode* mergeKLists(vector<ListNode*>& lists) { int size = lists.size(); if (size == 0) return NULL; ListNode* helper = new ListNode(0); ListNode* res = helper; priority_queue<ListNode*, vector<ListNode*>, cmp> que; for(int i = 0; i < size; i++) if(lists[i]) que.push(lists[i]); while(!que.empty()) { ListNode * p = que.top(); que.pop(); res->next = p; res = p; if(p->next) que.push(p->next); } ListNode* head = helper->next; return head; } }; <file_sep>/Kth_Largest_Element_In_An_Array.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Kth_Largest_Element_In_An_Array.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-31 20:38:23 // MODIFIED: 2015-05-31 21:09:29 #include <iostream> using namespace std; class Solution { public: int findKthLargest(vector<int> &nums, int k) { sort(nums.begin(), nums.end()); return nums[nums.size() - k]; } }; class QuickerSolution { public: int findKthLargest(vector<int> &nums, int k) { int L = 0, R = nums.size() - 1; while (L < R) { int left = L, right = R; int key = nums[left]; while (left < right) { while (left < right && nums[right] < key) right --; nums[left] = nums[right]; while (left < right && nums[left] >= key) left ++; nums[right] = nums[left]; } nums[left] = key; if (left == k - 1) return nums[left]; else if (left > k - 1) R = left - 1; else L = left + 1; } return nums[k - 1]; } }; <file_sep>/Maximum_Product_Subarray.cpp // C/C++ File // AUTHOR: laosi // FILE: Maximum_Product_Subarray.cpp // ROLE: TODO (some explanation) // CREATED: 2014-12-15 22:34:55 // MODIFIED: 2014-12-15 23:37:56 #include <iostream> using namespace std; class Solution { public: int maxProduct(int A[], int n) { if (n == 0) return 0; if (n == 1) return A[0]; int localMax = A[0]; int localMin = A[0]; int maxEle = A[0]; for (int i = 1; i < n; i ++) { int tempMax = A[i] > (localMax * A[i]) ? A[i] : (localMax * A[i]); int temp = localMax; localMax = tempMax > localMin * A[i] ? tempMax : localMin * A[i]; int tempMin = A[i] < temp * A[i] ? A[i] : temp * A[i]; localMin = tempMin < localMin * A[i] ? tempMin : localMin * A[i]; int tempCompare = maxEle > localMax ? maxEle : localMax; maxEle = tempCompare > localMin ? tempCompare : localMin; } return maxEle; } }; int main() { Solution s; int A[] = {-2, 3, -4}; cout << s.maxProduct(A, 3) << endl; int B[] = {2,-5,-2,-4,3}; cout << s.maxProduct(B, 5) << endl; return 0; } <file_sep>/Contains_Duplicate.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Contains_Duplicate.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-06-01 15:34:26 // MODIFIED: 2015-06-01 15:40:05 #include <iostream> using namespace std; class Solution { public: bool containsDuplicate(vector<int> &nums) { /* can also put nums into a set * then check if nums.size() > set.size() */ map<int, int>m; for (int i = 0; i < nums.size(); i ++) { if (m.find(nums[i]) == m.end()) m[nums[i]] = 1; else return true; } return false; } }; <file_sep>/Closest_Binary_Search_Tree_Value.cpp /********************************************************************************* * File Name : Closest_Binary_Search_Tree_Value.cpp * Created By : laosiaudi * Creation Date : [2015-10-25 14:56] * Last Modified : [2015-10-25 23:26] * Description : **********************************************************************************/ class Solution { public: int closestValue(TrieNode* root, double target) { double minValue = root->val; if (target < root->val) recursiveFind(root->left, target, minValue); else if (target > root->val) recursiveFind(root->right, target, minValue); return minValue; } void recursiveFind(TrieNode* root, double target, double &minValue) { if (root == NULL) return; double tmp = fabs(target, root->val); if (tmp < 0.0000001) { minValue = root->val; return; } if (tmp < fabs(target, minValue)) minValue = root->val; if (target < root->val) recursiveFind(root->left, target, minValue); else if (target > root->val) recursiveFind(root->right, target, minValue); } }; <file_sep>/Jump_Game.cpp // C/C++ File // AUTHOR: laosi // FILE: Jump_Game.cpp // ROLE: TODO (some explanation) // CREATED: 2014-12-15 23:47:47 // MODIFIED: 2014-12-16 02:17:29 #include <iostream> using namespace std; class Solution { //greedy public: bool canJump(int A[], int n) { int maxStep = 0; for (int start = 0; start <= maxStep && start < n; start ++) { if (A[start] + start > maxStep) maxStep = A[start] + start; if (maxStep >= n - 1) return true; } return false; } }; int main () { Solution s; int a[] = {2,0,6,9,8,4,5,0,8,9,1,2,9,6,8,8,0,6,3,1,2,2,1,2,6,5,3,1,2,2,6,4,2,4,3,0,0,0,3,8,2,4,0,1,2,0,1,4,6,5,8,0,7,9,3,4,6,6,5,8,9,3,4,3,7,0,4,9,0,9,8,4,3,0,7,7,1,9,1,9,4,9,0,1,9,5,7,7,1,5,8,2,8,2,6,8,2,2,7,5,1,7,9,6}; int *b = new int [25000]; for (int i = 0; i < 25000; i ++) b[i] = 25000 - i; if (s.canJump(b, 25000)) cout << "Yes\n"; return 0; } <file_sep>/Range_Sum_Query_2D_Immutable.cpp /********************************************************************************* * File Name : Range_Sum_Query_Immutable.cpp * Created By : laosiaudi * Creation Date : [2015-11-11 11:00] * Last Modified : [2015-11-13 15:46] * Description : **********************************************************************************/ class NumMatrix { public: vector<vector<int>>sum; NumMatrix(vector<vector<int>> &nums) { if (nums.size() == 0) ; else { sum.resize(nums.size()); for (int i = 0;i < nums.size(); i ++) sum[i].resize(nums[i].size(),0); sum[0][0] = nums[0][0]; for (int i = 1; i < nums[0].size(); i ++) sum[0][i] = sum[0][i - 1] + nums[0][i]; for (int i = 1; i < nums.size(); i ++) sum[i][0] = sum[i - 1][0] + nums[i][0]; for (int i = 1;i < nums.size(); i ++) { for (int j = 1; j < nums[0].size(); j ++) sum[i][j] = nums[i][j] + sum[i][j - 1] + sum[i - 1][j] - sum[i - 1][j - 1]; } } } int sumRegion(int row1, int col1, int row2, int col2) { int left = col1 > 0 ? sum[row2][col1 - 1] : 0; int right = row1 > 0 ? sum[row1 - 1][col2] : 0; int last = (row1 > 0 && col1 > 0) ? sum[row1 - 1][col1 - 1] : 0; return (sum[row2][col2] - left - right + last); } }; // Your NumMatrix object will be instantiated and called as such: // // NumMatrix numMatrix(matrix); // // numMatrix.sumRegion(0, 1, 2, 3); // // numMatrix.sumRegion(1, 2, 3, 4); <file_sep>/Single_Number.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Single_Number.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-25 10:12:20 // MODIFIED: 2015-04-25 10:14:02 #include <iostream> using namespace std; //使用异或的思想,出现两次就变成0 class Solution { public: int singleNumber(vector<int>& nums) { int n = nums.size(); if (n == 0) return -1; int ans = 0; for (int i = 0; i < n;i ++) ans ^= nums[i]; return ans; } }; <file_sep>/Delete_Node_In_A_Linked_List.cpp /********************************************************************************* * File Name : Delete_Node_In_A_Linked_List.cpp * Created By : laosiaudi * Creation Date : [2015-09-06 20:50] * Last Modified : [2015-09-06 20:58] * Description : **********************************************************************************/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; * */ class Solution { public: void deleteNode(ListNode* node) { if (node == NULL) return; node->val = node->next->val; ListNode* tmp = node->next; node->next = node->next->next; delete tmp; return; } }; <file_sep>/Integer_To_Roman.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Integer_To_Roman.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-11 16:59:17 // MODIFIED: 2015-05-11 17:32:38 #include <iostream> using namespace std; //classfiy digit of every bit //1:1,2,3 //2:4 //3:5 //4:6,7,8 //5:9 class Solution { public: string intToRoman(int num) { char symbos[7] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'}; string roman; int scale = 1000; int i = 6; while (1) { if (i < 0) break; int digit = num / scale; if (digit != 0) { if (digit <= 3 && digit >= 1) { roman.append(digit, symbos[i]); } else if (digit == 4) { roman.append(1, symbos[i]); roman.append(1, symbos[i + 1]); } else if (digit == 5) { roman.append(1, symbos[i + 1]); } else if (digit <= 8 && digit >= 6) { roman.append(1, symbos[i + 1]); roman.append(digit - 5, symbos[i]); } else { roman.append(1, symbos[i]); roman.append(1, symbos[i + 2]); } } i -= 2; num = num % scale; scale /= 10; } return roman; } }; <file_sep>/Combination_Sum.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Combination_Sum.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-22 17:20:46 // MODIFIED: 2015-04-22 18:39:51 #include <iostream> using namespace std; class Solution { public: vector<vector<int> > combinationSum(vector<int> &candidates, int target) { vector<vector<int> >v; int size = candidates.size(); if (size == 0) return v; sort(candidates.begin(), candidates.end()); for (int i = 0; i < size; i ++) { if (i > 0 && candidates[i] == candidates[i - 1]) continue; vector<int>temp; if (candidates[i] == target) { temp.push_back(candidates[i]); v.push_back(temp); } else { temp.push_back(candidates[i]); bool flag = recursiveFind(v, candidates, i, temp, candidates[i], target); temp.pop_back(); } } return v; } bool recursiveFind(vector<vector<int> > &v, vector<int> &candidates, int index, vector<int> &temp, int value, int target) { if (value == target) { v.push_back(temp); return true; } if (value > target) return false; int before = candidates[index]; for (int i = index; i < candidates.size(); i ++) { if (i > index && candidates[i] == candidates[i - 1]) continue; value += candidates[i]; temp.push_back(candidates[i]); bool flag = recursiveFind(v, candidates, i, temp, value, target); value -= candidates[i]; temp.pop_back(); } } }; <file_sep>/Subset.cpp // C/C++ File // AUTHOR: laosi // FILE: Subset.cpp // ROLE: TODO (some explanation) // CREATED: 2014-12-13 00:19:39 // MODIFIED: 2015-01-05 16:26:03 #include <iostream> using namespace std; //note: no-descending order--->> sort first, and select not to include the element first class Solution { public: vector<vector<int> > subsets(vector<int> &S) { vector<vector<int> >subsets; sort(S.begin(), S.end()); if (S.size() == 0) return subsets; vector<int>temp; temp.push_back(S[0]); vector<int>temp2; insert(subsets, 1, S.size(), temp2, S); insert(subsets, 1, S.size(), temp, S); return subsets; } void insert(vector<vector<int> >&v, int index, int length, vector<int> temp, vector<int> &S) { if (index == length) { v.push_back(temp); } else { insert(v, index + 1, length, temp, S); temp.push_back(S[index]); insert(v, index + 1, length, temp, S); } } }; <file_sep>/Plus_One.cpp // C/C++ File // AUTHOR: laosi // FILE: Plus_One.cpp // ROLE: TODO (some explanation) // CREATED: 2014-12-11 19:01:55 // MODIFIED: 2014-12-11 19:26:37 #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> plusOne(vector<int> &digits) { int add = 1; int temp; int newDigit = 0; for (int i = digits.size() - 1; i >= 0; i --) { if (digits[0] == 9 && add == 1 && i == 0) { digits[0] = 0; newDigit = 1; break; } temp = digits[i] + add; digits[i] = (temp >= 10 )?(temp - 10):(temp); add = temp >= 10?1:0; } if (newDigit == 1) digits.insert(digits.begin(), 1); return digits; } }; int main() { Solution s; int k[7] = {9,9,9,9,9,9,9}; vector<int>v; for (int i = 0;i < 7; i ++) v.push_back(k[i]); s.plusOne(v); return 0; } <file_sep>/Different_Ways_To_Add_Parentheses.cpp /********************************************************************************* * File Name : Different_Ways_To_Add_Parentheses.cpp * Created By : laosiaudi * Creation Date : [2015-10-20 21:39] * Last Modified : [2015-10-20 22:27] * Description : **********************************************************************************/ #include <iostream> #include <vector> using namespace std; class Solution { public: int compute(int a, int b, char op) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; } return 1; } vector<int> diffWaysToCompute(string input) { int val = 0, idx = 0; while (idx < input.length() && isdigit(input[idx])) { val *= 10; val += input[idx++] - '0'; } if (idx == input.length()) return {val}; vector<int> res; vector<int> left, right; for (int i = 0; i < input.length(); ++i) { if (!isdigit(input[i])) { left = diffWaysToCompute(input.substr(0, i)); right = diffWaysToCompute(input.substr(i + 1, input.length() -1 - i)); for (int j = 0; j < left.size(); ++j) { for (int k = 0; k < right.size(); ++k) { res.push_back(compute(left[j], right[k], input[i])); } } } } return res; } }; int main() { Solution s; vector<int>v = s.diffWaysToCompute("2-4"); for (auto i : v) cout << i << endl; return 0; } <file_sep>/Majority_Element_II.cpp /********************************************************************************* * File Name : Majority_Element_II.cpp * Created By : laosiaudi * Creation Date : [2015-09-24 16:02] * Last Modified : [2015-09-24 16:07] * Description : **********************************************************************************/ //Moore Voting https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm class Solution { public: vector<int> majorityElement(vector<int>& nums) { int num1 = 0, num2 = 0, cnt1 = 0, cnt2 = 0; vector<int>v; int size = nums.size(); for (int i = 0; i < size; i ++) { if (nums[i] == num1) cnt1 ++; else if (nums[i] == num2) cnt2 ++; else if (cnt1 == 0) { num1 = nums[i]; cnt1 = 1; } else if (cnt2 == 0) { num2 = nums[i]; cnt2 = 1; } else { cnt1 --; cnt2 --; } } cnt1 = 0, cnt2 = 0; for (int i = 0; i < size; i ++) { if (nums[i] == num1) cnt1 ++; else if (nums[i] == num2) cnt2 ++; } if (cnt1 > size / 3) v.push_back(num1); if (cnt2 > size / 3) v.push_back(num2); return v; } }; <file_sep>/Summary_Ranges.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Summary_Ranges.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-09-04 17:10:50 // MODIFIED: 2015-09-04 17:22:02 #include <iostream> using namespace std; class Solution { public: vector<string> summaryRanges(vector<int> &nums) { int n = nums.size(); string result = ""; vector<string> v; if (n == 0) return v; int start = nums[0]; int tmp = nums[0]; for (int i = 1; i < n; i ++) { if (nums[i] - tmp == 1) tmp = nums[i]; else { if (tmp == start) result = to_string(start); else result = to_string(start) + "->" + to_string(tmp); v.push_back(result); start = nums[i]; tmp = nums[i]; } } if (tmp == start) v.push_back(to_string(tmp)); else v.push_back(to_string(start) + "->" + to_string(tmp)); return v; } }; <file_sep>/Longest_Common_Prefix.cpp /********************************************************************************* * File Name : Longest_Common_Prefix.cpp * Created By : laosiaudi * Creation Date : [2015-10-26 00:20] * Last Modified : [2015-10-26 00:27] * Description : **********************************************************************************/ class Solution { public: string longestCommonPrefix(vector<string>& strs) { int size = strs.size(); if (size == 0) return ""; string compare = strs[0]; int len = compare.size(); for (int i = 0; i < len; i ++) { for (int j = 1; j < size; j ++) { if (i >= strs[j].size() || compare[i] != strs[j][i]) return compare.substr(0, i); } } return compare; } }; <file_sep>/Reverse_Integer.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Reverse_Integer.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-05 17:44:37 // MODIFIED: 2015-05-05 18:06:21 #include <iostream> using namespace std; class Solution { public: int reverse(int x) { bool isNega = false; if (x < 0) { isNega = true; x = - x; } long long res = 0;//handle overflow while (x != 0) { int temp = x % 10; res = res* 10 + temp; x = x / 10; } if (res > INT_MAX || res < INT_MIN) //handle overflow return 0; return isNega? -res:res; } }; <file_sep>/Unique_Binary_Search_Trees.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Unique_Binary_Search_Trees.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-20 22:53:28 // MODIFIED: 2015-05-20 23:06:06 #include <iostream> using namespace std; class Solution { public: int numTrees(int n) { vector<int>res(n + 1, 0); res[1] = 1; res[2] = 2; for (int i = 3; i <= n; i ++) { res[i] += 2*res[ i - 1]; int temp = (i - 1)/2; for (int j = 1; j <= temp; j ++) if (j * 2 == i - 1) res[i] = res[i] + res[j] * res[i - 1 - j]; else res[i] = res[i] + res[j] * res[i - 1 - j] * 2; } return res[n]; } }; <file_sep>/Set_Matrix_Zeroes.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Set_Matrix_Zeroes.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-18 16:12:42 // MODIFIED: 2015-04-18 16:40:10 #include <iostream> using namespace std; //O(m+n) space class Solution { public: void setZeroes(vector<vector<int> > &matrix) { int line = matrix.size(); if (line == 0) return ; int col = matrix[0].size(); vector<bool>row(line); vector<bool>column(col); for (int i = 0; i < line; i ++) { for (int j = 0; j < col; j ++) { if (matrix[i][j] == 0) { row[i] = true; column[j] = true; } } } for (int i = 0; i < line; i ++) { for (int j = 0; j < col; j ++) { if (row[i] || column[j]) matrix[i][j] = 0; } } } }; //O(1) space //use first row and col to record class Solution { public: void setZeroes(vector<vector<int> > &matrix) { int line = matrix.size(); if (line == 0) return ; int col = matrix[0].size(); bool firstRowZero = false; bool firstColZero = false; for (int i = 0 ;i < col; i ++) { if (matrix[0][i] == 0) { firstRowZero = true; break; } } for (int i = 0 ;i < line; i ++) { if (matrix[i][0] == 0) { firstColZero = true; break; } } for (int i = 0; i < line; i ++) { for (int j = 0; j < col; j ++) { if (matrix[i][j] == 0) { matrix[0][j] = 0; matrix[i][0] = 0; } } } for (int i = 1; i < line; i ++) { for (int j = 1; j < col; j ++) { if (matrix[i][0] == 0) matrix[i][j] = 0; if (matrix[0][j] == 0) matrix[i][j] = 0; } } if (firstRowZero) { for (int i = 0; i < col; i ++) matrix[0][i] = 0; } if (firstColZero) { for (int i = 0; i < line; i ++) matrix[i][0] = 0; } } }; <file_sep>/Happy_Number.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Happy_Number.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-25 18:13:39 // MODIFIED: 2015-04-25 18:19:19 #include <iostream> using namespace std; class Solution { public: bool isHappy(int n) { map<int, bool>check; int temp = n; while (1) { int ans = 0; while (1) { ans += (temp % 10) * (temp % 10); temp = temp / 10; if (temp == 0) break; } if (ans == 1) return true; if (check.find(ans) == check.end()) { check[ans] = true; } else { return false; } temp = ans; } } }; <file_sep>/google_summaryrange.cpp /********************************************************************************* * File Name : google_summaryrange.cpp * Created By : laosiaudi * Creation Date : [2015-10-16 00:48] * Last Modified : [2015-10-16 01:03] * Description : **********************************************************************************/ #include <iostream> #include <vector> #include <string> using namespace std; class Solution { public: vector<string> summaryRanges(vector<int> & nums) { vector<string>result; if (nums.size() == 0) return result; string tmp; tmp.push_back(nums[0] + '0'); for (int i = 1; i < nums.size(); i ++) { if (nums[i] - nums[i - 1] != 1) { if (nums[i - 1] + '0' == tmp[0]) result.push_back(tmp); else { tmp += "->"; tmp.push_back(nums[i - 1] + '0'); result.push_back(tmp); } tmp.clear(); tmp.push_back(nums[i] + '0'); } } if (nums[nums.size() - 1] + '0' == tmp[0]) result.push_back(tmp); else { tmp += "->"; tmp.push_back(nums[nums.size() - 1] + '0'); result.push_back(tmp); } return result; } }; int main() { vector<int>v; v.push_back(0); v.push_back(1); v.push_back(2); v.push_back(4); v.push_back(5); v.push_back(7); Solution s; vector<string> r = s.summaryRanges(v); for (string s : r) cout << s << endl; return 0; } <file_sep>/House_Robber_II.cpp // C/C++ File // AUTHOR: LaoSi // FILE: House_Robber_II.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-20 17:41:28 // MODIFIED: 2015-05-20 17:48:20 #include <iostream> using namespace std; class Solution { public: int rob(vector<int> &num) { int size = num.size(); if (size == 0) return 0; if (size == 1) return num[0]; //do not rob the first house vector<int>res1(size, 0); res1[1] = num[1]; for (int i = 2; i < size; i ++) { int temp = res1[i - 2] + num[i]; res1[i] = res1[i - 1] > temp ? res1[i - 1] : temp; } //rob the first house vector<int>res2(size, 0); res2[0] = num[0]; res2[1] = num[0]; for (int i = 2; i < size - 1; i ++) { int temp = res2[i - 2] + num[i]; res2[i] = res2[i - 1] > temp ? res2[i - 1] : temp; } return res1[size - 1] > res2[size - 2] ? res1[size - 1] : res2[size - 2]; } }; <file_sep>/Partition_List.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Partition_List.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-28 13:46:41 // MODIFIED: 2015-04-28 14:12:51 #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* partition(ListNode* head, int x) { if (head == NULL || head->next == NULL) return head; ListNode* small = new ListNode(0); ListNode* big = new ListNode(0); ListNode* walker = head; ListNode* smallWalker = small; ListNode* bigWalker = big; while (walker != NULL) { if (walker->val < x) { ListNode* temp = walker->next; smallWalker->next = walker; smallWalker = smallWalker->next; walker = temp; } else { ListNode* temp = walker->next; bigWalker->next = walker; bigWalker = bigWalker->next; walker = temp; } } bigWalker->next = NULL; smallWalker->next = big->next; head = small->next; delete small; delete big; return head; } }; //也可以找到第一个不小于x的节点,然后往它的左边一直插入小于x的节点 <file_sep>/Implement_strStr.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Implement_strStr.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-18 17:01:53 // MODIFIED: 2015-05-18 17:27:12 #include <iostream> using namespace std; //KMP algorithm class Solution { public: int strStr(string haystack, string needle) { if (needle == "") return 0; if (haystack == "") return -1; int m = haystack.size(); int n = needle.size(); vector<int> next = getNext(needle); int j = -1; for (int i = 0; i < m;i ++) { while (j >= 0 && haystack[i] != needle[j + 1]) j = next[j]; if (haystack[i] == needle[j + 1]) j ++; if (j == n - 1) return (i - n + 1); } return -1; } vector<int> getNext(string s) { int n = s.size(); vector<int> next(n, -1); int k = -1; int j = 1; for (; j < n; j ++) { while (k >= 0 && s[k + 1] != s[j]) k = next[k]; if (s[k + 1] == s[j]) k ++; next[j] = k; } return next; } }; <file_sep>/Insertion_Sort_List.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Insertion_Sort_List.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-30 11:11:23 // MODIFIED: 2015-04-30 12:02:56 #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* insertionSortList(ListNode* head) { if (head == NULL || head->next == NULL) return head; ListNode* helper = new ListNode(0); helper->next = head; ListNode* pre = helper; ListNode* com = head; while (com != NULL) { ListNode* tempPre = helper; ListNode* walker = helper->next; bool ischange = false; while (walker != com) { if (walker->val <= com->val) { tempPre = tempPre->next; walker = walker->next; } else { ListNode* nextNode = com->next; pre->next = nextNode; tempPre->next = com; com->next = walker; com = pre->next; ischange = true; break; } } if (ischange == false) { pre = pre->next; com = com->next; } } head = helper->next; delete helper; return head; } }; //another simple solution class Solution { public: ListNode* insertionSortList(ListNode* head) { if (head == NULL || head->next == NULL) return head; ListNode* helper = new ListNode(0); ListNode* com = head; while (com != NULL) { ListNode* tempPre = helper; ListNode* next = com->next; while (tempPre->next != NULL && tempPre->next->val <= com->val) { tempPre = tempPre->next; } com->next = tempPre->next; tempPre->next = com; com = next; } head = helper->next; delete helper; return head; } }; <file_sep>/Pascal_Trangle.cpp // C/C++ File // AUTHOR: laosi // FILE: Pascal_Trangle.cpp // ROLE: TODO (some explanation) // CREATED: 2014-12-11 22:27:07 // MODIFIED: 2014-12-11 22:49:54 #include <iostream> #include <vector> using namespace std; class Solution { public: vector<vector<int> > generate(int numRows) { vector<vector<int> >v; for (int i = 0; i < numRows; i ++) { vector<int>temp; int index = i + 1; for (int j = 0; j< index; j ++) { if (j == 0 || j == index - 1) temp.insert(temp.begin() + j, 1); else { temp.insert(temp.begin() + j,v[i - 1][j - 1] + v[i - 1][j]); } } v.insert(v.begin() + i, temp); } return v; } }; int main() { Solution s; s.generate(5); return 0; } <file_sep>/Minimum_Depth_of_Binary_Tree.cpp /********************************************************************************* * File Name : Minimum_Depth_of_Binary_Tree.cpp * Created By : laosiaudi * Creation Date : [2015-09-10 16:14] * Last Modified : [2015-09-10 16:31] * Description : **********************************************************************************/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; * */ class Solution { public: int minDepth(TreeNode* root) { if (root == NULL) return 0; int tmp = 1; queue<TreeNode*>q; q.push(root); while (!q.empty()) { int len = q.size(); for (int i = 0; i < len; i ++) { TreeNode* tmn = q.front(); q.pop(); if (tmn->left == NULL && tmn->right == NULL) return tmp; else { if (tmn->left != NULL) q.push(tmn->left); if (tmn->right != NULL) q.push(tmn->right); } } tmp ++; } return tmp; } //another solution int minDepth(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if(root == NULL) return 0; int lmin = minDepth(root->left); int rmin = minDepth(root->right); if(lmin ==0 && rmin ==0) return 1; if(lmin ==0) { lmin = INT_MAX; } if(rmin ==0){ rmin = INT_MAX; } return min(lmin, rmin) +1; } }; <file_sep>/Implement_Stack_using_Queues.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Implement_Stack_using_Queues.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-08-21 17:24:38 // MODIFIED: 2015-08-21 17:28:01 #include <iostream> using namespace std; class Stack { public: vector<int>q; // Push element x onto stack. void push(int x) { q.push_back(x); } // Removes the element on top of the stack. void pop() { q.erase(q.end() - 1); } // Get the top element. int top() { return q[q.size() - 1]; } // Return whether the stack is empty. bool empty() { return q.size() == 0; } }; <file_sep>/Excel_Sheet_Column_Number.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Excel_Sheet_Column_Number.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-07 16:52:35 // MODIFIED: 2015-05-07 16:55:58 #include <iostream> using namespace std; class Solution { public: int titleToNumber(string s) { int size = s.size(); int base = 1; int res = 0; for (int i = size - 1; i >= 0;i --) { res += (s[i] - 'A' + 1)*base; base *= 26; } return res; } }; <file_sep>/Search_A_2D_Matrix_II.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Search_A_2D_Matrix_II.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-09-02 20:09:24 // MODIFIED: 2015-09-02 20:23:56 #include <iostream> using namespace std; class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int line = matrix.size(); if (line == 0) return false; int top = line - 1; int bottom = 0; int mid = (top + bottom) / 2; while (top >= bottom && matrix[mid][0] <= target) { if (matrix[mid][0] == target) return true; bottom = mid + 1; mid = (bottom + top) / 2; } if (line != 1 && matrix[mid][0] > target) mid = mid - 1; int i = mid; for (; i >= 0; i --) { int size = matrix[i].size(); top = size - 1; bottom = 0; while (top >= bottom) { int tmp = (top + bottom) / 2; if (matrix[i][tmp] > target) top = tmp - 1; else if (matrix[i][tmp] < target) bottom = tmp + 1; else return true; } } return false; } }; <file_sep>/Interleaving_String.cpp /********************************************************************************* * File Name : Interleaving_String.cpp * Created By : laosiaudi * Creation Date : [2015-10-23 21:35] * Last Modified : [2015-10-23 22:39] * Description : **********************************************************************************/ #include <vector> #include <string> using namespace std; class Solution { public: bool isInterleave(string s1, string s2, string s3) { if (s3.size() != s1.size() + s2.size()) return false; vector<bool>col(s2.size() + 1, false); vector<vector<bool>> v(s1.size() + 1, col); v[0][0] = true; for (int i = 1; i <= s2.size(); i ++) v[0][i] = (s2[i - 1] == s3[i - 1]) && v[0][i - 1]; for (int i = 1; i <= s1.size(); i ++) v[i][0] = (s1[i - 1] == s3[i - 1]) && v[i - 1][0]; for (int i = 1; i <= s1.size(); i ++) { for (int j = 1; j <= s2.size(); j ++) { v[i][j] = ((s2[j - 1] == s3[i + j - 1]) && v[i][j - 1]) || ((s1[i - 1]) == s3[i + j - 1] && v[i - 1][j]); } } return v[s1.size()][s2.size()]; } }; <file_sep>/Gas_Station.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Gas_Station.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-06-04 12:37:02 // MODIFIED: 2015-06-04 12:59:20 #include <iostream> using namespace std; class Solution { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int index = 0; int size = gas.size(); int total = 0; int local = 0; for (int i = 0; i < size; i ++) { int amount = gas[i] - cost[i]; total += amount; local += amount; if (local < 0) { index = i + 1; local = 0; } } if (total >= 0) return index; else return -1; } }; <file_sep>/google_isstrobo.cpp /********************************************************************************* * File Name : google_isstrobo.cpp * Created By : laosiaudi * Creation Date : [2015-10-15 23:22] * Last Modified : [2015-10-15 23:32] * Description : **********************************************************************************/ #include <iostream> #include <map> #include <stdio.h> #include <stdlib.h> using namespace std; class Solution { public: bool isStrobogrammatic(string num) { int size = num.size(); if (size == 0) return false; map<char, char>digit; digit['0'] = '0'; digit['1'] = '1'; digit['6'] = '9'; digit['8'] = '8'; digit['9'] = '6'; string new_num; for (int i = num.size() - 1; i >= 0; i --) { if (digit.find(num[i]) == digit.end()) return false; new_num.push_back(digit[num[i]]); } return new_num.compare(num) == 0; } }; int main() { Solution s; if (s.isStrobogrammatic("69")) printf("69\n"); if (s.isStrobogrammatic("0")) printf("0\n"); if (s.isStrobogrammatic("123")) printf("error\n"); if (s.isStrobogrammatic("88")) printf("88\n"); if (s.isStrobogrammatic("169")) printf("error\n"); if (s.isStrobogrammatic("619")) printf("619\n"); if (s.isStrobogrammatic("101")) printf("101\n"); return 0; } <file_sep>/Add_Two_Numbers.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Add_Two_Numbers.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-30 16:02:32 // MODIFIED: 2015-05-05 10:40:10 #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* helper = new ListNode(-1); ListNode* pre = helper; ListNode* walker1 = l1; ListNode* walker2 = l2; int carry = 0; while (walker1 != NULL || walker2 != NULL) { int va1 = walker1 == NULL ? 0 : walker1->val; int va2 = walker2 == NULL ? 0 : walker2->val; ListNode* newNode = new ListNode((va1 + va2 + carry) %10); carry = (va1 + va2 + carry)/10; pre->next = newNode; pre = newNode; walker1 = walker1 == NULL ? NULL : walker1->next; walker2 = walker2 == NULL ? NULL : walker2->next; } if (carry > 0) pre->next = new ListNode(1); ListNode* head = helper->next; delete helper; return head; } }; <file_sep>/Sliding_Window_Maximum.cpp /********************************************************************************* * File Name : Sliding_Window_Maximum.cpp * Created By : laosiaudi * Creation Date : [2015-11-15 17:38] * Last Modified : [2015-11-15 19:56] * Description : **********************************************************************************/ class Solution { public: vector<int> simple_maxSlidingWindow(vector<int>& nums, int k) { vector<int>result; deque<int>q; for (int i = 0; i < nums.size(); i ++) { if (!q.empty() && q.front() == i - k) q.pop_front(); while (!q.empty() && nums[q.back()] < nums[i]) q.pop_back(); q.push_back(i); if (i >= k - 1) result.push_back(nums[q.front()]); } return result; } vector<int> maxSlidingWindow(vector<int>& nums, int k) { vector<int>result; if (k == 0 || nums.size() == 0) return result; priority_queue<int>q; map<int, int>m; for (int i = 0; i < k; i ++) { q.push(nums[i]); if (m.find(nums[i]) == m.end()) m[nums[i]] = 1; else m[nums[i]] ++; } result.push_back(q.top()); for (int i = k; i < nums.size(); i ++) { int top = q.top(); m[nums[i - k]] --; while (m[top] == 0) { q.pop(); if (q.empty()) break; top = q.top(); } q.push(nums[i]); if (m.find(nums[i]) == m.end()) m[nums[i]] = 1; else m[nums[i]] ++; result.push_back(q.top()); } return result; } }; <file_sep>/Best_Time_To_Buy_And_Sell_Stock_II.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Best_Time_To_Buy_And_Sell_Stock_II.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-01-30 11:15:10 // MODIFIED: 2015-01-30 11:18:11 #include <iostream> using namespace std; class Solution { public: int maxProfit(vector<int> &prices) { int length = prices.size(); if (length == 0) return 0; int bestProfit = 0; for (int i = 1; i < length; i ++) { if (prices[i] > prices[i - 1]) { bestProfit += (prices[i] - prices[i - 1]); } } return bestProfit; } }; <file_sep>/Add_Binary.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Add_Binary.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-06 13:34:33 // MODIFIED: 2015-05-06 13:44:44 #include <iostream> using namespace std; class Solution { public: string addBinary(string a, string b) { int len1 = a.size(); int len2 = b.size(); int maxLen = len1 > len2 ? len1 : len2; string res(maxLen, ' '); maxLen--; int carry = 0; for (int i = len1 - 1, j = len2 - 1;i >= 0 || j >= 0; i --, j --) { int av = (i >= 0?a[i]:'0') - '0'; int bv = (j >= 0?b[j]:'0') - '0'; int temp = av + bv + carry; carry = temp / 2; temp = temp % 2; res[maxLen--] = temp + '0'; } if (carry > 0) res = "1" + res; return res; } }; <file_sep>/Valid_Parentheses.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Valid_Parentheses.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-14 00:06:12 // MODIFIED: 2015-05-14 00:14:06 #include <iostream> using namespace std; class Solution { public: bool isValid(string s) { int size = s.size(); if (size == 0) return false; stack<char>ss; map<char, int>m; m['('] = 1; m[')'] = -1; m['['] = 2; m[']'] = -2; m['{'] = 3; m['}'] = -3; for (int i = 0; i < size; i ++) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') ss.push(s[i]); else { if (ss.empty()) return false; if (m[ss.top()] + m[s[i]] == 0) ss.pop(); else ss.push(s[i]); } } return ss.empty(); } }; <file_sep>/Shortest_Word_Distance.cpp /********************************************************************************* * File Name : Shortest_Word_Distance.cpp * Created By : laosiaudi * Creation Date : [2015-11-01 22:47] * Last Modified : [2015-11-01 22:51] * Description : **********************************************************************************/ class Solution { public: int shortestDistance(vector<string>& words, string word1, string word2) { int n = words.size(); int idx1 = -1, idx2 = -1, min_val = INT_MAX; for (int i = 0; i < n; i ++) { if (words[i] == word1) idx1 = i; if (words[i] == word2) idx2 = i; if (idx1 != -1 && idx2 != -1) min_val = min(min_val, abs(idx1 - idx2)); } return min_val; } }; <file_sep>/Binary_Tree_Preorder_Traversal.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Binary_Tree_Preorder_Traversal.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-06-02 17:00:48 // MODIFIED: 2015-06-02 17:15:33 #include <iostream> using namespace std; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int>res; if (root == NULL) return res; stack<TreeNode*>s; s.push(root); while (!s.empty()) { TreeNode* temp = s.top(); s.pop(); res.push_back(temp->val); if (temp->right) s.push(temp->right); if (temp->left) s.push(temp->left); } return res; } }; <file_sep>/Reverse_Linked_List.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Reverse_Linked_List.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-16 14:29:35 // MODIFIED: 2015-05-16 14:50:21 #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* pre = NULL; ListNode* walker = head; while (walker != NULL) { ListNode* temp = walker->next; walker->next = pre; pre = walker; walker = temp; } head = pre; return head; } }; //Recursive Version class Solution { public: ListNode* reverseList(ListNode* head) { if (head == NULL || head->next == NULL) return head; ListNode* temp = head->next; head->next = NULL; return recursiveReverse(head, temp); } ListNode* recursiveReverse(ListNode* pre, ListNode* cur) { if (cur->next == NULL) { cur->next = pre; return cur; } ListNode* temp = cur->next; cur->next = pre; return recursiveReverse(cur, temp); } }; <file_sep>/Longest_Consecutive_Sequence.cpp /********************************************************************************* * File Name : Longest_Consecutive_Sequence.cpp * Created By : laosiaudi * Creation Date : [2015-10-28 22:20] * Last Modified : [2015-10-28 22:29] * Description : **********************************************************************************/ class Solution { public: int longestConsecutive(vector<int>& nums) { if (nums.size() == 0) return 0; unordered_set<int>s; for (auto item : nums) s.insert(item); int maxLen = 1; while (!s.empty()) { auto item = *(std::begin(s)); queue<int>q; int tmp = 1; q.push(item); while (!q.empty()) { int target = q.front(); s.erase(target); q.pop(); if (s.find(target + 1) != std::end(s)) { tmp ++; q.push(target + 1); } if (s.find(target - 1) != std::end(s)) { tmp ++; q.push(target - 1); } } maxLen = max(maxLen, tmp); } return maxLen; } }; <file_sep>/Convert_Sorted_Array_To_Binary_Search_Tree.cpp /********************************************************************************* * File Name : Convert_Sorted_Array_To_Binary_Search_Tree.cpp * Created By : laosiaudi * Creation Date : [2015-09-07 13:22] * Last Modified : [2015-09-07 13:36] * Description : **********************************************************************************/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; * */ class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums) { int n = nums.size(); if (n == 0) return NULL; int mid = (n - 1)/2; TreeNode* root = new TreeNode(nums[mid]); if (0 <= mid - 1) root->left = constructSubTree(0, mid - 1, nums); if (mid + 1 <= n - 1) root->right = constructSubTree(mid + 1, n - 1, nums); return root; } TreeNode* constructSubTree(int start, int end, vector<int>& nums) { int index = (start + end)/2; int rootVal = nums[index]; TreeNode* root = new TreeNode(rootVal); if (start <= index - 1) root->left = constructSubTree(start, index - 1, nums); if (index + 1 <= end) root->right = constructSubTree(index + 1, end, nums); return root; } }; <file_sep>/Minimum_Size_Subarray_Sum.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Minimum_Size_Subarray_Sum.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-13 21:53:16 // MODIFIED: 2015-05-14 00:03:30 #include <iostream> using namespace std; class Solution { public: int minSubArrayLen(int s, vector<int> &nums) { int len = nums.size(); if (len == 0) return 0; int start = 0, end = 0; int sum = 0; int res = len + 1; for (; end < len; end ++) { sum += nums[end]; while (sum >= s) { res = res < (end - start + 1) ? res : (end - start + 1); sum -= nums[start ++]; } } if (res == len + 1) return 0; return res; } }; <file_sep>/Binary_Search_Tree_Iterator.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Binary_Search_Tree_Iterator.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-06-02 17:36:07 // MODIFIED: 2015-06-02 17:45:10 #include <iostream> using namespace std; /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class BSTIterator { public: BSTIterator(TreeNode *root) { //get inorder traversal v = inorderTraversal(root); index = 0; } /** @return whether we have a next smallest number */ bool hasNext() { if (v.size() == 0) return false; else return index < v.size(); } /** @return the next smallest number */ int next() { int temp = index; index ++; return v[temp]; } vector<int> inorderTraversal(TreeNode *root) { vector<int>v; if (root == NULL) return v; recursiveTraversal(v, root->left); v.push_back(root->val); recursiveTraversal(v, root->right); return v; } void recursiveTraversal(vector<int> &v, TreeNode *root) { if (root == NULL) return; recursiveTraversal(v, root->left); v.push_back(root->val); recursiveTraversal(v,root->right); } private: vector<int>v; int index; }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */ <file_sep>/Reverse_Words_In_A_String.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Reverse_Words_In_A_String.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-14 23:03:16 // MODIFIED: 2015-05-14 23:27:03 #include <iostream> using namespace std; class Solution { public: void reverseWords(string &s) { int size = s.size(); if (size == 0) return; stack<string>ss; string res; for (int i = 0; i < size;) { while (s[i] == ' ' && i < size) i ++; if (i == size) break; int start = i; while (s[i] != ' ' && i < size) i ++; int end = i; string element = s.substr(start, end - start); ss.push(element); } while (ss.size() > 1) { res = res + ss.top() + " "; ss.pop(); } if (ss.size() == 1) res += ss.top(); s = res; } }; //if want to O(1) in-place, first reverse the whole string, and then reverse every word //reverse a string can use in-place way: swap the chars of s[i] and s[len - 1 -n] <file_sep>/Convert_Sorted_List_To_Binary_Search_Tree.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Convert_Sorted_List_To_Binary_Search_Tree.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-30 15:25:48 // MODIFIED: 2015-04-30 15:58:35 #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *sortedListToBST(ListNode *head) { if (head == NULL) return NULL; ListNode* walker = head; ListNode* runner = head->next; while (walker != NULL && runner != NULL && runner->next != NULL) { walker = walker->next; runner = runner->next->next; } TreeNode* root = new TreeNode(walker->val); TreeNode* leftNode = recursiveBuild(head, walker); TreeNode* rightNode = recursiveBuild(walker->next, NULL); root->left = leftNode; root->right = rightNode; return root; } TreeNode* recursiveBuild(ListNode* head, ListNode* end) { if (head == end) return NULL; ListNode* walker = head; ListNode* runner = head->next; while (walker != end && runner != end && runner->next != end) { walker = walker->next; runner = runner->next->next; } TreeNode* root = new TreeNode(walker->val); TreeNode* leftNode = recursiveBuild(head, walker); TreeNode* rightNode = recursiveBuild(walker->next, end); root->left = leftNode; root->right = rightNode; return root; } }; <file_sep>/3Sum_Closest.cpp // C/C++ File // AUTHOR: LaoSi // FILE: 3Sum_Closest.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-22 17:03:11 // MODIFIED: 2015-04-22 17:17:54 #include <iostream> using namespace std; class Solution { public: int threeSumClosest(vector<int> &num, int target) { if (num.size() <= 2) return 0; sort(num.begin(), num.end()); int minValue = 999999; int result = 0; for (int i = 0; i <= num.size() - 3; i ++) { if (i > 0 && num[i] == num[i - 1]) continue; int start = i + 1; int end = num.size() - 1; while (start < end) { if (start > i + 1 && num[start] == num[start - 1]) { start ++; continue; } if (end < num.size() - 1 && num[end] == num[end + 1]) { end --; continue; } if (num[start] + num[end] + num[i] - target >= 0) { int e = abs(num[start] + num[end] + num[i] - target); if (e < minValue) { result = num[start] + num[end] + num[i]; minValue = e; } end --; } else { int e = abs(num[start] + num[end] + num[i] - target); if (e < minValue) { result = num[start] + num[end] + num[i]; minValue = e; } start ++; } } } return result; } }; <file_sep>/Sum_Root_To_Leaf_Numbers.cpp /********************************************************************************* * File Name : Sum_Root_To_Leaf_Numbers.cpp * Created By : laosiaudi * Creation Date : [2015-09-08 14:48] * Last Modified : [2015-09-08 14:58] * Description : **********************************************************************************/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; * */ class Solution { public: int sumNumbers(TreeNode* root) { if (root == NULL) return 0; int sum = 0; int temp = 0; getSum(root, sum, root->val); return sum; } void getSum(TreeNode* root, int &sum, int temp) { if (root->left == NULL && root->right == NULL) { sum += temp; return; } if (root->left) getSum(root->left, sum, temp*10 + root->left->val); if (root->right) getSum(root->right, sum, temp*10 + root->right->val); } }; <file_sep>/Trapping_Rain_Water.cpp /********************************************************************************* * File Name : Trapping_Rain_Water.cpp * Created By : laosiaudi * Creation Date : [2015-09-05 19:46] * Last Modified : [2015-09-05 21:56] * Description : **********************************************************************************/ #include <iostream> #include <vector> #include <stack> using namespace std; class Solution { public: //best solution 8ms //reference:http://blog.unieagle.net/2012/10/31/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Atrapping-rain-water/ int bestTrap(vector<int> &water) { int size = water.size(); int sum = 0; if (size < 2) return sum; int *maxHeightLeft = new int[size]; int maxValue = water[0]; for (int i = 0; i < size; i ++) { maxHeightLeft[i] = maxValue; maxValue = maxValue > water[i] ? maxValue : water[i]; } int *maxHeightRight = new int[size]; maxValue = water[size - 1]; for (int i = size - 1; i >= 0; i --) { maxHeightRight[i] = maxValue; maxValue = maxValue > water[i] ? maxValue : water[i]; int tmp = maxHeightLeft[i] < maxHeightRight[i]? maxHeightLeft[i] : maxHeightRight[i]; if (tmp > water[i]) sum += (tmp - water[i]); } delete []maxHeightLeft; delete []maxHeightRight; return sum; } //12ms int trap(vector<int>& water) { int size = water.size(); if (size == 0) return 0; int sum = 0; int start = 0; for (int i = 0; i < size; i ++) { if (water[i] != 0) { start = i; break; } } int count = 0; int i = start + 1; if (i >= size) return 0; stack<int>s; while (i < size) { if (water[i] < water[start]) { while (!s.empty() && water[s.top()] < water[i]) { count += water[s.top()]; s.pop(); } s.push(i); } else { while (!s.empty()) { count += water[s.top()]; s.pop(); } sum += (i - start - 1) * water[start]; sum -= count; count = 0; start = i; } i ++; } if (!s.empty()) { i = s.top(); s.pop(); int h = water[i]; while (!s.empty()) { sum += h * (i - s.top() - 1); i = s.top(); h = water[i]; s.pop(); } sum += h * (i - start - 1); sum -= count; } return sum; } }; <file_sep>/Remove_Linked_List_Elements.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Remove_Linked_List_Elements.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-27 11:06:37 // MODIFIED: 2015-04-27 11:16:35 #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeElements(ListNode* head, int val) { if (head == NULL) return head; ListNode* helper = new ListNode(0); helper->next = head; ListNode* walker = helper; while (walker->next != NULL) { if (walker->next->val == val) { walker->next = walker->next->next; } else { walker = walker->next; } } head = helper->next; delete helper; return head; } }; <file_sep>/Word_Search.cpp // C/C++ File // AUTHOR: laosi // FILE: Word_Search.cpp // ROLE: TODO (some explanation) // CREATED: 2014-12-12 22:52:45 // MODIFIED: 2014-12-12 23:20:23 // use DFS, if use BFS, will exceed the limit of stack space #include <iostream> using namespace std; class Solution { public: bool exist(vector<vector<char> > &board, string word) { int m = board.size(); int n = board[0].size(); vector<bool> mark(m*n, false); for (int i = 0; i < m; ++i){ for (int j = 0; j < n; ++j) { mark.clear(); mark.resize(m*n, false); if (worker(board, mark, word, i, j, 0)) return true; } } return false; } bool worker(vector<vector<char> > &board, vector<bool> &mark, string &word, int x, int y, int k) { int m = board.size(); int n = board[0].size(); if (k == word.size()) return true; else if (x < 0 || x >= m || y < 0 || y >= n || mark[x*n + y] == true || word[k] != board[x][y]) return false; else { mark[x*n+y] = true; if (worker(board, mark, word, x+1, y, k+1)) return true; if (worker(board, mark, word, x-1, y, k+1)) return true; if (worker(board, mark, word, x, y+1, k+1)) return true; if (worker(board, mark, word, x, y-1, k+1)) return true; mark[x*n+y] = false; return false; } } }; <file_sep>/Search_Insert_Position.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Search_Insert_Position.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-01-05 14:38:02 // MODIFIED: 2015-01-05 14:53:23 #include <iostream> using namespace std; class Solution { public: int searchInsert(int A[], int n, int target) { return binarySearch(A, 0, n - 1, target); } int binarySearch(int A[], int start, int end, int target) { if (start == end) { if (target <= A[start]) return start; else return start + 1; } int pivot = (start + end)/2; int result = -1; if (target <= A[pivot]) result = binarySearch(A, start, pivot, target); else result = binarySearch(A, pivot + 1, end, target); return result; } }; int main() { Solution s; int a[4] = {1,3,5,6}; cout << s.searchInsert(a, 4, 5) << endl; cout << s.searchInsert(a, 4, 2) << endl; cout << s.searchInsert(a, 4, 7) << endl; cout << s.searchInsert(a, 4, 0) << endl; } <file_sep>/Binary_Tree_Postorder_Traversal.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Binary_Tree_Postorder_Traversal.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-06-02 17:17:25 // MODIFIED: 2015-06-02 17:34:49 #include <iostream> using namespace std; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: //modify original structure vector<int> postorderTraversal(TreeNode* root) { vector<int>res; if (root == NULL) return res; stack<TreeNode*>s; s.push(root); while (!s.empty()) { TreeNode* tn = s.top(); s.pop(); TreeNode* ln = tn->left; TreeNode* rn = tn->right; tn->left = NULL; tn->right = NULL; if (ln == NULL && rn == NULL) { res.push_back(tn->val); } else { s.push(tn); } if (rn) s.push(rn); if (ln) s.push(ln); } return res; } }; class BetterSolution { public://do not modify the tree structure vector<int> postorderTraversal(TreeNode* root) { vector<int>res; stack<int>resStack; if (root == NULL) return res; stack<TreeNode*>s; s.push(root); while (!s.empty()) { TreeNode* tn = s.top(); s.pop(); TreeNode* ln = tn->left; TreeNode* rn = tn->right; resStack.push(tn->val); if (ln) s.push(ln); if (rn) s.push(rn); } while (!resStack.empty()) { res.push_back(resStack.top()); resStack.pop(); } return res; } }; <file_sep>/Repeated_DNA_Sequences.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Repeated_DNA_Sequences.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-25 10:23:32 // MODIFIED: 2015-04-25 17:48:06 #include <iostream> #include <string> #include <vector> #include <map> #include <math.h> using namespace std; //MLE version, need to encode the string class Solution { public: vector<string> findRepeatedDnaSequences(string s) { vector<string>v; map<string , bool>m; if (s.size() < 10) return v; for (int i = 0; i < s.size() - 10; i ++) { string temp = s.substr(i, 10); if (m.find(temp) == m.end()) m[temp] = false; else { if (m[temp] != true) { m[temp] = true; v.push_back(temp); } } } return v; } }; //442ms class BetterSolution { public: vector<string> findRepeatedDnaSequences(string s) { vector<string>v; map<int , bool>m; if (s.size() < 10) return v; for (int i = 0; i < s.size() - 9; i ++) { string temp = s.substr(i, 10); int num = string2Long(temp); if (m.find(num) == m.end()) m[num] = false; else { if (m[num] != true) { m[num] = true; v.push_back(long2String(num)); } } } return v; } long string2Long(string s) { long num = 0; char trans[20]; int index = 0; for (int i = 0; i < 10; i ++) { if (s[i] == 'A') { trans[index ++] = '0'; trans[index ++] = '0'; } else if (s[i] == 'C') { trans[index ++] = '0'; trans[index ++] = '1'; } else if (s[i] == 'G') { trans[index ++] = '1'; trans[index ++] = '0'; } else { trans[index ++] = '1'; trans[index ++] = '1'; } } index = 0; for (int i = 19; i >= 0; i --) { if (trans[i] == '1') num += 1 * pow(2, index++); else index ++; } return num; } string long2String(long num) { string s(10, ' '); int single = 3; int index = 0; for (int i = 18; i >= 0; i -= 2) { int temp = num & (single << i); temp = temp >> i; if (temp == 0) s[index ++] = 'A'; else if (temp == 1) s[index ++] = 'C'; else if (temp == 2) s[index ++] = 'G'; else s[index ++] = 'T'; } return s; } }; //258ms class BestSolution { public: vector<string> findRepeatedDnaSequences(string s) { vector<string> ans; int result = 0; if (s.size() < 10) return ans; map<char, int>m; m['A'] = 0; m['C'] = 1; m['G'] = 2; m['T'] = 3; map<int, bool>check; for (int i = 0; i < 10; i ++) result = (result << 2) + m[s[i]]; check[result] = false; for (int i = 10; i < s.size(); i ++) { result = ((result & 0x3ffff)<< 2) + m[s[i]]; //不加&0x3ffff就会一直忘左移而不会将最高位丢掉,知道左移到硬件上能到的最高的位数 if (check.find(result) == check.end()) check[result] = false; else { if (check[result] != true) { check[result] = true; ans.push_back(string(s, i - 9, 10)); } } } return ans; } }; int main() { string s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"; string t = "AAAAAAAAAAA"; BestSolution ss; vector<string> v = ss.findRepeatedDnaSequences(s); for (int i = 0; i < v.size(); i ++) cout << v[i] << endl; vector<string> vv = ss.findRepeatedDnaSequences(t); for (int i = 0; i < vv.size(); i ++) cout << vv[i] << endl; return 0; } <file_sep>/Path_Sum_II.cpp /********************************************************************************* * File Name : Path_Sum_II.cpp * Created By : laosiaudi * Creation Date : [2015-09-10 15:21] * Last Modified : [2015-09-10 15:30] * Description : **********************************************************************************/ /** * Definition for a binary tree node. * * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; * */ class Solution { public: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> v; if (root == NULL) return v; vector<int>tmpV; getSum(root, 0, sum, v, tmpV); return v; } void getSum(TreeNode* root, int tmp, int sum, vector<vector<int>> &v, vector<int>tmpV) { if (root == NULL) return; if (root->left == NULL && root->right == NULL) { if (tmp + root->val == sum) { tmpV.push_back(root->val); v.push_back(tmpV); } return; } tmpV.push_back(root->val); getSum(root->left, tmp + root->val, sum, v, tmpV); getSum(root->right, tmp + root->val, sum, v, tmpV); return; } }; <file_sep>/Ugly_Number.cpp /********************************************************************************* * File Name : Ugly_Number.cpp * Created By : laosiaudi * Creation Date : [2015-09-06 21:06] * Last Modified : [2015-09-06 21:18] * Description : **********************************************************************************/ #include <iostream> using namespace std; class Solution { public: bool isUgly(int num) { if (num <= 0) return false; if (num == 1) return true; int div[3] = {2, 3, 5}; int base = 0; int tmp = num; while (base <= 2) { if (tmp % div[base] == 0) tmp = tmp / div[base]; else base ++; if (tmp == 1) return true; } return false; } }; <file_sep>/Search_In_Rotated_Sorted_Array_II.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Search_In_Rotated_Sorted_Array_II.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-23 17:21:59 // MODIFIED: 2015-04-23 17:41:56 #include <iostream> using namespace std; class Solution { //O(n) better to use linear search public: bool search(vector<int>& nums, int target) { int num = nums.size(); if (num == 0) return false; return recursiveSearch(nums, target, 0, num - 1); } bool recursiveSearch(vector<int> &nums, int target, int start, int end) { if (start > end) return false; if (start == end) return nums[start] == target? true : false; int middle = (start + end)/2; if (nums[middle] == target) return true; if (nums[middle] < nums[end]) { if (target > nums[middle] && target <= nums[end]) { bool flag = recursiveSearch(nums, target, middle + 1, end); if (flag == false) return recursiveSearch(nums, target, start, middle - 1); else return true; } else { bool flag = recursiveSearch(nums, target, start, middle - 1); if (flag == false) return recursiveSearch(nums, target, middle + 1, end); else return true; } } else { if (target < nums[middle] && target >= nums[start]) { bool flag = recursiveSearch(nums, target, start, middle - 1); if (flag == false) return recursiveSearch(nums, target, middle + 1, end); else return true; } else { bool flag = recursiveSearch(nums, target, middle + 1, end); if (flag == false) return recursiveSearch(nums, target, start , middle - 1); else return true; } } } }; class Solution { public: bool search(vector<int> &nums, int target) { int num = nums.size(); if(0 == num) return false; for(int i = 0; i < num; ++i) if(nums[i] == target) return true; return false; } }; <file_sep>/Triangle.cpp // C/C++ File // AUTHOR: laosi // FILE: Triangle.cpp // ROLE: TODO (some explanation) // CREATED: 2014-12-12 23:32:45 // MODIFIED: 2014-12-13 00:16:12 #include <iostream> using namespace std; //note: using DP, only O(n) extra space used class Solution { public: int minimumTotal(vector<vector<int> > &Triangle) { int height = Triangle.size(); if (height == 0) return 0; if (height == 1) return Triangle[0][0]; int N = Triangle[height - 1].size(); int *minimum = new int [N]; for (int i = 0;i < Triangle[height - 1].size(); i ++) minimum[i] = Triangle[height - 1][i]; for (int i = height - 1; i > 0; i --) { for (int j = 0; j < Triangle[i].size() - 1; j ++) { int temp1 = minimum[j] + Triangle[i - 1][j]; int temp2 = minimum[j + 1] + Triangle[i - 1][j]; minimum[j] = temp1 < temp2 ? temp1 : temp2; } } int temp = minimum[0]; delete []minimum; return temp; } }; <file_sep>/Pow_X_N.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Pow_X_N.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-05 18:07:36 // MODIFIED: 2015-05-05 18:26:58 #include <iostream> using namespace std; class Solution { public: double myPow(double x, int n) { if (n==0) return 1; double t = myPow(x,n/2); if (n%2) { return n<0 ? 1/x*t*t : x*t*t; } else { return t*t; } } }; <file_sep>/Longest_Valid_Parentheses.cpp /********************************************************************************* * File Name : Longest_Valid_Parentheses.cpp * Created By : laosiaudi * Creation Date : [2015-10-23 22:43] * Last Modified : [2015-10-24 00:24] * Description : **********************************************************************************/ class Solution { public: int longestValidParentheses(string s) { int size = s.size(); if (size == 0) return 0; stack<int>ss; int start = 0; int maxLen = 0; for (int i = 0;i < size; i ++) { if (s[i] == '(') { ss.push(i); } else { if (!ss.empty()) { ss.pop(); if (ss.empty()) maxLen = maxLen > (i - start + 1) ? maxLen : (i - start + 1); else maxLen = maxLen > (i - ss.top()) ? maxLen : (i - ss.top()); } else { start = i; } } } return maxLen; } }; <file_sep>/Remove_Invalid_Parentheses.cpp /* * python solution from collections import deque class Solution(object): def removeInvalidParentheses(self, s): """ :type s: str :rtype: List[str] """ table = set() result = [] if len(s) == 0: return result d = deque() d.append(s) minStep = -1 cnt = 1 while len(d) != 0: if (minStep != -1 ) and (cnt > minStep): return result size = len(d) for i in range(0, size): tmp = d.popleft() if self.check(tmp) is True: if tmp not in table: table.add(tmp) result.append(tmp) minStep = cnt else: for j in range(0, len(tmp)): if tmp[j] is '(' or ')': d.append(tmp[:j] + tmp[j + 1:]) cnt = cnt + 1 return result def check(self, sstr): ss = [] for char in sstr: if char is '(': ss.append(char) elif char is ')': if len(ss) == 0: return False ss.pop() return len(ss) == 0 if __name__ == "__main__": s = Solution() print s.removeInvalidParentheses("()())()") */ class Solution { public: vector<string> removeInvalidParentheses(string s) { vector<string>v; if (s.size() == 0) { v.push_back(s); return v; } map<string,bool>m; queue<string>q; q.push(s); int minStep = -1; int cnt = 1; while (!q.empty()) { if (minStep != -1 && cnt > minStep) return v; int size = q.size(); for (int i = 0; i < size; i ++) { string tmp = q.front(); q.pop(); int left = 0; int right = 0; if (check(tmp, left, right)) { v.push_back(tmp); minStep = cnt; } else { bool flag = left > right; for (int j = 0; j < tmp.size(); j ++) { if (flag) { if (tmp[j] == '(') { string newStr = tmp.substr(0, j) + tmp.substr(j + 1); if (m.find(newStr) == m.end()) { m[newStr] = true; q.push(tmp.substr(0, j) + tmp.substr(j + 1)); } } } else { if (tmp[j] == ')') { string newStr = tmp.substr(0, j) + tmp.substr(j + 1); if (m.find(newStr) == m.end()) { m[newStr] = true; q.push(tmp.substr(0, j) + tmp.substr(j + 1)); } } } } } } cnt ++; } return v; } bool check(string s, int &left, int &right) { stack<char>stk; for (int i = 0; i < s.size(); i ++) { if (s[i] == '(') { stk.push(s[i]); left ++; } else if (s[i] == ')') { if (stk.empty()) return false; stk.pop(); right ++; } } return stk.empty(); } }; <file_sep>/Binary_Tree_Right_Side_View.cpp /********************************************************************************* * File Name : Binary_Tree_Right_Side_View.cpp * Created By : laosiaudi * Creation Date : [2015-09-08 19:30] * Last Modified : [2015-09-08 20:10] * Description : **********************************************************************************/ /** * Definition for a binary tree node. * * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; * */ class Solution { public: vector<int> rightSideView(TreeNode* root) { vector<int>v; if (root == NULL) return v; int tmp = 1; v.push_back(root->val); getRightSide(v, tmp + 1, root->right); getRightSide(v, tmp + 1, root->left); return v; } void getRightSide(vector<int> &v, int tmp, TreeNode* root) { if (root == NULL) { return; } int len = v.size(); if (tmp > len) { v.push_back(root->val); } getRightSide(v, tmp + 1, root->right); getRightSide(v, tmp + 1, root->left); return; } vector<int> betterRightSideView(TreeNode* root) { vector<int>v; if (root == NULL) return v; queue<TreeNode*>q; q.push(root); while (!q.empty()) { int size = q.size(); for (int i = 0; i < size; i ++) { TreeNode* tmp = q.front(); q.pop(); if (i == 0) v.push_back(tmp->val); if (tmp->right) q.push(tmp->right); if (tmp->left) q.push(tmp->left); } } return v; } }; <file_sep>/Two_Sum.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Two_Sum.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-11 20:21:15 // MODIFIED: 2015-04-11 20:57:14 #include <iostream> #include <algorithm> #include <map> #include <vector> using namespace std; class Solution { public: struct ele { int val; int index; bool operator < (const ele& right) const { return val < right.val; } }; vector<int> twoSum(vector<int> &numbers, int target) { vector<ele>number; for (int i = 0; i < numbers.size(); i ++) { ele temp; temp.val = numbers[i]; temp.index = i; number.push_back(temp); } sort(number.begin(), number.end(), less<ele>()); vector<int>result; bool flag = false; for (int i = 0; i < number.size() - 1 && flag == false; i ++) { for (int j = i + 1; j < number.size(); j ++) { if (target == number[i].val + number[j].val) { int index1; int index2; index1 = number[i].index < number[j].index ? number[i].index : number[j].index; index2 = number[i].index > number[j].index ? number[i].index : number[j].index; result.push_back(index1 + 1); result.push_back(index2 + 1); flag = true; break; } } } return result; } }; class BetterSolution { public: struct node { int val; int index; bool operator < (const struct node & item) { return val < item.val; } }; vector<int> twoSum(vector<int>& nums, int target) { int size = nums.size(); vector<int>v; vector<struct node>new_nums; if (size < 2) return v; for (int i = 0; i < nums.size(); i ++) { struct node item; item.val = nums[i]; item.index = i + 1; new_nums.push_back(item); } sort(new_nums.begin(), new_nums.end()); int begin = 0; int end = size - 1; while (begin < end) { int sum = new_nums[begin].val + new_nums[end].val; if (sum == target) { if (new_nums[begin].index > new_nums[end].index) { v.push_back(new_nums[end].index); v.push_back(new_nums[begin].index); } else { v.push_back(new_nums[begin].index); v.push_back(new_nums[end].index); } return v; } else if (sum > target) { end --; } else { begin ++; } } return v; } }; int main() { vector<int>v; v.push_back(-1); v.push_back(-2); v.push_back(-3); v.push_back(-4); v.push_back(-5); vector<int>result; Solution s; result = s.twoSum(v, -8); cout << result[0] << " " << result[1] << endl; return 0; } <file_sep>/Evaluate_Reverse_Polish_Notation.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Evaluate_Reverse_Polish_Notation.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-06-01 17:04:36 // MODIFIED: 2015-06-01 17:14:44 #include <iostream> using namespace std; class Solution { public: int evalRPN(vector<string> &tokens) { stack<int>s; for (int i = 0; i < tokens.size(); i ++) { string temp = tokens[i]; if (temp == "+") { int operand_1 = s.top(); s.pop(); int operand_2 = s.top(); s.pop(); s.push(operand_1 + operand_2); } else if (temp == "-") { int operand_1 = s.top(); s.pop(); int operand_2 = s.top(); s.pop(); s.push(operand_2 - operand_1); } else if (temp == "*") { int operand_1 = s.top(); s.pop(); int operand_2 = s.top(); s.pop(); s.push(operand_1 * operand_2); } else if (temp == "/") { int operand_1 = s.top(); s.pop(); int operand_2 = s.top(); s.pop(); s.push(operand_2 / operand_1); } else { s.push(stringToNum(temp)); } } return s.top(); } int stringToNum(string s) { int res = 0; int sign = 1; for (int i = 0; i < s.size(); i ++) { if (s[i] == '-') sign = -sign; else res = res * 10 + s[i] - '0'; } return sign*res; } }; <file_sep>/Remove_Element.cpp // C/C++ File // AUTHOR: laosi // FILE: Remove_Element.cpp // ROLE: TODO (some explanation) // CREATED: 2014-12-12 00:17:18 // MODIFIED: 2014-12-12 00:24:18 #include <iostream> using namespace std; class Solution { public: int removeElement(int A[], int n, int elem) { int num = 0; int *a = new int [n]; int index = 0; for (int i = 0;i < n;i ++) { if (A[i] == elem) num ++; else { a[index ++] = A[i]; } } for (int i = 0;i < n - num; i ++) A[i] = a[i]; delete []a; return n - num; } }; <file_sep>/Insert_Interval.cpp /********************************************************************************* * File Name : Insert_Interval.cpp * Created By : laosiaudi * Creation Date : [2015-10-18 00:02] * Last Modified : [2015-10-18 00:52] * Description : **********************************************************************************/ #include <vector> #include <iostream> using namespace std; struct Interval { int start; int end; Interval() : start(0), end(0) {} Interval(int s, int e) : start(s), end(e) {} }; //TLE erase cost too much time class Solution { public: vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { vector<Interval>::iterator it = intervals.begin(); while (it != intervals.end()) { if (it->end < newInterval.start) { it ++; continue; } else if (it->start > newInterval.end) { intervals.insert(it, newInterval); return intervals; } else { newInterval.start = newInterval.start < it->start ? newInterval.start : it->start; newInterval.end = newInterval.end > it->end ? newInterval.end : it->end; it = intervals.erase(it); } } intervals.push_back(newInterval); return intervals; } }; class Solution { public: vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { vector<Interval> res; int index = 0; while(index < intervals.size() && intervals[index].end < newInterval.start){ res.push_back(intervals[index++]); } while(index < intervals.size() && intervals[index].start <= newInterval.end){ newInterval.start = min(newInterval.start, intervals[index].start); newInterval.end = max(newInterval.end, intervals[index].end); index++; } res.push_back(newInterval); while(index < intervals.size()){ res.push_back(intervals[index++]); } return res; } }; int main() { Interval i1(1,2); Interval i2(3,4); Interval i3(5,6); Interval i4(7,8); Interval i5(9,10); vector<Interval>v; v.push_back(i1); v.push_back(i2); v.push_back(i3); v.push_back(i4); v.push_back(i5); Interval ii(0,11); Solution s; v = s.insert(v, ii); for (auto item : v) { cout << item.start << " " << item.end << endl; } return 0; } <file_sep>/Longest_Substring_Without_Repeating_Characters.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Longest_Substring_Without_Repeating_Characters.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-26 11:18:23 // MODIFIED: 2015-04-26 11:55:18 #include <iostream> #include <string> #include <map> using namespace std; class Solution { public: int lengthOfLongestSubstring(string s) { map<char,int>m; int maxLen = 0; if (s.size() == 0) return 0; m[s[0]] = 0; int index = 1; int last = 0; for (int i = 1; i < s.size(); i ++) { if (m.find(s[i]) == m.end()) { index ++; m[s[i]] = i; } else { if (m[s[i]] >= last) { if (index > maxLen) maxLen = index; index = i - m[s[i]]; last = m[s[i]]; m[s[i]] = i; } else { index ++; m[s[i]] = i; } } } return maxLen > index ? maxLen : index; } }; int main() { Solution s; cout << s.lengthOfLongestSubstring("abba") << endl; cout << s.lengthOfLongestSubstring("bbbbb") << endl; cout << s.lengthOfLongestSubstring("abcabcbb") << endl; cout << s.lengthOfLongestSubstring("abcdefbcdefghi") << endl; return 0; } <file_sep>/H-Index.cpp /********************************************************************************* * File Name : H-Index.cpp * Created By : laosiaudi * Creation Date : [2015-09-11 18:58] * Last Modified : [2015-09-11 19:44] * Description : **********************************************************************************/ class Solution { public: int hIndex(vector<int>& citations) { int cnt = 0; sort(citations.begin(), citations.end(), std::greater<int>()); for (int i = 0; i < citations.size(); i ++) { if (i < citations[i]) cnt ++; } return cnt; } }; <file_sep>/Valid_Number.cpp /********************************************************************************* * File Name : Valid_Number.cpp * Created By : laosiaudi * Creation Date : [2015-11-01 22:35] * Last Modified : [2015-11-01 22:36] * Description : **********************************************************************************/ //reference:http://www.cnblogs.com/chasuner/p/validNumber.html class Solution { public: bool isNumber(string s) { enum InputType { INVALID, // 0 SPACE, // 1 SIGN, // 2 DIGIT, // 3 DOT, // 4 EXPONENT, // 5 NUM_INPUTS // 6 }; int transitionTable[][NUM_INPUTS] = { -1, 0, 3, 1, 2, -1, // next states for state 0 -1, 8, -1, 1, 4, 5, // next states for state 1 -1, -1, -1, 4, -1, -1, // next states for state 2 -1, -1, -1, 1, 2, -1, // next states for state 3 -1, 8, -1, 4, -1, 5, // next states for state 4 -1, -1, 6, 7, -1, -1, // next states for state 5 -1, -1, -1, 7, -1, -1, // next states for state 6 -1, 8, -1, 7, -1, -1, // next states for state 7 -1, 8, -1, -1, -1, -1, // next states for state 8 }; int state = 0; int i = 0; while (i < s.size() && s[i] != '\0') { InputType inputType = INVALID; if (isspace(s[i])) inputType = SPACE; else if (s[i] == '+' || s[i] == '-') inputType = SIGN; else if (isdigit(s[i])) inputType = DIGIT; else if (s[i] == '.') inputType = DOT; else if (s[i] == 'e' || s[i] == 'E') inputType = EXPONENT; state = transitionTable[state][inputType]; if (state == -1) return false; else ++i; } return state == 1 || state == 4 || state == 7 || state == 8; } };<file_sep>/Word_Ladder.cpp /********************************************************************************* * File Name : Word_Ladder.cpp * Created By : laosiaudi * Creation Date : [2015-10-22 17:04] * Last Modified : [2015-10-22 19:59] * Description : **********************************************************************************/ #include <unordered_map> #include <unordered_set> #include <queue> #include <string> #include <iostream> using namespace std; class Solution { public: unordered_map<string, vector<string>>dict; unordered_set<string>visit; int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) { for (int i = 0; i < beginWord.size(); i ++) { for (int j = 0; j < 26; j ++) { if (beginWord[i] == 'a' + j) continue; string tmp = beginWord; tmp[i] = 'a' + j; if (wordList.find(tmp) != wordList.end()) dict[beginWord].push_back(tmp); } } for (int i = 0; i < endWord.size(); i ++) { for (int j = 0; j < 26; j ++) { if (endWord[i] == 'a' + j) continue; string tmp = endWord; tmp[i] = 'a' + j; if (wordList.find(tmp) != wordList.end()) dict[tmp].push_back(endWord); } } for (auto item : wordList) { for (int i = 0; i < item.size(); i ++) { for (int j = 0; j < 26; j ++) { if (item[i] == 'a' + j) continue; string tmp = item; tmp[i] = 'a' + j; if (wordList.find(tmp) != wordList.end()) dict[item].push_back(tmp); } } } queue<string>q; q.push(beginWord); q.push("#"); int cnt = 1; while (!q.empty()) { string tmp = q.front(); visit.insert(tmp); q.pop(); if (tmp == "#") { if (!q.empty()) q.push("#"); cnt ++; continue; } for (auto item : dict[tmp]) { if (item == endWord) return cnt + 1; if (visit.find(item) == visit.end()) q.push(item); } } return 0; } }; int main() { Solution ss; unordered_set<string>s; s.insert("hot"); s.insert("dot"); s.insert("dog"); s.insert("lot"); s.insert("log"); cout << ss.ladderLength("hit", "cog", s); } <file_sep>/Majority_Element.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Majority_Element.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-01-08 19:50:03 // MODIFIED: 2015-01-08 20:06:42 #include <iostream> using namespace std; class Solution { public: int majorityElement(vector<int> &num) { int length = num.size(); int limit = length/2; map<int,int>record; for (int i = 0; i < length; i ++) { if (record.find(num[i]) == record.end()) { record[num[i]] = 0; } else { record[num[i]] ++; } if (record[num[i]] == limit) return num[i]; } } }; <file_sep>/Course_Schedule_II.cpp /********************************************************************************* * File Name : Course_Schedule.cpp * Created By : laosiaudi * Creation Date : [2015-10-22 22:05] * Last Modified : [2015-10-22 23:16] * Description : **********************************************************************************/ #include <vector> #include <queue> #include <unordered_map> #include <algorithm> #include <iostream> using namespace std; class Solution { public: vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { vector<int>result; if (numCourses == 0) return result; unordered_map<int, int>pre_num; unordered_map<int, vector<int>>course; for (int i = 0; i < numCourses; i ++) pre_num[i] = 0; for (auto item : prerequisites) { pre_num[item.first] ++; course[item.second].push_back(item.first); } queue<int>q; int cnt = 0; for (int i = 0; i < numCourses; i ++) { if (pre_num[i] == 0) { q.push(i); cnt ++; } } while (!q.empty()) { int num = q.front(); result.push_back(num); q.pop(); for (auto item : course[num]) { pre_num[item] --; if (pre_num[item] == 0) { q.push(item); cnt ++; } } } if (cnt != numCourses) result.clear(); return result; } }; int main() { Solution s; vector<pair<int, int>>v; v.push_back(std::make_pair(0,1)); s.canFinish(2, v); } <file_sep>/Balanced_Binary_Tree.cpp /********************************************************************************* * File Name : Balanced_Binary_Tree.cpp * Created By : laosiaudi * Creation Date : [2015-09-07 11:30] * Last Modified : [2015-09-07 11:48] * Description : **********************************************************************************/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; **/ class Solution { public: bool isBalanced(TreeNode* root) { if (root == NULL) return true; int lh = getHeight(root->left); if (lh == -1) return false; int rh = getHeight(root->right); if (rh == -1) return false; return abs(lh - rh) <= 1; } int getHeight(TreeNode* node) { if (node == NULL) return 0; int lh = getHeight(node->left); int rh = getHeight(node->right); if (lh == -1 || rh == -1) return -1; if (abs(lh - rh) > 1) return -1; return (lh > rh ? lh : rh) + 1; } }; <file_sep>/Compare_Version_Numbers.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Compare_Version_Numbers.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-15 01:05:04 // MODIFIED: 2015-05-15 10:20:25 #include <iostream> using namespace std; class Solution { public: int compareVersion(string version1, string version2) { int len1 = version1.size(); int len2 = version2.size(); int p1 = 0; int p2 = 0; vector<int>v1; vector<int>v2; for (;p1 < len1; p1 ++) { int temp = 0; while (version1[p1] != '.' && p1 < len1) { temp = temp * 10 + version1[p1] - '0'; p1 ++; } v1.push_back(temp); if (p1 == len1) break; } for (;p2 < len2; p2 ++) { int temp = 0; while (version2[p2] != '.' && p2 < len2) { temp = temp * 10 + version2[p2] - '0'; p2 ++; } v2.push_back(temp); if (p2 == len2) break; } int i, j; len1 = v1.size(); len2 = v2.size(); for (i = 0, j = 0;i < len1 && j < len2; i ++, j ++) { if (v1[i] > v2[j]) return 1; else if (v1[i] < v2[j]) return -1; } if (i == len1 && j == len2) return 0; else if (i == len1 && j != len2) { return v2[j] == 0 ? 0 : -1; } else if (i != len1 && j == len2) { return v1[i] == 0 ? 0 : 1; } } }; <file_sep>/Linked_List_Cycle_II.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Linked_List_Cycle_II.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-29 18:10:03 // MODIFIED: 2015-04-29 18:33:03 #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ // follow up: http://www.cnblogs.com/hiddenfox/p/3408931.html // follow up:http://www.vimer.cn/2010/10/%E4%B8%80%E9%81%93%E4%B8%8D%E9%94%99%E7%9A%84%E7%AE%97%E6%B3%95%E9%A2%98-%E5%88%A4%E6%96%AD%E9%93%BE%E8%A1%A8%E6%98%AF%E5%90%A6%E6%9C%89%E7%8E%AF.html class Solution { public: ListNode* detectCycle(ListNode *head) { if (head == NULL || head->next == NULL) return NULL; ListNode* walker = head; ListNode* runner = head; bool hasCycle = false; while (walker != NULL && runner != NULL && walker->next != NULL && runner->next != NULL) { walker = walker->next; runner = runner->next->next; if (walker == runner) { hasCycle = true; break; } } if (hasCycle == false) return NULL; else { runner = head; while (runner != walker) { runner = runner->next; walker = walker->next; } return runner; } } }; <file_sep>/Word_Break_II.cpp /********************************************************************************* * File Name : Word_Break_II.cpp * Created By : laosiaudi * Creation Date : [2015-10-16 16:53] * Last Modified : [2014-12-31 19:04] * Description : **********************************************************************************/ #include <vector> #include <unordered_set> #include <iostream> #include <string> #include <map> using namespace std; class Solution { public: vector<string> wordBreak(string s, unordered_set<string>& wordDict) { vector<bool>possible(s.size(), false); for (int i = 0; i < s.size(); i ++) { string tmp = s.substr(0, i + 1); if (wordDict.find(tmp) != std::end(wordDict)) { possible[i] = true; continue; } for (int j = 0; j <= i - 1; j ++) { possible[i] = possible[j] && (wordDict.find(s.substr(j + 1, i - j)) != std::end(wordDict)); if (possible[i]) break; } } vector<string>result; if (!possible[s.size() - 1]) return result; for (int i = 0; i< s.size(); i ++) { if (possible[i] && wordDict.find(s.substr(0, i + 1)) != std::end(wordDict)) { string tmp = s.substr(0, i + 1); recursiveFind(i + 1, s, result, tmp, possible, wordDict); } } return result; } void recursiveFind(int start, string s, vector<string> & result, string tmp, vector<bool>possible, unordered_set<string>wordDict) { if (start == s.size()) { result.push_back(tmp); return; } for (int i = start; i < s.size(); i ++) { string new_str = s.substr(start, i - start + 1); if (possible[i] && wordDict.find(new_str) != std::end(wordDict)) { string ss = (tmp + " " + new_str); recursiveFind(i + 1, s, result, ss, possible, wordDict); } } return; } }; int main() { Solution s; unordered_set<string> wordDict; wordDict.insert("aaaa"); wordDict.insert("aaa"); vector<string>res = s.wordBreak("aaaaaaa", wordDict); for (auto s : res) cout << s << endl; return 0; } <file_sep>/First_Missing_Positive.cpp // C/C++ File // AUTHOR: LaoSi // FILE: First_Missing_Positive.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-09-04 00:14:01 // MODIFIED: 2015-09-04 17:07:00 #include <iostream> using namespace std; class Solution { public: //O(nlogn) int firstMissingPositive(vector<int> &nums) { int n = nums.size(); if (n == 0) return 1; sort(nums.begin(), nums.end()); int tmp = 0; for (int i = 0; i < n; i ++) { if (nums[i] > 0) { if (i > 0 && nums[i] == nums[i - 1]) continue; if (nums[i] - tmp == 1) { tmp ++; } else { return tmp + 1; } } } return nums[n - 1] + 1; } //O(n) using hash table, make a[i] = i + 1 int bestFirstMissingPositive(vector<int> &nums) { int n = nums.size(); for (int i = 0 ;i < n; i ++) { while (i != nums[i] - 1) { if (nums[i] <= 0 || nums[i] > n || nums[i] ==nums[nums[i] - 1]) break; int tmp = nums[i]; nums[i] = nums[nums[i] - 1]; nums[tmp - 1] = tmp; } } for (int i = 0; i < n; i ++) { if (nums[i] != i + 1) return i + 1; } return n + 1; } }; <file_sep>/Count_And_Say.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Count_And_Say.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-15 10:22:48 // MODIFIED: 2015-05-15 10:32:57 #include <iostream> using namespace std; class Solution { public: string countAndSay(int n) { string res = "1"; for (int i = 2; i <= n ; i ++) { string temp; int count = 1; res = res + "#"; for (int j = 0; j < res.size() - 1; j ++) { if (res[j] == res[j + 1]) count ++; else { temp.push_back(count + '0'); temp.push_back(res[j]); count = 1; } } res = temp; } return res; } }; <file_sep>/Kth_Smallest_Element_In_A_Bst.cpp /********************************************************************************* * File Name : Kth_Smallest_Element_In_A_Bst.cpp * Created By : laosiaudi * Creation Date : [2015-09-09 15:12] * Last Modified : [2015-09-09 15:14] * Description : **********************************************************************************/ /** Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; */ class Solution { public: int kthSmallest(TreeNode* root, int k) { vector<int>v; inorderTraverse(root, v); return v[k - 1]; } void inorderTraverse(TreeNode* root, vector<int>& v) { if (root == NULL) return; inorderTraverse(root->left, v); v.push_back(root->val); inorderTraverse(root->right, v); return; } }; <file_sep>/Implement_Trie.cpp /********************************************************************************* * File Name : Implement_Trie.cpp * Created By : laosiaudi * Creation Date : [2015-10-25 14:33] * Last Modified : [2015-10-25 15:42] * Description : **********************************************************************************/ class TrieNode { public: // Initialize your data structure here. TrieNode() { val = ' '; word = false; } char val; bool word; unordered_map<char, TrieNode*>children; }; class Trie { public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(string word) { int index = 0; TrieNode* tmp = root; while (index < word.size()) { if (tmp->children.find(word[index]) == std::end(tmp->children)) { TrieNode* newNode = new TrieNode(); newNode->val = word[index]; index ++; tmp->children[newNode->val] = newNode; tmp = newNode; } else { tmp = tmp->children[word[index]]; index ++; } } tmp->word = true; } // Returns if the word is in the trie. bool search(string word) { TrieNode* tmp = root; int index = 0; while (index < word.size()) { if (tmp->children.find(word[index]) == std::end(tmp->children)) return false; else { tmp = tmp->children[word[index]]; index ++; } } return tmp->word; } // Returns if there is any word in the trie // that starts with the given prefix. bool startsWith(string prefix) { TrieNode* tmp = root; int index = 0; while (index < prefix.size()) { if (tmp->children.find(prefix[index]) == std::end(tmp->children)) return false; else { tmp = tmp->children[prefix[index]]; index ++; } } return true; } private: TrieNode* root; }; // Your Trie object will be instantiated and called as such: // Trie trie; // trie.insert("somestring"); // trie.search("key"); <file_sep>/Peeking_Iterator.cpp /********************************************************************************* * File Name : Peeking_Iterator.cpp * Created By : laosiaudi * Creation Date : [2015-10-23 20:02] * Last Modified : [2015-10-23 20:33] * Description : **********************************************************************************/ // Below is the interface for Iterator, which is already defined for you. // **DO NOT** modify the interface for Iterator. class Iterator { struct Data; Data* data; public: Iterator(const vector<int>& nums); Iterator(const Iterator& iter); virtual ~Iterator(); // Returns the next element in the iteration. int next(); // Returns true if the iteration has more elements. bool hasNext() const; }; class PeekingIterator : public Iterator { public: bool hasPeeked; int peekEle; PeekingIterator(const vector<int>& nums) : Iterator(nums) { // Initialize any member here. // **DO NOT** save a copy of nums and manipulate it directly. // You should only use the Iterator interface methods. hasPeeked = false; peekEle = 0; } // Returns the next element in the iteration without advancing the iterator. int peek() { if (hasPeeked == false) { hasPeeked = true; peekEle = Iterator::next(); } return peekEle; } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. int next() { if (!hasPeeked) { return Iterator::next(); } hasPeeked = false; int tmp = peekEle; peekEle = 0; return tmp; } bool hasNext() const { return hasPeeked || Iterator::hasNext(); } }; <file_sep>/Bulls_And_Cows.cpp /********************************************************************************* * File Name : Bulls_And_Cows.cpp * Created By : laosiaudi * Creation Date : [2015-11-11 20:05] * Last Modified : [2015-11-11 20:51] * Description : **********************************************************************************/ class Solution { public: string getHint(string secret, string guess) { int A = 0; int B = 0; int m[256]={0}; for (int i = 0; i < secret.size(); i ++) { if (secret[i] == guess[i]) A ++; else { m[secret[i]] ++; } } for (int i = 0; i < secret.size(); i ++) { if (secret[i] != guess[i] && m[guess[i]]) { m[guess[i]] --; B ++; } } string result = to_string(A) + "A" + to_string(B) + "B"; return result; } }; <file_sep>/Word_Break.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Word_Break.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-19 16:48:49 // MODIFIED: 2015-05-20 17:11:00 #include <iostream> using namespace std; //DP class Solution { public: bool wordBreak(string s, unordered_set<string> & wordDict) { int len = s.size(); if (len == 0) return false; vector<bool>possible(len, false); for (int i = 0; i < len; i ++) { string sub = s.substr(0, i + 1); if (wordDict.find(sub) != wordDict.end()) { possible[i] = true; continue; } for (int j = 0; j <= i - 1; j ++) { possible[i] = possible[j] && wordDict.find(s.substr(j + 1, i - j)) != wordDict.end(); if (possible[i]) break; } } return possible[len - 1]; } }; <file_sep>/House_Robber.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Hose_Robber.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-20 17:22:45 // MODIFIED: 2015-05-20 17:26:09 #include <iostream> using namespace std; class Solution { public: int rob(vector<int> &num) { int size = num.size(); vector<int>res(size + 2, 0); for (int i = 2; i < size + 2; i ++) { int temp = res[i - 2] + num[i - 2]; res[i] = res[i - 1] > temp ? res[i - 1] : temp; } return res[size + 1]; } }; <file_sep>/Maximal_Square.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Maximal_Square.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-09-02 13:55:45 // MODIFIED: 2015-09-03 17:03:09 #include <iostream> using namespace std; class Solution { public: int maximalSquare(vector<vector<char> >& matrix) { int line = matrix.size(); if (line == 0) return 0; int col = matrix[0].size(); vector<int>v(col, 0); vector<vector<int> >tmp(line, v); int len = 0; for (int i = 0;i < line; i ++) { for (int j = 0; j < col; j ++) { tmp[i][j] = matrix[i][j] - '0'; if (i == 0) { if (tmp[i][j] && len == 0) len = 1; } else if (j == 0) { if (tmp[i][j] && len == 0) len = 1; } else { if (!tmp[i][j]) { tmp[i][j] = 0; } else { tmp[i][j] = getState(tmp[i - 1][j], tmp[i][j - 1], tmp[i - 1][j - 1]); len = len > tmp[i][j] ? len : tmp[i][j]; } } } } return len * len; } int getState(int a, int b, int c) { if (a == 0 || b == 0 || c == 0) { return 1; } else if (a == b && c >= a) { return a + 1; } else if (a == b && c < a) { return a; } else { if (a - b == 1 || b - a == 1) return a > b ? a : b; else return (a < b ? a: b) + 1; } } //best getState function , actually getState can be simplied as below //but function below has another perfect idea //the state is formed by the min of (a,b,c) + 1 int bestGetState(int a, int b, int c) { int tmp = a < b ? a : b; return (tmp < c ? tmp : c) + 1; } }; <file_sep>/Range_Sum_Query_Immutable.cpp /********************************************************************************* * File Name : Range_Sum_Query_Immutable.cpp * Created By : laosiaudi * Creation Date : [2015-11-11 11:00] * Last Modified : [2015-11-11 11:04] * Description : **********************************************************************************/ class NumArray { public: int *sum; NumArray(vector<int> &nums) { if (nums.size() == 0) sum = NULL; else { sum = new int[nums.size()]; sum[0] = nums[0]; for (int i = 1;i < nums.size(); i ++) sum[i] = sum[i - 1] + nums[i]; } } int sumRange(int i, int j) { return i == 0 ? sum[j] : sum[j] - sum[i - 1]; } }; // Your NumArray object will be instantiated and called as such: // NumArray numArray(nums); // numArray.sumRange(0, 1); // numArray.sumRange(1, 2); <file_sep>/Unique_Paths.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Unique_Paths.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-11 19:01:27 // MODIFIED: 2015-04-11 19:54:44 // If use method like DFS, will TLE. Should store state first #include <iostream> #include <stack> using namespace std; class Solution { public: struct grid { int x; int y; }; int uniquePaths(int m, int n) { if (m == 1 && n == 1) return 1; for (int i = 0;i < m;i ++) { for (int j = 0; j < n;j ++) { visit[i][j] = false; way[i][j] = 0; } } return recursivePath(1, 0, m, n) + recursivePath(0, 1, m, n); } int recursivePath(int x, int y, int line, int col) { if (x < 0 || x >= line || y < 0 || y >= col) return 0; if (x == line - 1 && y == col - 1) return 1; if (visit[x][y] == true) return way[x][y]; else { visit[x][y] = true; way[x][y] = recursivePath(x, y + 1, line, col) + recursivePath(x + 1, y , line , col); return way[x][y]; } } bool visit[100][100]; int way[100][100]; }; int main() { Solution s; cout << s.uniquePaths(23,12) << endl; cout << s.uniquePaths(3,3) << endl; cout << s.uniquePaths(2,2) << endl; return 0; } <file_sep>/Min_Stack.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Min_Stack.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-31 21:34:24 // MODIFIED: 2015-05-31 22:25:44 #include <iostream> using namespace std; class MinStack { public: void push(int x) { if (v.size() == 0) minEle = x; else minEle = minEle < x? minEle : x; v.push_back(x); } void pop() { int temp = v[v.size() - 1]; v.pop_back(); if (temp != minEle) return ; int minTemp = v[0]; for (int i = 1; i < v.size();i ++) { if (v[i] < minTemp) minTemp = v[i]; } minEle = minTemp; } int top() { return v[v.size() - 1]; } int getMin() { return minEle; } private: vector<int>v; int minEle; }; class AnotherSolution { public: void push(int x) { if (minStack.size() == 0 || x <= minStack.top()) minStack.push(x); v.push_back(x); } void pop() { if (minStack.top() == v[v.size() - 1]) minStack.pop(); v.pop_back(); } int top() { return v[v.size() - 1]; } int getMin() { return minStack.top(); } private: vector<int>v; stack<int>minStack; }; <file_sep>/Find_Peak_Element.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Find_Peak_Element.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-01-05 16:15:40 // MODIFIED: 2015-01-08 20:25:55 #include <iostream> #include <vector> using namespace std; class Solution { public: int findPeakElement(const vector<int> &num) { int length = num.size(); if (length == 1) return 0; return findByRecursive(num, 0, length - 1); } int findByRecursive(const vector<int>&A, int start, int end) { if (start == end) { if (start == 0) { return (A[0] > A[1]?0:-1); } else if (start == A.size() - 1) { return (A[start] > A[start - 1]?start:-1); } else { return (A[start] > A[start - 1] && A[start] > A[start + 1])?start:-1; } } else { int pivot = (start + end)/2; int resultLeft = findByRecursive(A, start, pivot); if (resultLeft != -1) return resultLeft; int resultRight = findByRecursive(A, pivot + 1, end); if (resultRight != -1) return resultRight; } } }; <file_sep>/Same_Tree.cpp /********************************************************************************* * File Name : Same_Tree.cpp * Created By : laosiaudi * Creation Date : [2015-09-05 21:57] * Last Modified : [2015-09-05 22:10] * Description : **********************************************************************************/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; * */ #include <iostream> using namespace std; class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { return recursiveJudge(p, q); } bool recursiveJudge(TreeNode* p, TreeNode* q) { if ((p == NULL && q != NULL) || (p != NULL && q == NULL)) return false; if (p == NULL && q == NULL) return true; if (p->val != q->val) return false; bool left = recursiveJudge(p->left, q->left); if (left == false) return false; return recursiveJudge(p->right, q->right); } }; <file_sep>/Isomorphic_Strings.cpp /********************************************************************************* * File Name : Isomorphic_Strings.cpp * Created By : laosiaudi * Creation Date : [2015-09-11 14:32] * Last Modified : [2015-11-01 23:01] * Description : **********************************************************************************/ class Solution { public: bool isIsomorphic(string s, string t) { map<char, char>m; map<char, char>r; for (int i = 0; i < s.size(); i ++) { char sc = s[i]; char tc = t[i]; if (m.find(sc) == m.end() && r.find(tc) == r.end()) { m[sc] = tc; r[tc] = sc; } else { if (r[tc] != sc) return false; if (m[sc] != tc) return false; } } return true; } }; <file_sep>/Reverse_Linked_List_II.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Reverse_Linked_List_II.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-27 00:11:05 // MODIFIED: 2015-04-27 00:51:29 #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL){} }; class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { if (head == NULL || m == n) return head; ListNode* helper = new ListNode(0); helper->next = head; ListNode* walker = helper; ListNode* last = helper; for (int i = 1; i <= m; i ++) { walker = walker->next; if (i == m - 1) last = walker; } ListNode* end; ListNode* before = walker; ListNode* newEnd = walker; for (int i = m; i <= n; i ++) { ListNode* temp = walker->next; if (i > m) { walker->next = before; before = walker; } if (i == n) end = walker; walker = temp; } last->next = end; newEnd->next =walker; head = helper->next; delete helper; return head; } }; int main() { ListNode* first = new ListNode(3); ListNode* second = new ListNode(5); first->next = second; Solution s; ListNode* head = s.reverseBetween(first, 1, 2); while (head) { cout << head->val << endl; head = head->next; } return 0; } <file_sep>/Binary_Tree_Level_Order_Traversal_II.cpp /********************************************************************************* * File Name : Binary_Tree_Level_Order_Traversal.cpp * Created By : laosiaudi * Creation Date : [2015-09-06 19:56] * Last Modified : [2015-09-06 20:20] * Description : **********************************************************************************/ #include <vector> #include <queue> #include <stack> #include <iostream> using namespace std; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; * */ class Solution { public: vector<vector<int>> levelOrderBottom(TreeNode* root) { queue<TreeNode*>q; stack<int>s; stack<int>count; vector<vector<int>>v; if (root == NULL) return v; q.push(root); while (!q.empty()) { int size = q.size(); vector<int>tmp; int cnt = 0; for (int i = 0;i < size; i ++) { TreeNode* tmpNode = q.front(); if (tmpNode != NULL) { tmp.push_back(tmpNode->val); q.push(tmpNode->left); q.push(tmpNode->right); s.push(tmpNode->val); cnt ++; } q.pop(); } if (cnt > 0) count.push(cnt); } while (!count.empty()) { int cnt = count.top(); count.pop(); vector<int>tmp(cnt, 0); for (int i = cnt - 1; i >= 0; i --) { tmp[i] = s.top(); s.pop(); } v.push_back(tmp); } return v; } }; <file_sep>/Letter_Combinations_Of_A_Phone_Number.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Letter_Combinations_Of_A_Phone_Number.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-15 13:50:29 // MODIFIED: 2015-05-15 14:14:01 #include <iostream> using namespace std; class Solution { public: vector<string> letterCombinations(string digits) { int len = digits.size(); vector<string>v; if (len == 0) return v; string temp; recursiveCombinations(v, digits, 0, len, temp); return v; } void recursiveCombinations(vector<string> &v, string digits, int start, int len, string &temp) { if (start == len) { v.push_back(temp); return; } int num = digits[start] - '0'; int step; if (num == 1 || num == 0) step = 0; else if (num == 9 || num == 7) step = 3; else step = 2; if (num == 1) recursiveCombinations(v, digits, start + 1, len, temp); else { char startChar = 'a' + (num - 2)*3; if (num == 9) startChar ++; if (num == 8) startChar ++; for (int i = 0; i <= step; i ++) { temp.push_back(startChar + i); recursiveCombinations(v, digits, start + 1, len, temp); temp.pop_back(); } } } }; <file_sep>/Excel_Sheet_Column_Title.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Excel_Sheet_Column_Title.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-06 15:03:35 // MODIFIED: 2015-05-06 15:34:12 #include <iostream> using namespace std; //进制转换 class Solution { public: string convertToTitle(int n) { stack<char>s; while (n > 0) { int digit = (n - 1) % 26; n = (n - 1) / 26; s.push(digit + 'A'); } string res; while (!s.empty()) { res.push_back(s.top()); s.pop(); } return res; } }; <file_sep>/Length_Of_Last_Word.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Length_Of_Last_Word.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-15 13:43:58 // MODIFIED: 2015-05-15 13:47:24 #include <iostream> using namespace std; class Solution { public: int lengthOfLastWord(string s) { int len = s.size(); int i = 0; int res = 0; while (i < len) { while (s[i] == ' ' && i < len) i ++; if (i == len) break; int start = i; while (s[i] != ' ' && i < len) i ++; int end = i - 1; res = end - start + 1; } return res; } }; <file_sep>/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-21 20:13:17 // MODIFIED: 2015-04-21 21:40:46 #include <iostream> using namespace std; /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { int number = preorder.size(); if (number == 0) return NULL; int root = preorder[0]; TreeNode* rootNode = new TreeNode(root); int rootIndex; for (int i = 0; i < number; i ++) { if (root == inorder[i]) { rootIndex = i; break; } } TreeNode* leftRootNode; TreeNode* rightRootNode; if (rootIndex - 1 >= 0) { int leftRoot = preorder[1]; leftRootNode = buildSubTree(preorder, inorder, 0, rootIndex - 1, 1, leftRoot); } else { leftRootNode = NULL; } if (rootIndex + 1<= number - 1) { int rightRoot = preorder[rootIndex + 1]; rightRootNode = buildSubTree(preorder, inorder, rootIndex + 1, number - 1, rootIndex + 1, rightRoot); } else { rightRootNode = NULL; } rootNode->left = leftRootNode; rootNode->right = rightRootNode; return rootNode; } TreeNode *buildSubTree(vector<int> &preorder, vector<int> &inorder, int start, int end, int index, int root) { if (start == end) { TreeNode* child = new TreeNode(inorder[start]); return child; } TreeNode* rootNode = new TreeNode(root); int rootIndex; for (int i = start; i <= end; i ++) { if (root == inorder[i]) { rootIndex = i; break; } } TreeNode* leftRootNode; TreeNode* rightRootNode; if (rootIndex - 1 >= start) { int leftRoot = preorder[index + 1]; leftRootNode = buildSubTree(preorder, inorder, start, rootIndex - 1, index + 1, leftRoot); } else { leftRootNode = NULL; } if (rootIndex + 1 <= end) { int rightRoot = preorder[index + rootIndex - start + 1]; rightRootNode = buildSubTree(preorder, inorder, rootIndex + 1, end, index + rootIndex - start + 1, rightRoot); } else { rightRootNode = NULL; } rootNode->left = leftRootNode; rootNode->right = rightRootNode; return rootNode; } }; <file_sep>/Simplify_Path.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Simplify_Path.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-14 00:28:20 // MODIFIED: 2015-05-14 23:10:34 #include <iostream> using namespace std; class Solution { public: string simplifyPath(string path) { int size = path.size(); stack<string>ss; string temp; for (int i = 0; i < size;) { while (path[i] == '/' && i < size) i ++; if (i == size) break; int start = i; while (path[i] != '/' && i < size) i ++; int end = i -1; string element = path.substr(start, end-start+1); if (element == "..") { if (!ss.empty()) ss.pop(); } else if (element != ".") ss.push(element); } string res = "/"; while (!ss.empty()) { if (res == "/") res = res + ss.top(); else res = "/" + ss.top() + res; ss.pop(); } return res; } }; <file_sep>/Basic_Calculator.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Basic_Calculator.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-08-21 16:13:16 // MODIFIED: 2015-08-21 16:57:40 #include <iostream> #include <stack> using namespace std; class Solution { public: int calculate(string s) { int len = s.size(); if (len == 0) return 0; stack<char> charStack; stack<int> numStack; int base = 0; for (int i = 0; i < len; i ++) { if (s[i] >= '0' && s[i] <= '9') { base = s[i] - '0'; while (s[i + 1] >= '0' && s[i + 1] <= '9') { base = 10 * base + s[i + 1] - '0'; i ++; } numStack.push(base); base = 0; } else if (s[i] == '+' || s[i] == '-') { if (!charStack.empty() && charStack.top() != '(') { int ele1 = numStack.top(); numStack.pop(); int ele2 = numStack.top(); numStack.pop(); if (charStack.top() == '+') numStack.push(ele1 + ele2); else numStack.push(ele2 - ele1); charStack.pop(); } charStack.push(s[i]); } else if (s[i] == '(') { charStack.push(s[i]); } else if (s[i] == ')') { if (!charStack.empty() && charStack.top() != '(') { int ele1 = numStack.top(); numStack.pop(); int ele2 = numStack.top(); numStack.pop(); if (charStack.top() == '+') numStack.push(ele1 + ele2); else numStack.push(ele2 - ele1); charStack.pop(); } charStack.pop(); } else if (s[i] == ' ') continue; } while (!charStack.empty()) { char op = charStack.top(); int ele1 = numStack.top(); numStack.pop(); int ele2 = numStack.top(); numStack.pop(); if (op == '+') numStack.push(ele1 + ele2); else numStack.push(ele2 - ele1); charStack.pop(); } return numStack.top(); } }; int main() { Solution s; cout << s.calculate("(1)"); return 0; } <file_sep>/Sort_Colors.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Sort_Colors.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2014-12-27 20:02:40 // MODIFIED: 2015-01-05 14:29:51 #include <iostream> using namespace std; //two-pass algorithm class Solution { public: void sortColors(int A[], int n) { int numOfRed = 0; int numOfWhite = 0; int numOfBlue = 0; for (int i = 0;i < n; i ++) { if (A[i] == 0) numOfRed ++; if (A[i] == 1) numOfWhite ++; if (A[i] == 2) numOfBlue ++; } int index = 0; for (int i = 1; i <= numOfRed; i ++) { A[index ++] = 0; } for (int i = 1; i <= numOfWhite; i ++) { A[index ++] = 1; } for (int i = 1; i <= numOfBlue; i ++) { A[index ++] = 2; } } }; //one-pass algorithm class Solution { public: void sortColors(int A[], int n) { if (n == 0) return ; int startOfWhite = 0; int endOfWhite = n - 1; int index = 0; while (index <= endOfWhite) { if (A[index] == 0) { A[index] = A[startOfWhite]; A[startOfWhite] = 0; index ++; startOfWhite ++; } else if (A[index] == 1) { index ++; } else { A[index] = A[endOfWhite]; A[endOfWhite] = 2; endOfWhite --; } } } }; <file_sep>/Fraction_To_Recurring_Decimal.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Fraction_To_Recurring_Decimal.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-25 18:22:35 // MODIFIED: 2015-04-25 21:04:39 #include <iostream> #include <map> #include <vector> #include <math.h> using namespace std; class Solution { public: string fractionToDecimal(int numerator, int denominator) { if (numerator == 0) return "0"; vector<int>v; bool isNega = false; if (numerator < 0 ^ denominator < 0) isNega = true; long long int n = numerator, d = denominator; n = abs(n); d = abs(d); int temp = n/d; v.push_back(temp); long long int left = n % d; map<int, bool>m; bool isLoop = false; int loopDigit = -1;; while (left) { if (m.find(left) == m.end()){ m[left] = true; } else { isLoop = true; loopDigit = left * 10 / d; break; } n = left * 10; left = n % d; temp = n / d; v.push_back(temp); } int size = v.size(); if (size > 1) size ++; if (isLoop) size += 2; if (v[0] >= 10){ vector<int>t; int real = v[0]; while (real != 0) { t.push_back(real % 10); real = real / 10; } size = size - 1 + t.size(); string digits(size, ' '); int index = 0; for (int i = t.size() - 1; i >= 0; i --) digits[index ++] = t[i] - 0 + '0'; if (v.size() == 1) return digits; digits[index ++] = '.'; for (int i = 1; i < v.size() - 1; i ++) { if (v[i] == loopDigit) digits[index ++] = '('; digits[index ++] = v[i] - 0 + '0'; } if (isLoop) digits[index ++] = ')'; if (isNega) digits = "-" + digits; return digits; } else { string digits(size, ' '); digits[0] = v[0] - 0 + '0'; if (v.size() == 1) return digits; int index = 1; digits[index ++] = '.'; for (int i = 1; i <= v.size() - 1; i ++) { if (v[i] == loopDigit) digits[index ++] = '('; digits[index ++] = v[i] - 0 + '0'; } if (isLoop) digits[index ++] = ')'; if (isNega) digits = "-" + digits; return digits; } } }; class BetterSolution { public: string fractionToDecimal(int numerator, int denominator) { if(numerator==0) return "0"; string result; if(numerator<0 ^ denominator<0 ) result+='-'; //异或,numerator<0和denominator<0仅有一个为真 //转化为正数,INT_MIN转化为正数会溢出,故用long long。long long int n=abs(INT_MIN)得到的n仍然是负的,所以写成下面的形式。 long long int n=numerator,d=denominator; n=abs(n);d=abs(d); result+=to_string(n/d); //整数部分 long long int r=n%d; //余数r if(r==0) return result; else result+='.'; //下面处理小数部分,用哈希表 map<int,int> m; while(r){ //检查余数r是否在哈希表中,是的话则开始循环了 if(m.find(r)!=m.end()){ result.insert(m[r],1,'('); //http://www.cplusplus.com/reference/string/basic_string/insert/ result+=')'; break; } m[r]=result.size(); //这个余数对应于result的哪个位置 //正常运算 r*=10; result+=to_string(r/d); r=r%d; } return result; } }; int main () { Solution s; cout << s.fractionToDecimal(-1, -2147483648) << endl; cout << s.fractionToDecimal(2, 1) << endl; cout << s.fractionToDecimal(2, 3) << endl; cout << s.fractionToDecimal(19, 4) << endl; return 0; } <file_sep>/Search_For_A_Range.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Search_For_A_Range.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-01-05 14:53:54 // MODIFIED: 2015-01-05 15:32:56 #include <iostream> using namespace std; class Solution { public: vector<int> searchRange(int A[], int n, int target) { vector<int>v; if (n == 1) { if (A[0] == target) { v.push_back(0); v.push_back(0); return v; } else { v.push_back(-1); v.push_back(-1); return v; } } int start = binarySearch(A, 0, n - 1, target); int end = binarySearch(A, 0, n - 1, target + 1); if (A[start] == target && A[end - 1] == target) { v.push_back(start); v.push_back(end - 1); } else { v.push_back(-1); v.push_back(-1); } return v; } int binarySearch(int A[], int start, int end, int target) { if (start == end) { if (target <= A[start]) return start; else return start + 1; } int pivot = (start + end)/2; int result = -1; if (target <= A[pivot]) result = binarySearch(A, start, pivot, target); else result = binarySearch(A, pivot + 1, end, target); return result; } }; <file_sep>/Sqrt_x.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Sqrt_x.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-05 12:31:43 // MODIFIED: 2015-05-05 15:55:19 #include <iostream> using namespace std; //TLE class Solution { public: int mySqrt(int x) { if (x == 0) return x; if (x < 0) return -1; for (int i = 1;i <= x/2; i ++) { if (i * i > x) return i - 1; } } }; //binary search class Solution { public: int mySqrt(int x) { long long i = 0; //use long long long long j = x/2 + 1; while (i <= j) { long long mid = (i + j)/2; long long sq = mid * mid; if (sq == x) return mid; else if (sq < x) i = mid + 1; else j = mid - 1; } return j; } }; //Newton //reference: http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html class Solution { public: int mySqrt(int x) { if (x == 0) return 0; double last = 0; double res = 1; while (res != last) { last = res; res = (res + x / res) / 2; } return int(res); } }; <file_sep>/Symmetric_Tree.cpp /********************************************************************************* * File Name : Symmetric_Tree.cpp * Created By : laosiaudi * Creation Date : [2015-09-08 13:51] * Last Modified : [2015-09-08 16:50] * Description : **********************************************************************************/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; * */ class Solution { public: bool isSymmetric(TreeNode* root) { if (root == NULL) return true; vector<TreeNode*>v; v.push_back(root); int level = 1; while (level > 0) { int i = 0; while (i < level) { TreeNode* tmp = v[i]; i ++; if (tmp == NULL) continue; v.push_back(tmp->left); v.push_back(tmp->right); } int start = 0, end = level - 1; while (start < end) { TreeNode* lc = v[start]; TreeNode* rc = v[end]; int vlc = lc == NULL ? -1 : lc->val; int vrc = rc == NULL ? -1 : rc->val; if (vlc != vrc) return false; start ++; end --; } v.erase(v.begin(), v.begin() + level); level = v.size(); } return true; } //recursive version bool isSymmetric(TreeNode* root) { if (root == NULL) return true; return isReSymmetric(root->left, root->right); } bool isReSymmetric(TreeNode* left, TreeNode* right) { if (left == NULL) return right == NULL; if (right == NULL) return left == NULL; if (left->val != right->val) return false; if (!isReSymmetric(left->left, right->right)) return false; if (!isReSymmetric(left->right, right->left)) return false; return true; } }; <file_sep>/Numbers_Of_1_Bits.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Numbers_Of_1_Bits.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-06-04 18:16:19 // MODIFIED: 2015-06-04 18:20:58 #include <iostream> using namespace std; class Solution { public: int hammingWeight(uint32_t n) { int num[16] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4}; int i = 8; int res = 0; while (i --) { uint32_t temp = n & 0xf; res += num[temp]; n = n >> 4; } return res; } }; <file_sep>/Valid_Sudoku.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Valid_Sudoku.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-26 13:48:55 // MODIFIED: 2015-04-26 14:11:59 #include <iostream> using namespace std; class Solution { public: bool isValidSudoku(vector<vector<char> > &board) { if (board.size() < 9 || board[0].size() < 9) return false; //check row for (int i = 0; i < 9;i ++) { vector<bool>checked(9, false); for (int j = 0; j < 9; j ++) { if ('1' <= board[i][j] && board[i][j] <= '9') { int num = board[i][j] - '1' + 1; if (checked[num - 1]) return false; else checked[num - 1] = true; } } } //check col for (int i = 0; i < 9;i ++) { vector<bool>checked(9, false); for (int j = 0; j < 9; j ++) { if ('1' <= board[j][i] && board[j][i] <= '9') { int num = board[j][i] - '1' + 1; if (checked[num - 1]) return false; else checked[num - 1] = true; } } } //check sub-grid for (int i = 0; i < 9;i ++) { vector<bool>checked(9, false); for (int j = 0; j < 9; j ++) { if ('1' <= board[i / 3 * 3+ j / 3][i % 3 * 3+ j % 3] && board[i / 3 * 3+ j/3][i % 3 * 3 + j % 3] <= '9') { int num = board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3] - '1' + 1; if (checked[num - 1]) return false; else checked[num - 1] = true; } } } return true; } }; <file_sep>/Word_Ladder_II.cpp /********************************************************************************* * File Name : Word_Ladder.cpp * Created By : laosiaudi * Creation Date : [2015-10-22 17:04] * Last Modified : [2015-10-22 21:59] * Description : **********************************************************************************/ #include <unordered_map> #include <unordered_set> #include <queue> #include <string> #include <iostream> using namespace std; class Solution { public: unordered_map<string, vector<string>>dict; unordered_map<string, bool>visit; struct node { vector<string>v; string val; }; vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string>& wordList) { vector<vector<string>>result; bool find = false; queue<struct node>q; struct node newNode; newNode.val = beginWord; newNode.v.push_back(beginWord); q.push(newNode); struct node ter; ter.val = "#"; q.push(ter); while (!q.empty()) { struct node tmpNode = q.front(); string tmp = tmpNode.val; q.pop(); visit[tmp] = true; if (tmp == "#") { if (!q.empty()) { struct node ter; ter.val = "#"; q.push(ter); } if (find) return result; continue; } if (equalEnd(tmp, endWord)) { find = true; tmpNode.v.push_back(endWord); result.push_back(tmpNode.v); continue; } if (find) continue; for (int i = 0; i < tmp.size(); i ++) { for (int j = 0; j < 26; j ++) { if (tmp[i] == 'a' + j) continue; string item = tmp; item[i] = 'a' + j; if (wordList.find(item) != wordList.end()) { if (visit.find(item) == visit.end()) { tmpNode.val = item; tmpNode.v.push_back(item); q.push(tmpNode); tmpNode.v.erase(std::begin(tmpNode.v) + tmpNode.v.size() - 1); } } } } } return result; } bool equalEnd(string tmp, string end) { if (tmp.size() != end.size()) return false; int cnt = 0; for (int i = 0; i < tmp.size(); i ++) { if (tmp[i] != end[i]) cnt ++; if (cnt > 1) return false; } return cnt == 1; } }; int main() { Solution ss; unordered_set<string>s; s.insert("hot"); s.insert("dot"); s.insert("dog"); s.insert("lot"); s.insert("log"); vector<vector<string>> result = ss.findLadders("hit", "cog", s); for (auto item : result) { for (auto i : item) { cout << i << " "; } cout << endl; } } <file_sep>/Permutation_Sequence.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Permutation_Sequence.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-06 10:48:01 // MODIFIED: 2015-05-06 11:33:15 #include <iostream> using namespace std; //DFS will TLE, get string directly //reference: http://fisherlei.blogspot.jp/2013/04/leetcode-permutation-sequence-solution.html class Solution { public: string getPermutation(int n, int k) { int nums[9]; int perm = 1; for (int i = 0; i < n;i ++) { nums[i] = i + 1; perm *= (i + 1); } k --;//index starts from 0 string target; for (int i = 0;i < n;i ++) { perm = perm / (n - i); int index = k / perm; target.push_back(nums[index] + '0'); //in case of re-use for (int j = index;j < n - i; j ++) nums[j] = nums[j + 1]; k = k % perm; } return target; } }; <file_sep>/Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-21 20:13:17 // MODIFIED: 2015-04-21 22:02:38 #include <iostream> using namespace std; /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { int number = inorder.size(); if (number == 0) return NULL; int root = postorder[number - 1]; TreeNode* rootNode = new TreeNode(root); int rootIndex; for (int i = 0; i < number; i ++) { if (root == inorder[i]) { rootIndex = i; break; } } TreeNode* leftRootNode; TreeNode* rightRootNode; if (rootIndex - 1 >= 0) { int leftRoot = postorder[number - 1 - (number - 1 - rootIndex) - 1]; leftRootNode = buildSubTree(inorder, postorder, 0, rootIndex - 1, rootIndex - 1, leftRoot); } else { leftRootNode = NULL; } if (rootIndex + 1<= number - 1) { int rightRoot = postorder[number - 1 - 1]; rightRootNode = buildSubTree(inorder, postorder, rootIndex + 1, number - 1, number - 1 - 1, rightRoot); } else { rightRootNode = NULL; } rootNode->left = leftRootNode; rootNode->right = rightRootNode; return rootNode; } TreeNode *buildSubTree(vector<int> &inorder, vector<int> &postorder, int start, int end, int index, int root) { if (start == end) { TreeNode* child = new TreeNode(inorder[start]); return child; } TreeNode* rootNode = new TreeNode(root); int rootIndex; for (int i = start; i <= end; i ++) { if (root == inorder[i]) { rootIndex = i; break; } } TreeNode* leftRootNode; TreeNode* rightRootNode; if (rootIndex - 1 >= start) { int leftRoot = postorder[index - (end - rootIndex) - 1]; leftRootNode = buildSubTree(inorder, postorder, start, rootIndex - 1, index - (end - rootIndex) - 1, leftRoot); } else { leftRootNode = NULL; } if (rootIndex + 1 <= end) { int rightRoot = postorder[index - 1]; rightRootNode = buildSubTree(inorder, postorder, rootIndex + 1, end, index - 1, rightRoot); } else { rightRootNode = NULL; } rootNode->left = leftRootNode; rootNode->right = rightRootNode; return rootNode; } }; <file_sep>/Max_Points_On_A_Line.cpp /********************************************************************************* * File Name : Max_Points_On_A_Line.cpp * Created By : laosiaudi * Creation Date : [2015-10-19 15:51] * Last Modified : [2015-10-19 16:06] * Description : **********************************************************************************/ /** * * Definition for a point. * * struct Point { * * int x; * * int y; * * Point() : x(0), y(0) {} * * Point(int a, int b) : x(a), y(b) {} * * }; * */ class Solution { public: int maxPoints(vector<Point>& points) { unordered_map<float, int> slope; int maxNum = 0; for (int i = 0;i < points.size(); i ++) { slope.clear(); slope[INT_MIN] = 0; int duplicate = 1; for (int j = i + 1; j < points.size(); j ++) { if (points[j].x == points[i].x && points[j].y == points[i].y) { duplicate ++; continue; } float k = (points[j].x == points[i].x) ? INT_MAX : (float)(points[j].y - points[i].y) / (points[j].x - points[i].x); if (slope.find(k) == std::end(slope)) slope[k] = 1 ; else slope[k] ++; } for (auto it : slope) { if (it.second + duplicate > maxNum) maxNum = it.second + duplicate; } } return maxNum; } }; <file_sep>/Paint_Fence.cpp /********************************************************************************* * File Name : Paint_Fence.cpp * Created By : laosiaudi * Creation Date : [2015-10-22 16:24] * Last Modified : [2015-10-25 17:52] * Description : **********************************************************************************/ //google #include <vector> #include <iostream> using namespace std; class Solution { public: int numWays(int n, int k) { if (n == 0 || k == 0) return 0; if (n == 1) return k; int s = k; int d = k * (k - 1); for (int i = 2; i < n; i ++) { int temp = s + d; s = d; d = (k - 1) * temp; } return d + s; } }; int main() { Solution s; for (int i = 1; i <= 20; i ++) cout << s.numWays(i, 2) << endl; } <file_sep>/First_Bad_Version.cpp /********************************************************************************* * File Name : First_Bad_Version.cpp * Created By : laosiaudi * Creation Date : [2015-11-11 19:36] * Last Modified : [2015-11-11 19:41] * Description : **********************************************************************************/ // Forward declaration of isBadVersion API. bool isBadVersion(int version); class Solution { public: int firstBadVersion(int n) { int start = 1, end = n; int target = 0; while (start <= end) { int mid = start + (end - start) / 2;//(start + end)/2 will cause overflow if (isBadVersion(mid)) { target = mid; end = mid - 1; } else { start = mid + 1; if (isBadVersion(start)) return start; } } return target; } }; <file_sep>/Palindrome_Number.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Palindrome_Number.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-06 11:38:20 // MODIFIED: 2015-05-06 11:51:05 #include <iostream> using namespace std; class Solution { public: bool isPalindrome(int x) { if (x < 0) return false;//negative numbers are not palindrome_number int y = reverse(x); if (y == x) return true; else return false; } int reverse(int x) { long long res = 0;//handle overflow while (x != 0) { int temp = x % 10; res = res* 10 + temp; x = x / 10; } if (res > INT_MAX || res < INT_MIN) //handle overflow return 0; return res; } }; //simple solution class Solution { public: bool isPalindrome(int x) { if (x < 0) return false; int div = 1; while (x/div >= 10) { div *= 10; } while (x > 0) { int first = x/div; int last = x % 10; if (first != last) return false; x = x % div / 10; div /= 100; } return true; } }; int main() { Solution s; bool k = s.isPalindrome(-2147447412); if (k) cout << "yes\n"; return 0; } <file_sep>/Single_Number_III.cpp /********************************************************************************* * File Name : Single_Number_III.cpp * Created By : laosiaudi * Creation Date : [2015-10-24 14:25] * Last Modified : [2015-10-24 14:31] * Description : **********************************************************************************/ class Solution { public: vector<int> singleNumber(vector<int>& nums) { vector<int>result; if (nums.size() == 0) return result; int XOR = nums[0]; for (int i = 1; i < nums.size(); i ++) XOR ^= nums[i]; int posOfOne = 1; while ((posOfOne & XOR) != posOfOne) posOfOne = posOfOne << 1; int x = 0; for (int i = 0;i < nums.size(); i ++) { if (nums[i] & posOfOne) x = x ^ nums[i]; } int y = x ^ XOR; result.push_back(x); result.push_back(y); return result; } }; <file_sep>/Move_Zeroes.cpp /********************************************************************************* * File Name : Move_Zeroes.cpp * Created By : laosiaudi * Creation Date : [2015-09-24 15:11] * Last Modified : [2015-09-24 15:18] * Description : **********************************************************************************/ class Solution { public: void moveZeroes(vector<int>& nums) { int size = nums.size(); int start = 0; int num = 0; int i; for (i = 0; i < size; i ++) { if (nums[i] != 0) nums[i - num] = nums[i]; else num ++; } for (int j = i - num; j < size; j ++) nums[j] = 0; } }; <file_sep>/Find_the_Duplicate_Number.cpp /********************************************************************************* * File Name : Find_the_Duplicate_Number.cpp * Created By : laosiaudi * Creation Date : [2015-09-30 14:52] * Last Modified : [2015-09-30 15:45] * Description : **********************************************************************************/ class Solution { public: int findDuplicate(vector<int>& nums) { int size = nums.size(); int low = 1; int high = size - 1; while (low <= high) { int mid = (low + high) / 2; int cnt = count(nums, mid); if (cnt > mid) { high = mid - 1; } else { low = mid + 1; } } return low; } int count(vector<int> &nums, int limit) { int cnt = 0; for (int i = 0; i < nums.size(); i ++) { if (nums[i] <= limit) { cnt ++; } } return cnt; } }; <file_sep>/Remove_Nth_Node_From_End_Of_List.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Remove_Nth_Node_From_End_Of_List.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-27 00:57:04 // MODIFIED: 2015-04-27 01:33:51 #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { if (head == NULL) return head; ListNode* helper = new ListNode(0); helper->next = head; ListNode* walker = helper; while (1) { ListNode* temp = walker; for (int i = 1; i <= n + 1; i ++) temp = temp->next; if (temp == NULL) { ListNode* removeNode = walker->next; walker->next = removeNode->next; break; } walker = walker->next; } head = helper->next; delete helper; return head; } }; //一个指针先走n步,然后一起走,当第一个指针到达终点,第二个指针指向的节点就是要删除的节点 class BetterSolution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { if (head == NULL) return head; ListNode* pre = head; ListNode* walker = head; int step = 0; while (step < n && pre != NULL) { pre = pre->next; step ++; } while (step == n && pre == NULL) { head = head->next; return head; } while (pre->next != NULL) { walker = walker->next; pre = pre->next; } walker->next = walker->next->next; return head; } }; <file_sep>/Reverse_Bits.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Reverse_Bits.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-06-04 17:59:36 // MODIFIED: 2015-06-04 18:12:58 #include <iostream> using namespace std; //to optimize, can split the 32bits to chunks of 4bits, and store //reversed representations of every 4-bit patterns, e.g. 1000 --> 0001 class Solution { public: uint32_t reverseBits(uint32_t n) { int counter = 31; uint32_t res = 0; while (counter--){ res += (n & 0x1); res = res << 1; n = n >> 1; } return res + (n & 0x1); } }; <file_sep>/Restore_IP_Address.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Restore_IP_Address.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-15 22:42:22 // MODIFIED: 2015-05-15 23:28:50 #include <iostream> #include <vector> using namespace std; class Solution { public: vector<string> restoreIpAddresses(string s) { int size = s.size(); vector<string>v; if (size < 4) return v; vector<string>ip; recursiveRestore(v, 0, s, size, 0, ip); return v; } void recursiveRestore(vector<string> &v, int start, string s, int size, int num, vector<string> &ip) { if (start == size && num < 4) return; if (num == 4 && start != size) return; if (num == 4 && start == size) { string temp = ip[0]; for (int i = 1; i < 4; i ++) temp = temp + "." + ip[i]; v.push_back(temp); return ; } int step; if (s[start] == '0') step = 0; else step = 2; for (int i = 0; i <= step; i ++) { int res = 0; bool flag = true; for (int j = 0; j <= i; j ++) { if (start + j >= size) { return; } res = 10 * res + s[start + j] - '0'; } if (res > 255 || res < 0) continue; else { ip.push_back(s.substr(start, i + 1)); recursiveRestore(v, start + i + 1, s, size, num + 1, ip); ip.pop_back(); } } } }; int main () { Solution s; s.restoreIpAddresses("100100"); return 0; } <file_sep>/Shortest_Palindrome.cpp /********************************************************************************* * File Name : Shortest_Palindrome.cpp * Created By : laosiaudi * Creation Date : [2015-10-29 13:56] * Last Modified : [2015-10-29 14:20] * Description : **********************************************************************************/ class Solution { public: string shortestPalindrome(string s) { if (s.size() <= 1) return s; vector<bool>palin(s.size(), false); for (int i = 0; i < s.size(); i ++) { if (palindrome(i, s)) palin[i] = true; } int index = s.size(); for (int i = s.size() - 1; i >= 0;i --) { if (palin[i] == true) { index = i + 1; break; } } if (index == s.size()) return s; else { string tmp; for (int i = index; i < s.size() - 1; i ++) tmp.insert(0, 1, s[i]); return tmp + s; } } bool palindrome(int end, string s) { int start = 0; while (start <= end) { if (s[start] != s[end]) return false; else { start ++; end --; } } return true; } }; <file_sep>/Container_With_Most_Water.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Container_With_Most_Water.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-21 19:57:17 // MODIFIED: 2015-04-21 20:07:09 #include <iostream> using namespace std; class Solution { public: int maxArea(vector<int>& height) { int left = 0; int right = height.size() - 1; int maxValue = 0; while (left < right) { int shorter = height[left] < height[right] ? height[left] : height[right]; int area = (right - left) * shorter; maxValue = area > maxValue ? area : maxValue; if (height[left] < height[right]) left ++; else right --; } return maxValue; } }; <file_sep>/Path_Sum.cpp /********************************************************************************* * File Name : Path_Sum.cpp * Created By : laosiaudi * Creation Date : [2015-09-08 20:35] * Last Modified : [2015-09-08 20:56] * Description : **********************************************************************************/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; * */ class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if (root == NULL) return false; return checkSum(root, 0, sum); } bool checkSum(TreeNode* root, int tmp, int sum) { if (root->left == NULL && root->right == NULL) return (tmp + root->val) == sum; bool re = false; if (root->left) re = checkSum(root->left, tmp + root->val, sum); if (re) return true; if (root->right) re = checkSum(root->right, tmp + root->val, sum); return re; } }; <file_sep>/Search_A_2D_Matrix.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Search_A_2D_Matrix.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-18 16:44:58 // MODIFIED: 2015-08-01 23:16:40 #include <iostream> #include <vector> using namespace std; class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int line = matrix.size(); if (line == 0) return false; int col = matrix[0].size(); if (target < matrix[0][0]) return false; int start = 0; int end = line - 1; int mid = (start + end)/2; while (start <= end) { mid = (start + end)/2; if (matrix[mid][0] == target) return true; else if (target < matrix[mid][0]) end = mid - 1; else start = mid + 1; } start = end; int rowStart = 0; int rowEnd = col - 1; int rowMid = (rowStart + rowEnd)/2; if (matrix[start][rowMid] == target) return true; while (rowStart <= rowEnd) { rowMid = (rowStart + rowEnd)/2; if (matrix[start][rowMid] == target) return true; else if (target < matrix[start][rowMid]) rowEnd = rowMid - 1; else rowStart = rowMid + 1; } return false; } }; int main() { vector<vector<int> >v; vector<int>vv; vv.push_back(1); vv.push_back(1); v.push_back(vv); Solution s; s.searchMatrix(v, 2); return 0; } <file_sep>/Combination_Sum_II.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Combination_Sum_II.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-22 18:40:47 // MODIFIED: 2015-04-22 19:54:49 #include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: vector<vector<int> > combinationSum2(vector<int> &candidates, int target) { vector<vector<int> >v; int size = candidates.size(); if (size == 0) return v; sort(candidates.begin(), candidates.end()); for (int i = 0; i < size; i ++) { if (i > 0 && candidates[i] == candidates[i - 1]) continue; vector<int>temp; if (candidates[i] == target) { temp.push_back(candidates[i]); v.push_back(temp); } else { temp.push_back(candidates[i]); recursiveFind(v, candidates, i + 1, temp, candidates[i], target); temp.pop_back(); } } return v; } void recursiveFind(vector<vector<int> > &v, vector<int> &candidates, int index, vector<int> &temp, int value, int target) { if (value == target) { v.push_back(temp); return ; } if (value > target) return ; int before = candidates[index]; for (int i = index; i < candidates.size(); i ++) { if (i > index && candidates[i] == candidates[i - 1]) continue; value += candidates[i]; temp.push_back(candidates[i]); recursiveFind(v, candidates, i + 1, temp, value, target); value -= candidates[i]; temp.pop_back(); } } }; int main() { vector<int>v; v.push_back(4); v.push_back(4); v.push_back(2); v.push_back(1); v.push_back(4); v.push_back(2); v.push_back(2); v.push_back(1); v.push_back(3); Solution s; s.combinationSum2(v, 6); return 0; } <file_sep>/Pascal_Trangle_II.cpp // C/C++ File // AUTHOR: laosi // FILE: Pascal_Trangle.cpp // ROLE: TODO (some explanation) // CREATED: 2014-12-11 22:27:07 // MODIFIED: 2014-12-12 00:15:41 #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> getRow(int rowIndex) { vector<int>v; v.push_back(1); for (int i = 0; i <= rowIndex; i ++) { int former = 1; int index = i + 1; for (int j = 0; j< index; j ++) { if (j == 0) { v[0] = 1;; former = 1; } else if (j == index - 1) { v.push_back(1); v[j - 1] = former; } else { int temp = v[j - 1]; v[j - 1] = former; former = temp + v[j]; } } } return v; } }; int main() { Solution s; vector<int>p; p = s.getRow(3); for (int i = 0;i < p.size();i ++) cout << p[i]; return 0; } <file_sep>/Flatten_Binary_Tree_To_Linked_List.cpp /********************************************************************************* * File Name : Flatten_Binary_Tree_To_Linked_List.cpp * Created By : laosiaudi * Creation Date : [2015-09-08 20:14] * Last Modified : [2015-09-08 20:33] * Description : **********************************************************************************/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; * */ class Solution { public: void flatten(TreeNode* root) { if (root == NULL) return; stack<TreeNode*>s; s.push(root); TreeNode* walker = new TreeNode(-1); TreeNode* head = walker; while (!s.empty()) { TreeNode* tmp = s.top(); s.pop(); walker->right = tmp; walker->left = NULL; walker = tmp; if (tmp->right != NULL) s.push(tmp->right); if (tmp->left != NULL) s.push(tmp->left); } delete []head; } }; <file_sep>/Rotate_List.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Rotate_List.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-26 23:11:40 // MODIFIED: 2015-04-27 00:10:11 #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if (head == NULL || k == 0) return head; ListNode* walker = head; ListNode* tail; int size = 0; while (walker != NULL) { size ++; if (walker->next == NULL) tail = walker; walker = walker->next; } k = k % size; if (size == 1 || k == size || k == 0) return head; ListNode* newhead; int index = 1; walker = head; while (index != size - k) { walker = walker->next; index ++; } newhead = walker->next; walker->next = NULL; tail->next = head; head = newhead; return head; } }; //也可以 首先从head开始跑,直到最后一个节点,这时可以得出链表长度len。然后将尾指针指向头指针,将整个圈连起来,接着往前跑len – k%len,从这里断开,就是要求的结果了。 <file_sep>/Remove_Duplicates_From_Sorted_Array_II.cpp // C/C++ File // AUTHOR: laosi // FILE: Remove_Element_From_Sorted_Array.cpp // ROLE: TODO (some explanation) // CREATED: 2014-12-12 00:25:25 // MODIFIED: 2014-12-11 23:13:49 #include <iostream> using namespace std; class Solution { public: int removeDuplicates(int A[], int n) { int index = 1; int count = 1; for (int i = 1;i < n;i ++) { if (A[i] == A[i - 1]) { if (count < 2) { A[index ++] = A[i]; count ++; } else { continue; } } else { A[index ++] = A[i]; count = 1; } } if (n == 0) return 0; else return index; } }; int main() { int a[10] = {1,1,1,3,3,4,6,6,6,7}; int b[5] = {1,2,3,4,5}; Solution s; int t = s.removeDuplicates(a, 10); for (int i = 0;i < t; i ++) cout << a[i]; cout << endl; t = s.removeDuplicates(b, 5); for (int i = 0;i < t; i ++) cout << b[i]; cout << endl; return 0; } <file_sep>/Swap_Nodes_In_Pairs.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Swap_Nodes_In_Pairs.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-26 14:13:26 // MODIFIED: 2015-04-26 14:45:45 #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* swapPairs(ListNode* head) { if (head == NULL || head->next == NULL) return head; ListNode* second = head->next; ListNode* temp = second->next; second->next = head; head->next = temp; head = second; ListNode* first; second = head->next; ListNode* start; start = head->next; while (start->next != NULL) { first = start->next; if (first == NULL || first->next == NULL) break; second = first->next; temp = second->next; first->next = temp; second->next = first; start->next = second; if (start->next == NULL) break; start = start->next->next; } return head; } }; //recursive class Solution { public: ListNode* swapPairs(ListNode* head) { if (head == NULL || head->next == NULL) return head; ListNode* nextPair = head->next->next; ListNode* newHead = head->next; head->next->next = head; head->next = swapPairs(nextPair); head = newHead; return head; } }; <file_sep>/Bitwise_And_Of_Numbers_Range.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Bitwise_And_Of_Numbers_Range.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-06-04 18:30:04 // MODIFIED: 2015-06-05 11:40:52 #include <iostream> using namespace std; class Solution { public: int rangeBitwiseAnd(int m, int n) { int mask = ~0; while (mask != 0) { if ((m & mask) == (n & mask)) break; mask = mask << 1; } return m & mask; } }; int main() { Solution s; cout << (2147483646 & 2147483647); cout << s.rangeBitwiseAnd(2147483646, 2147483647); } <file_sep>/Valid_Anagram.cpp /********************************************************************************* * File Name : Valid_Anagram.cpp * Created By : laosiaudi * Creation Date : [2015-09-11 14:29] * Last Modified : [2015-09-11 14:29] * Description : **********************************************************************************/ class Solution { public: bool isAnagram(string s, string t) { sort(s.begin(), s.end()); sort(t.begin(), t.end()); return s == t; } }; <file_sep>/Merge_Sorted_Array.cpp // C/C++ File // AUTHOR: laosi // FILE: Merge_Sorted_Array.cpp // ROLE: TODO (some explanation) // CREATED: 2014-12-11 18:36:48 // MODIFIED: 2014-12-11 18:59:05 #include <iostream> using namespace std; class Solution { public: void merge(int A[], int m, int B[], int n) { int *C = new int [m + n]; int i, j; int index = 0; for (i = 0, j = 0;i < m && j < n;) { if (A[i] < B[j]) { C[index ++] = A[i ++]; } else { C[index ++] = B[j ++]; } } if (i == m) { for (; index < n + m; index ++) C[index] = B[j ++]; } else { for (; index < m + n; index ++) C[index] = A[i ++]; } for (i = 0;i < m + n; i ++) { A[i] = C[i]; } delete []C; } }; int main() { Solution s; int a[100] = {}; int b[1] = {2}; s.merge(a, 0, b, 1); return 0; } <file_sep>/Maximum_Depth_of_Binary_Tree.cpp /********************************************************************************* * File Name : Minimum_Depth_of_Binary_Tree.cpp * Created By : laosiaudi * Creation Date : [2015-09-10 16:14] * Last Modified : [2015-09-10 16:35] * Description : **********************************************************************************/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; * */ class Solution { public: int maxDepth(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if(root == NULL) return 0; int lmin = maxDepth(root->left); int rmin = maxDepth(root->right); if(lmin ==0 && rmin ==0) return 1; if(lmin ==0) { lmin = INT_MIN; } if(rmin ==0){ rmin = INT_MIN; } return max(lmin, rmin) +1; } }; <file_sep>/Rotate_Image.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Rotate_Image.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-19 10:54:05 // MODIFIED: 2015-04-19 11:33:42 #include <iostream> using namespace std; class Solution { public: void rotate(vector<vector<int> > &matrix) { int line = matrix.size(); if (line <= 1) return ; int times = line / 2; for (int i = 0; i < times; i ++) { for (int j = i; j < n - i - 1;j ++) { int start = matrix[i][j]; int temp_1 = matrix[j][n - 1 - i]; matrix[j][n - 1 - i] = start; int temp_2 = matrix[n - 1 - i][n - 1 - j]; matrix[n - 1 - i][n - 1 - j] = temp_1; int temp_3 = matrix[n - 1 - j][i]; matrix[n - 1 - j][i] = temp_2; matrix[i][j] = temp_3; } } } }; <file_sep>/Game_Of_Life.cpp /********************************************************************************* * File Name : Game_Of_Lift.cpp * Created By : laosiaudi * Creation Date : [2015-10-24 14:46] * Last Modified : [2015-10-24 15:11] * Description : **********************************************************************************/ class Solution { public: void gameOfLife(vector<vector<int>>& board) { int m = board.size(); if (m == 0) return; int n = board[0].size(); vector<int>v(n, 0); vector<vector<int>>new_board(m, v); for (int i = 0; i < m; i ++) { for (int j = 0; j < n; j ++) { int tmp = getState(i, j, board, m, n); new_board[i][j] = tmp; } } board = new_board; } int getState(int i, int j, vector<vector<int>>& board, int m, int n) { int x[8] = {0, 0, 1, 1, 1, -1, -1, -1}; int y[8] = {1, -1, 1, -1, 0, 1, -1, 0}; int cnt = 0; for (int ii = 0; ii < 8; ii ++) { if (i + x[ii] < m && j + y[ii] < n && i + x[ii] >= 0 && j + y[ii] >= 0) { if (board[i + x[ii]][j + y[ii]] == 1) cnt ++; } } if (board[i][j] == 1) { if (cnt < 2) return 0; else if (cnt == 2 || cnt == 3) return 1; else return 0; } else { if (cnt == 3) return 1; else return 0; } } }; //state 0: dead - dead //state 1: live - live //state 2: live - dead //state 3: dead - live class BetterSolution { public: void gameOfLife(vector<vector<int>>& board) { int m = board.size(); if (m == 0) return; int n = board[0].size(); for (int i = 0; i < m; i ++) { for (int j = 0; j < n; j ++) { board[i][j] = getState(i, j, board, m, n); } } for (int i = 0; i < m; i ++) { for (int j = 0; j < n; j ++) board[i][j] %= 2; } } int getState(int i, int j, vector<vector<int>>& board, int m, int n) { int x[8] = {0, 0, 1, 1, 1, -1, -1, -1}; int y[8] = {1, -1, 1, -1, 0, 1, -1, 0}; int cnt = 0; for (int ii = 0; ii < 8; ii ++) { if (i + x[ii] < m && j + y[ii] < n && i + x[ii] >= 0 && j + y[ii] >= 0) { if (board[i + x[ii]][j + y[ii]] == 1 || board[i + x[ii]][j + y[ii]] == 2) cnt ++; } } if (board[i][j] == 1 || board[i][j] == 2) { if (cnt < 2) return 2; else if (cnt == 2 || cnt == 3) return 1; else return 2; } else { if (cnt == 3) return 3; else return 0; } } }; <file_sep>/3Sum.cpp // C/C++ File // AUTHOR: LaoSi // FILE: 3Sum.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-21 23:24:58 // MODIFIED: 2015-04-22 15:40:00 #include <iostream> using namespace std; class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int> >v; if (num.size() <= 2) return v; sort(num.begin(), num.end()); for (int i = 0; i <= num.size() - 3; i ++) { if (i > 0 && num[i] == num[i - 1]) continue; int start = i + 1; int end = num.size() - 1; while (start < end) { if (start > i + 1 && num[start] == num[start - 1]) { start ++; continue; } if (end < num.size() - 1 && num[end] == num[end + 1]) { end --; continue; } if (num[start] + num[end] == -num[i]) { vector<int>temp; temp.push_back(num[i]); temp.push_back(num[start]); temp.push_back(num[end]); v.push_back(temp); start ++; end --; } else if (num[start] + num[end] > -num[i]) { end --; } else { start ++; } } } return v; } }; <file_sep>/Single_Number_II.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Single_Number_II.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-06-06 20:27:46 // MODIFIED: 2015-06-06 21:20:47 #include <iostream> using namespace std; //each number appears three times or once. class Solution { public: //O(n) with extra space int singleNumber(vector<int> &nums) { vector<int>v(32, 0); int res = 0; for (int i = 0; i < 32; i ++) { for (int j = 0; j < nums.size(); j ++) { if ((nums[j] >> i) & 0x1) v[i] ++; } res = res | ((v[i] % 3) << i); } return res; } }; class BetterSolution { public: //O(n) without extra space int singleNumber(vector<int> &nums) { int count = 0; int res = 0; for (int i = 0; i < 32; i ++) { for (int j = 0; j < nums.size(); j ++) { if ((nums[j] >> i) & 0x1) count ++; } res = res | ((count % 3) << i); count = 0; } return res; } }; <file_sep>/Serialize_and_Deserialize_Binary_Treen.cpp class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { string result; recursiveSerial(root,result); return result; } void recursiveSerial(TreeNode* root, string &result) { if (root == NULL) { result = result + "#"; return; } result = result + to_string(root->val) + ","; string left = serialize(root->left); string right = serialize(root->right); result = result + left + right; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { int index = 0; return recursiveDeserialize(data, index); } TreeNode* recursiveDeserialize(string &data, int &index) { if (index >= data.size() || data[index] == '#') return NULL; int end = index; while (data[end] != ',') end ++; TreeNode* root = new TreeNode(atoi(data.substr(index, end - index).c_str())); index = end + 1; root->left = recursiveDeserialize(data, index); index = index + 1; root->right = recursiveDeserialize(data, index); return root; } }; <file_sep>/Merge_Intervals.cpp /********************************************************************************* * File Name : Merge_Intervals.cpp * Created By : laosiaudi * Creation Date : [2015-10-18 00:55] * Last Modified : [2015-10-18 01:05] * Description : **********************************************************************************/ /** * * Definition for an interval. * * struct Interval { * * int start; * * int end; * * Interval() : start(0), end(0) {} * * Interval(int s, int e) : start(s), end(e) {} * * }; * */ class Solution { public: vector<Interval> merge(vector<Interval>& intervals) { vector<Interval>result; if (intervals.size() == 0) return result; std::sort(std::begin(intervals), std::end(intervals), [](const Interval & first, const Interval & second){ return first.start < second.start; }); Interval compare = intervals[0]; for (int i = 1; i < intervals.size(); i ++) { Interval tmp = intervals[i]; if (compare.end < tmp.start) { result.push_back(compare); compare = tmp; } else if (compare.start > tmp.end) { result.push_back(tmp); } else { compare.start = compare.start < tmp.start ? compare.start : tmp.start; compare.end = compare.end > tmp.end ? compare.end : tmp.end; } } result.push_back(compare); return result; } }; <file_sep>/Missing_Number.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Missing_Number.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-09-03 17:26:45 // MODIFIED: 2015-09-03 20:49:31 #include <iostream> using namespace std; class Solution { public: int missingNumber(vector<int> &nums) { int n = nums.size(); int temp = 1; for (int i = 2; i <= n; i ++) temp = temp ^ i; for (int i = 0;i < n; i ++) temp = temp ^ nums[i]; return temp; } }; <file_sep>/Implement_Queue_using_Stacks.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Implement_Queue_using_Stacks.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-08-21 17:17:31 // MODIFIED: 2015-08-21 17:22:53 #include <iostream> using namespace std; class Queue { public: vector<int>s; // Push element x to the back of queue. void push(int x) { s.push_back(x); } // Removes the element from in front of queue. void pop(void) { s.erase(s.begin()); } // Get the front element. int peek(void) { return s.front(); } // Return whether the queue is empty. bool empty(void) { return s.size() == 0; } }; <file_sep>/Wiggle_Sort.cpp /********************************************************************************* * File Name : Wiggle_Sort.cpp * Created By : laosiaudi * Creation Date : [2015-10-24 16:10] * Last Modified : [2015-10-24 16:25] * Description : **********************************************************************************/ //google wiggle sort #include <vector> #include <iostream> using namespace std; class Solution { public: void wiggleSort(vector<int>& nums) { if (nums.size() <= 1) return; for (int i = 0; i < nums.size() - 1; i ++) { if (i % 2 == 1) { if (nums[i] < nums[i + 1]) { int tmp = nums[i]; nums[i] = nums[i + 1]; nums[i + 1] = tmp; } } else { if (nums[i] > nums[i + 1]) { int tmp = nums[i]; nums[i] = nums[i + 1]; nums[i + 1] = tmp; } } } } }; int main() { vector<int>v; v.push_back(3); v.push_back(5); v.push_back(2); v.push_back(1); v.push_back(6); v.push_back(4); Solution s; s.wiggleSort(v); for (auto item : v) { cout << item << " "; } } <file_sep>/Divide_Two_Integers.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Divide_Two_Integers.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-08 17:26:55 // MODIFIED: 2015-05-08 17:31:44 #include <iostream> using namespace std; //reference:http://www.cnblogs.com/TenosDoIt/p/3795342.html //reference:http://bangbingsyb.blogspot.hk/2014/11/divide-two-integers-divide-two-integers.html class Solution { public: int divide(int dividend, int divisor) { if(!divisor) return dividend>=0 ? INT_MAX : INT_MIN; if(dividend==INT_MIN && divisor==-1) return INT_MAX; //overflow problem bool isNeg = false; if((dividend<0 && divisor>0) || (dividend>0 && divisor<0)) isNeg = true; unsigned long long dvd = abs((long long)dividend); unsigned long long dvs = abs((long long)divisor); unsigned long long dvs_original = dvs; int i = 0; while(dvs<<(i+1) <= dvd) i++; int res = 0; while(dvd>=dvs_original) { if(dvd >= dvs<<i) { dvd -= dvs<<i; res += 1<<i; } i--; } return isNeg ? 0-res : res; } };<file_sep>/Best_Time_To_Buy_And_Sell_Stock.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Best_Time_To_Buy_And_Sell_Stock.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-01-10 11:46:14 // MODIFIED: 2015-01-10 11:51:44 #include <iostream> using namespace std; class Solution { public: int maxProfit(vector<int> &prices) { int length = prices.size(); if (length == 0) return 0; int minPrice = prices[0]; int bestProfit = 0; for (int i = 1; i < length; i ++) { if (prices[i] <= minPrice) { minPrice = prices[i]; } else { int temp = price[i] - minPrice; bestProfit = bestProfit > temp ? bestProfit : temp; } } return bestProfit; } }; <file_sep>/Validate_Binary_Search_Tree.cpp /********************************************************************************* * File Name : Validate_Binary_Search_Tree.cpp * Created By : laosiaudi * Creation Date : [2015-09-09 00:05] * Last Modified : [2015-09-09 00:39] * Description : **********************************************************************************/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * * }; * */ class Solution { public: //in-order traversal and see if it is increasing bool isValidBST(TreeNode* root) { vector<int>v; inorderTraverse(root, v); int n = v.size(); if (n <= 1) return true; for (int i = 1; i < n; i ++) { if (v[i] <= v[i - 1]) return false; } return true; } void inorderTraverse(TreeNode* root, vector<int>& v) { if (root == NULL) return; inorderTraverse(root->left, v); v.push_back(root->val); inorderTraverse(root->right, v); return; } //recursive method //pass min and max to every subtree //reference:http://fisherlei.blogspot.com/2013/01/leetcode-validate-binary-search-tree.html bool isValidBST(TreeNode* root) { return ISValidBST(root, LONG_MIN, LONG_MAX); } bool ISValidBST(TreeNode* root, long min, long max) { if (root == NULL) return true; if (root->val > min && root->val < max && ISValidBST(root->left, min, root->val) && ISValidBST(root->right, root->val, max)) return true; else return false; } }; <file_sep>/Contains_Duplicate_II.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Contains_Duplicate_II.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-06-01 15:55:10 // MODIFIED: 2015-06-01 16:26:04 #include <iostream> using namespace std; class Solution { public: //sliding window 76ms bool containsNearbyDuplicate(vector<int> &nums, int k) { int start = 0, end = 0; set<int>s; for (int i = 0; i < nums.size(); i ++) { if (s.find(nums[i]) == s.end()) { s.insert(nums[i]); end ++; } else { return true; } if (end - start > k) { s.erase(nums[start]); start ++; } } return false; } //using struct to keep index and value, 20ms struct Node { int value; int index; bool operator < (const Node& nd) const { if (value < nd.value) return true; else if (value > nd.value) return false; else { return index < nd.index; } } }; bool containsNearbyDuplicate(vector<int> &nums, int k) { if (nums.size() == 0) return false; vector<Node>v; for (int i = 0; i < nums.size(); i ++) { Node temp; temp.value = nums[i]; temp.index = i; v.push_back(temp); } sort(v.begin(), v.end()); int start = 0, end = 1; while (start <= nums.size() - 1 && end <= nums.size() - 1) { if (v[start].value == v[end].value) { if (v[end].index - v[start].index <= k) return true; else { start = end; end ++; } } if (end == nums.size()) break; if (v[start].value != v[end].value) { start = end; end = end + 1; } } return false; } }; <file_sep>/Spiral_Matrix_II.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Spiral_Matrix_II.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-12 14:18:35 // MODIFIED: 2015-04-12 14:25:30 #include <iostream> using namespace std; class Solution { public: vector<vector<int> > generateMatrix(int n) { vector<vector<int> >v; if (n == 0) return v; int matrix[n][n]; int k = 1; int top = 0; int left = 0; int right = n - 1; int bottom = n - 1; while (left < right && top < bottom) { for (int i = left; i < right; i ++) matrix[top][i] = k ++; for (int i = top; i < bottom; i ++) matrix[i][right] = k ++; for (int i = right; i > left; i --) matrix[bottom][i] = k ++; for (int i = bottom; i > top; i --) matrix[i][left] = k ++; top ++; right --; left ++; bottom --; } if (n % 2 != 0) matrix[n/2][n/2] = k; for (int i = 0; i < n; i ++) { vector<int>temp; for (int j = 0; j < n; j ++) temp.push_back(matrix[i][j]); v.push_back(temp); } return v; } }; <file_sep>/Binary_Tree_Zigzag_Level_Order_Traversal.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Binary_Tree_Zigzag_Level_Order_Traversal.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-06-02 16:20:19 // MODIFIED: 2015-06-02 16:59:26 #include <iostream> using namespace std; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int> >res; stack<TreeNode*>s; if (root == NULL) return res; else { s.push(root); recursiveZigZag(res, 0, s);//0 --> left to right return res; } } void recursiveZigZag(vector<vector<int> >&v, int bit, stack<TreeNode*> &s) { if (s.empty()) return; vector<int>level; stack<TreeNode*>temp; while (!s.empty()) { TreeNode* tn = s.top(); if (!bit) { if (tn->left) temp.push(tn->left); if (tn->right) temp.push(tn->right); } else { if (tn->right) temp.push(tn->right); if (tn->left) temp.push(tn->left); } level.push_back(tn->val); s.pop(); } bit = bit? 0 : 1; v.push_back(level); s = temp; recursiveZigZag(v, bit, temp); } }; <file_sep>/Count_Primes.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Count_Primes.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-06 14:45:31 // MODIFIED: 2015-05-06 14:58:49 #include <iostream> using namespace std; //reference:http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes class Solution { public: int countPrimes(int n) { vector<int>v(n + 1,1); int limit = sqrt(n); int counter = 0; for (int i = 2; i < n; i ++) { if (v[i] != 1) continue; int temp = 2; for (; temp * i <= n; temp ++) v[temp*i] = 2; counter ++; } return counter; } }; <file_sep>/Valid_Palindrome.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Valid_Palindrome.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-11 17:43:17 // MODIFIED: 2015-05-11 17:52:49 #include <iostream> using namespace std; class Solution { public: bool isPalindrome(string s) { int size = s.size(); if (size == 0) return true; std::transform(s.begin(), s.end(), s.begin(), ::tolower); int start = 0; int end = size - 1; while (start < end) { while (judge(s[start]) == false && start < end) { start ++; } while (judge(s[end]) == false && start < end) { end --; } if (s[start] != s[end]) return false; start ++; end --; } return true; } bool judge(char s) { if (s >= 'a' && s <= 'z') return true; if (s >= '0' && s <= '9') return true; return false; } }; <file_sep>/Decode_Ways.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Decode_Ways.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-15 10:35:29 // MODIFIED: 2015-05-15 10:59:54 #include <iostream> using namespace std; class Solution { public: int numDecodings(string s) { int num = 0; int len = s.size(); if (len == 0) return 0; vector<int>res(len + 1, 1); if (s[len - 1] != '0') res[1] = 1; else res[1] = 0; for (int i = 2; i <= len ; i ++) { int d1 = s[len - i] - '0'; if (d1 == 0) { res[i] = 0; continue; } int d2 = s[len - i + 1] - '0'; int temp = d1 * 10 + d2; if (temp <= 26) res[i] = res[i - 1] + res[i - 2]; else res[i] = res[i - 1]; } return res[len]; } }; <file_sep>/Invert_Binary_Tree.cpp /********************************************************************************* * File Name : Invert_Binary_Tree.cpp * Created By : laosiaudi * Creation Date : [2015-09-07 13:57] * Last Modified : [2015-09-07 14:02] * Description : **********************************************************************************/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; * */ class Solution { public: TreeNode* invertTree(TreeNode* root) { if (root == NULL) return NULL; TreeNode* oldLeft = root->left; TreeNode* oldRight = root->right; root->left = invertTree(oldRight); root->right = invertTree(oldLeft); return root; } }; <file_sep>/Unique_Paths_II.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Unique_Paths.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-11 19:01:27 // MODIFIED: 2015-04-11 20:08:01 // If use method like DFS, will TLE. Should store state first #include <iostream> #include <stack> #include <vector> using namespace std; class Solution { public: struct grid { int x; int y; }; int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); if (m == 1 && n == 1) return obstacleGrid[0][0] == 1 ? 0 : 1; if (obstacleGrid[0][0] == 1) return 0; for (int i = 0;i < m;i ++) { for (int j = 0; j < n;j ++) { visit[i][j] = false; way[i][j] = 0; } } return recursivePath(1, 0, m, n, obstacleGrid) + recursivePath(0, 1, m, n, obstacleGrid); } int recursivePath(int x, int y, int line, int col, vector<vector<int> > &obstacleGrid) { if (x < 0 || x >= line || y < 0 || y >= col || obstacleGrid[x][y] == 1) return 0; if (x == line - 1 && y == col - 1) return 1; if (visit[x][y] == true) return way[x][y]; else { visit[x][y] = true; way[x][y] = recursivePath(x, y + 1, line, col, obstacleGrid) + recursivePath(x + 1, y , line , col, obstacleGrid); return way[x][y]; } } bool visit[100][100]; int way[100][100]; }; int main() { Solution s; cout << s.uniquePathsWithObstacles(23,12) << endl; cout << s.uniquePathsWithObstacles(3,3) << endl; cout << s.uniquePathsWithObstacles(2,2) << endl; return 0; } <file_sep>/Populating_Next_Right_Pointers_in_Each_Node.cpp /********************************************************************************* * File Name : Populating_Next_Right_Pointers_in_Each_Node.cpp * Created By : laosiaudi * Creation Date : [2015-09-10 15:35] * Last Modified : [2015-09-10 16:13] * Description : **********************************************************************************/ /** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; * */ class Solution { public: void connect(TreeLinkNode *root) { if (root == NULL) return; if (root->left != NULL && root->right != NULL) { root->left->next = root->right; connectTwoNodes(root->left, root->right); } return; } void connectTwoNodes(TreeLinkNode* left, TreeLinkNode* right) { if (left->left != NULL && right->left != NULL) { left->left->next = left->right; right->left->next = right->right; left->right->next = right->left; connectTwoNodes(left->left, left->right); connectTwoNodes(left->right, right->left); connectTwoNodes(right->left, right->right); return; } } //another solution //reference:http://siddontang.gitbooks.io/leetcode-solution/content/tree/populating_next_right_pointers_in_each_node.html void connect(TreeLinkNode *root) { if(!root) { return; } TreeLinkNode* p = root; TreeLinkNode* first = NULL; while(p) { //记录下层第一个左子树 if(!first) { first = p->left; } //如果有左子树,那么next就是父节点 if(p->left) { p->left->next = p->right; } else { //叶子节点了,遍历结束 break; } //如果有next,那么设置右子树的next if(p->next) { p->right->next = p->next->left; p = p->next; continue; } else { //转到下一层 p = first; first = NULL; } } } }; <file_sep>/ZigZag_Convertion.cpp // C/C++ File // AUTHOR: LaoSi // FILE: ZigZag_Convertion.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-31 14:31:21 // MODIFIED: 2015-05-31 20:22:16 #include <iostream> using namespace std; class Solution { public: string convert(string s, int Rows) { if (Rows <= 1) return s; int X = 2*(Rows - 1); int len = s.size(); string res; int index = 0; for (int i = 1; i <= Rows && index <= len - 1; i ++) { res.push_back(s[index]); int step = Rows - i; int pre = index; int next = pre + 2*step; while (1) { if (step == 0) { next = next + X; if (next >= len) break; res.push_back(s[next]); } else { if (next >= len) break; res.push_back(s[next]); pre = next; next = pre + X - 2*step; if (next >= len) break; if (next != pre) { res.push_back(s[next]); pre = next; next = pre + 2*step; } else { pre = next; next = pre + X; } } } index ++; } return res; } }; class ShorterSolution { public: string convert(string s, int Rows) { if (Rows <= 1) return s; int X = 2*(Rows - 1); string res; for (int i = 1; i <= Rows; i ++) { for (int j = i - 1; j < s.size();j += X) { res.push_back(s[j]); if (i != 1 && i != Rows && j + X - 2*(i - 1) < s.size()) res.push_back(s[j + X - 2 * (i - 1)]); } } return res; } }; <file_sep>/Sort_List.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Sort_List.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-26 14:48:33 // MODIFIED: 2015-04-26 16:07:40 #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* sortList(ListNode* head) { if (head == NULL || head->next == NULL) return head; ListNode* oneStep = head; ListNode* twoStep = head; while (twoStep->next != NULL && twoStep->next->next != NULL) { oneStep = oneStep->next; twoStep = twoStep->next->next; } ListNode* secondHead = oneStep->next; oneStep->next = NULL; //将前半段和后半段分开,便于后面合并 ListNode* firstHead = sortList(head); secondHead = sortList(secondHead); head = merge(firstHead, secondHead); return head; } ListNode* merge(ListNode* node1, ListNode* node2) { //将后半段插入到前半段 ListNode *helper = new ListNode(0); helper->next = node1; ListNode* temp = helper; while (node1 != NULL && node2 != NULL) { if (node1->val < node2->val) node1 = node1->next; else { ListNode* next = node2->next; node2->next = temp->next; temp->next = node2; node2 = next; } temp = temp->next; } if (node2 != NULL) temp->next = node2; return helper->next; } }; <file_sep>/Spiral_Matrix.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Spiral_Matrix.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-12 10:34:05 // MODIFIED: 2015-04-12 14:14:52 #include <iostream> #include <vector> using namespace std; class BetterSolution { public: vector<int> spiralOrder(vector<vector<int> > &matrix) { vector<int>v; int line = matrix.size(); if (line == 0) return v; if (line == 1) return matrix[0]; int col = matrix[0].size(); if (col == 1) { for (int i = 0; i < line; i ++) v.push_back(matrix[i][0]); return v; } int top = 0; int left = 0; int right = col - 1; int bottom = line - 1; while (left < right && top < bottom) { for (int i = left; i < right; i ++) v.push_back(matrix[top][i]); for (int i = top; i < bottom; i ++) v.push_back(matrix[i][right]); for (int i = right; i > left; i --) v.push_back(matrix[bottom][i]); for (int i = bottom; i > top; i --) v.push_back(matrix[i][left]); top ++; right --; left ++; bottom --; } if (line % 2 != 0 || col % 2 != 0){ if (left < right) { for (int i = left; i <= right; i ++) v.push_back(matrix[top][i]); } if (top < bottom) { for (int i = top; i <= bottom; i++) v.push_back(matrix[i][left]); } if (left == right && top == bottom ) v.push_back(matrix[top][left]); } return v; } }; class Solution { public: vector<int> spiralOrder(vector<vector<int> > &matrix) { vector<int>v; int line = matrix.size(); if (line == 0) return v; int col = matrix[0].size(); if (line == 1) return matrix[0]; if (col == 1) { for (int i = 0; i < line; i ++) v.push_back(matrix[i][0]); return v; } int total = line * col; int num = 0; for (int i = 1; i <= line - 1; i++) { for (int j = i - 1; j <= col - i && num <= total - 1; j ++) { v.push_back(matrix[i - 1][j]); num ++; } for (int j = i; j <= line - i && num <= total - 1; j ++) { v.push_back(matrix[j][col - i]); num ++; } for (int j = col - i - 1; j >=i - 1 && num <= total - 1; j --) { v.push_back(matrix[line - i][j]); num ++; } for (int j = line - i - 1; j >= i && num <= total - 1; j --) { v.push_back(matrix[j][i - 1]); num ++; } } return v; } }; int main() { vector<vector<int> >v; vector<int>v1; v1.push_back(2); v1.push_back(5); v1.push_back(8); vector<int>v2; v2.push_back(4); v2.push_back(0); v2.push_back(-1); v.push_back(v1); v.push_back(v2); Solution s; vector<int>re = s.spiralOrder(v); for (int i = 0;i < re.size(); i ++) cout << re[i] << " "; vector<vector<int> >vv; vector<int>v3; v3.push_back(1); v3.push_back(2); vv.push_back(v3); BetterSolution ss; vector<int>rr = ss.spiralOrder(vv); cout << endl; for (int i = 0;i < rr.size(); i ++) cout << rr[i] << " "; return 0; } <file_sep>/LRU_Cache.cpp /********************************************************************************* * File Name : LRU_Cache.cpp * Created By : laosiaudi * Creation Date : [2015-10-18 17:40] * Last Modified : [2015-10-18 19:43] * Description : **********************************************************************************/ #include <map> #include <vector> using namespace std; class LRUCache{ public: struct Node { int key; int value; Node* pre; Node* next; Node(int k, int v) { key = k; value = v; pre = next = NULL; } }; Node* head; Node* tail; int capacity; int cnt; map<int,Node*>table; LRUCache(int capacity) { this->capacity = capacity; cnt = 0; head = new Node(0, 0); tail = head; } int get(int key) { if (table.find(key) == std::end(table)) return -1; int v = table[key]->value; adjustCache(key); return v; } void set(int key, int value) { if (table.find(key) == std::end(table)) { if (cnt == capacity) { int old_key = head->next->key; table.erase(old_key); Node* old_node = head->next; head->next = old_node->next; if (old_node->next != NULL) old_node->next->pre = head; Node* new_node = new Node(key, value); if (tail != old_node) { tail->next = new_node; new_node->pre = tail; } else { head->next = new_node; new_node->pre = head; } table[key] = new_node; tail = new_node; delete old_node; } else { Node* new_node = new Node(key, value); tail->next = new_node; new_node->pre = tail; tail = new_node; table[key] = new_node; cnt ++; } } else { table[key]->value = value; adjustCache(key); } } void adjustCache(int key) { if (tail == table[key]) return; Node* pre = table[key]->pre; Node* next = table[key]->next; pre->next = next; next->pre = pre; table[key]->next = tail->next; table[key]->pre = tail; tail->next = table[key]; tail = table[key]; } }; <file_sep>/Search_In_Rotated_Sorted_Array.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Search_In_Rotated_Sorted_Array.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-01-30 11:25:08 // MODIFIED: 2015-04-23 17:20:04 #include <iostream> using namespace std; class Solution { public: int search(int A[], int n, int target) { if (n == 0) return -1; int start = 0; int end = n - 1; int middle = (0 + n - 1)/2; while (start <= end) { if (A[middle] == target) return middle; if (A[middle] < A[end]) { //右边为升序 if (target > A[middle] && target <= A[end]) start = middle + 1; else end = middle - 1; } else { //左边为升序 if (target < A[middle] && target >= A[start]) end = middle - 1; else start = middle + 1; } middle = (start + end)/2; } return -1; } }; <file_sep>/Remove_Duplicates_From_Sorted_List_II.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Remove_Duplicates_From_Sorted_List_II.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-28 11:50:11 // MODIFIED: 2015-04-28 13:08:19 #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if (head == NULL) return head; ListNode* helper = new ListNode(-9999); helper->next = head; ListNode* walker = helper; ListNode* pre = helper; bool isDuplicate = false; while (walker->next != NULL) { if (walker->next->val == walker->val) { if (isDuplicate == false) isDuplicate = true; ListNode* deleteNode = walker->next; walker->next = walker->next->next; } else { if (isDuplicate) { ListNode* deleteNode = walker; pre->next = walker->next; walker = walker->next; isDuplicate = false; } else { if (walker != helper) pre = pre->next; walker = walker->next; } } } if (isDuplicate) { pre->next = walker->next; } head = helper->next; delete helper; return head; } }; <file_sep>/Binary_Tree_Inorder_Traversal.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Binary_Tree_Inorder_Traversal.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-25 21:11:41 // MODIFIED: 2015-04-25 21:14:42 #include <iostream> using namespace std; /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode *root) { vector<int>v; if (root == NULL) return v; recursiveTraversal(v, root->left); v.push_back(root->val); recursiveTraversal(v, root->right); return v; } void recursiveTraversal(vector<int> &v, TreeNode *root) { if (root == NULL) return; recursiveTraversal(v, root->left); v.push_back(root->val); recursiveTraversal(v,root->right); } }; //iterative version class Solution { public: vector<int> inorderTraversal(TreeNode *root) { vector<int>result; stack<TreeNode*>s; if (root == NULL) return result; TreeNode* tmp = root; while (s.size() > 0 || tmp != NULL) { while (tmp != NULL) { s.push(tmp); tmp = tmp->left; } tmp = s.top(); result.push_back(tmp->val); s.pop(); tmp = tmp->right; } return result; } }; <file_sep>/Perfect_Squares.cpp /********************************************************************************* * File Name : Perfect_Squares.cpp * Created By : laosiaudi * Creation Date : [2015-10-16 19:34] * Last Modified : [2015-10-16 20:15] * Description : **********************************************************************************/ #include <iostream> #include <queue> #include <vector> #include <math.h> using namespace std; class Solution { public: int numSquares(int n) { vector<int>v; v.push_back(0); v.push_back(1); for (int i = 2; i <= n; i ++) { int tmp = sqrt(i); if (tmp * tmp == i) v.push_back(1); else { int min = INT_MAX; for (int j = tmp; j >= 1; j --) { int cnt = 1 + v[i - j * j]; min = min < cnt ? min : cnt; } v.push_back(min); } } return v[n]; } }; int main() { Solution s; cout << s.numSquares(3) << endl; //cout << s.numSquares(12) << endl; //cout << s.numSquares(13) << endl; //cout << s.numSquares(9) << endl; //cout << s.numSquares(48) << endl; //cout << s.numSquares(9975) << endl; return 0; } <file_sep>/Product_Of_Array_Except_Self.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Product_Of_Array_Except_Self.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-09-05 17:01:51 // MODIFIED: 2015-09-05 17:15:14 #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int size = nums.size(); vector<int>result(size, 1); if (size == 0 || size == 1) return result; for (int i = size - 2; i >= 0; i --) { result[i] = result[i + 1] * nums[i + 1]; } int tmp = 1; for (int i = 0; i < size; i ++) { result[i] = result[i] * tmp; tmp *= nums[i]; } return result; } }; <file_sep>/Longest_Palindrome_Substring.cpp /********************************************************************************* * File Name : Longest_Palindrome_Substring.cpp * Created By : laosiaudi * Creation Date : [2015-10-26 00:31] * Last Modified : [2015-10-26 01:41] * Description : **********************************************************************************/ #include <iostream> #include <string> #include <vector> using namespace std; class Solution { public: string longestPalindrome(string s) { int size = s.size(); if (size == 0) return ""; bool pa[size][size]; memset(pa, false, size*size*sizeof(bool)); int maxLen = 1; int start = 0; int end = 0; for (int j = 0; j < size; j ++) { for (int i = 0; i < j; i ++) { if (i + 1 == j) pa[i][j] = s[i] == s[j]; else { pa[i][j] = s[i] == s[j] && pa[i + 1][j - 1]; } if (pa[i][j] && maxLen < j - i + 1) { maxLen = (j -i + 1); start = i; end = j; } } pa[j][j] = true; } return s.substr(start, end - start + 1); } }; int main() { Solution s; cout << s.longestPalindrome("esbtzjaaijqkgmtaajpsdfiqtvxsgf<KEY>kd<KEY>adtftzweb<KEY>"); } <file_sep>/Ugly_Number_II.cpp /********************************************************************************* * File Name : Ugly_Number_II.cpp * Created By : laosiaudi * Creation Date : [2015-09-07 10:55] * Last Modified : [2015-09-07 11:26] * Description : **********************************************************************************/ #include <iostream> using namespace std; class Solution { public: //normal solution -- TLE int nthUglyNumber(int n) { int cnt = 1; int start = 1; for (; cnt != n; start ++) { if (isUgly(start)) cnt ++; } return start - 1; } bool isUgly(int num) { if (num <= 0) return false; if (num == 1) return true; int div[3] = {2, 3, 5}; int base = 0; int tmp = num; while (base <= 2) { if (tmp % div[base] == 0) tmp = tmp / div[base]; else base ++; if (tmp == 1) return true; } return false; } //better solution //reference:http://www.cnblogs.com/grandyang/p/4743837.html int nthUglyNumber(int n) { vector<int>res(1, 1); int i2 = 0, i3 = 0, i5 = 0; while (res.size() < n) { int m2 = res[i2] * 2; int m3 = res[i3] * 3; int m5 = res[i5] * 5; int tmp = m2 < m3 ? m2 : m3; int mm = tmp < m5 ? tmp : m5; if (mm == m2) i2 ++; if (mm == m3) i3 ++; if (mm == m5) i5 ++; res.push_back(mm); } return res[n - 1]; } }; <file_sep>/Find_Minimum_In_Rotated_Sorted_Array.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Find_Minimum_In_Rotated_Sorted_Array.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-01-08 20:09:54 // MODIFIED: 2015-01-08 20:43:46 #include <iostream> #include <vector> using namespace std; class Solution { public: #define SpecialNum 999999 int findMin(vector<int> &num) { int length = num.size(); if (length == 1) return num[0]; int result = findByRecursive(num, 0, length - 1); if (result == SpecialNum) return num[0]; else return result; } int findByRecursive(const vector<int>&A, int start, int end) { if (start == end) { if (start == 0) { return (A[0] > A[1]?A[1]:SpecialNum); } else if (start == A.size() - 1) { return (A[start] < A[start - 1]?A[start]:SpecialNum); } else { return (A[start] > A[start - 1] && A[start] > A[start + 1])?A[start + 1]:SpecialNum; } } else { int pivot = (start + end)/2; int resultLeft = findByRecursive(A, start, pivot); if (resultLeft != SpecialNum) return resultLeft; int resultRight = findByRecursive(A, pivot + 1, end); if (resultRight != SpecialNum) return resultRight; return SpecialNum; } } }; int main() { Solution s; vector<int>num; num.push_back(4); num.push_back(5); num.push_back(6); num.push_back(7); num.push_back(0); num.push_back(1); num.push_back(2); cout << s.findMin(num) << endl; return 0; } <file_sep>/google_isunique.cpp /********************************************************************************* * File Name : google_isunique.cpp * Created By : laosiaudi * Creation Date : [2015-10-15 23:57] * Last Modified : [2015-10-16 00:14] * Description : **********************************************************************************/ #include <string> #include <vector> #include <set> #include <map> #include <iostream> using namespace std; class Solution { public: map<string, set<string>>abbr_set; void buildSet(vector<string> dict) { for (string s : dict) { int size = s.size(); string abbr = s[0] + to_string(size - 2) + s[size - 1]; abbr_set[abbr].insert(s); } } bool isUnique(string word) { int n = word.size(); string abbr = word[0] + to_string(n - 2) + word[n - 1]; return abbr_set[abbr].count(word) == abbr_set[abbr].size(); } }; int main() { Solution s; vector<string>v; v.push_back("deer"); v.push_back("door"); v.push_back("cake"); v.push_back("card"); s.buildSet(v); if (s.isUnique("dear")) cout << "error\n"; if (s.isUnique("cart")) cout << "cart\n"; if (s.isUnique("cane")) cout << "error\n"; if (s.isUnique("make")) cout << "make\n"; return 0; } <file_sep>/Power_Of_Two.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Power_Of_Two.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-09-03 17:08:25 // MODIFIED: 2015-09-03 17:22:41 #include <iostream> using namespace std; class Solution { public: bool isPowerOfTwo(int n) { int sign = (n >> 31) & 0x1; int y = n + ~1 + 1; int res = n & y; return !!n & !sign & !res; } }; <file_sep>/Minimum_Path_Sum.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Minimum_Path_Sum.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2014-12-14 12:43:25 // MODIFIED: 2014-12-14 12:49:35 #include <iostream> using namespace std; class Solution { public: int minPathSum(vector<vector<int> > &grid) { for (int i = 0; i < grid.size(); i ++) { for (int j = 0; j < grid[i].size(); j ++) { if (i == 0 && j == 0) continue; else { if (i == 0) grid[i][j] += grid[i][j - 1]; else if (j == 0) grid[i][j] += grid[i - 1][j]; else { grid[i][j] += (grid[i][j - 1] < grid[i - 1][j] ?grid[i][j - 1]:grid[i - 1][j]); } } } } int maxRow = grid.size() - 1; int maxCol = grid[maxRow].size() - 1; return grid[maxRow][maxCol]; } }; <file_sep>/H-Index_II.cpp /********************************************************************************* * File Name : H-Index_II.cpp * Created By : laosiaudi * Creation Date : [2015-09-11 19:53] * Last Modified : [2015-09-11 20:02] * Description : **********************************************************************************/ class Solution { public: int hIndex(vector<int>& citations) { int len = citations.size(); if (len == 0) return 0; int left = 0; int right = len - 1; while (left <= right) { int mid = (left + right) / 2; if (citations[mid] == len - mid) return (len - mid); else if (citations[mid] > len - mid) right = mid - 1; else left = mid + 1; } return len - left; } };<file_sep>/Lowest_Common_Ancestor_of_a_Binary_Search_Tree.cpp /********************************************************************************* * File Name : Lowest_Common_Ancestor_of_a_Binary_Search_Tree.cpp * Created By : laosiaudi * Creation Date : [2015-10-18 01:08] * Last Modified : [2015-10-18 01:10] * Description : **********************************************************************************/ /** * * Definition for a binary tree node. * * struct TreeNode { * * int val; * * TreeNode *left; * * TreeNode *right; * * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * * }; * */ class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { TreeNode* walker = root; if (walker == NULL) return NULL; while (walker != NULL) { if (walker->val > p->val && walker->val > q->val) walker = walker->left; else if (walker->val < p->val && walker->val < q->val) walker = walker->right; else return walker; } return NULL; } }; <file_sep>/Intersection_Of_Two_Linked_Lists.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Intersection_Of_Two_Linked_Lists.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-29 21:52:45 // MODIFIED: 2015-04-29 21:58:11 #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ //将其中一个链表首尾链接,然后找环就行 class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if (headA == NULL || headB == NULL) return NULL; ListNode* temp = headB; while (temp->next != NULL) { temp = temp->next; } temp->next = headB; ListNode* node = detectCycle(headA); temp->next = NULL; return node; } ListNode* detectCycle(ListNode *head) { if (head == NULL || head->next == NULL) return NULL; ListNode* walker = head; ListNode* runner = head; bool hasCycle = false; while (walker != NULL && runner != NULL && walker->next != NULL && runner->next != NULL) { walker = walker->next; runner = runner->next->next; if (walker == runner) { hasCycle = true; break; } } if (hasCycle == false) return NULL; else { runner = head; while (runner != walker) { runner = runner->next; walker = walker->next; } return runner; } } }; <file_sep>/Multiply_Strings.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Multiply_Strings.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-06 12:59:32 // MODIFIED: 2015-05-06 13:27:40 #include <iostream> #include <string> using namespace std; class Solution { public: string multiply(string num1, string num2) { int len1 = num1.size(); int len2 = num2.size(); if (len1 == 0 || len2 == 0) return ""; int numOfZeros = 0; string res = "0"; for (int i = len2 - 1;i >= 0; i --) { string temp = doMultiply(num1, num2[i], numOfZeros); res = doAdd(temp, res); numOfZeros ++; } if (res[0] == '0') return "0"; return res; } string doMultiply(string num1, char num, int numOfZeros) { int len = num1.size(); string res(len, ' '); int carry = 0; for (int i = len - 1; i >= 0; i--) { int temp = (num1[i] - '0')*(num - '0') + carry; carry = temp / 10; res[i] = temp % 10 + '0'; } if (carry > 0) { string s(1, carry + '0'); res = s + res; } for (int i = 1; i <= numOfZeros; i ++) { res = res + "0"; } return res; } string doAdd(string s1, string s2) { if (s2 == "0") return s1; if (s1 == "0") return s2; int len1 = s1.size(); int len2 = s2.size(); if (len1 < len2) { for (int i = 1;i <= len2 - len1; i ++) { s1 = "0" + s1; } } if (len2 < len1) { for (int i = 1; i <= len1 - len2; i ++) s2 = "0" + s2; } int maxLen = len1 > len2? len1 : len2; string res(maxLen, ' '); int carry = 0; for (int i = maxLen - 1; i >= 0; i --) { int temp = s1[i] - '0' + s2[i] - '0' + carry; carry = temp / 10; temp = temp % 10; res[i] = temp + '0'; } if (carry > 0) { string s(1, carry + '0'); res = s + res; } return res; } }; int main() { Solution s; cout << s.multiply("0", "0"); } <file_sep>/Count_Complete_Tree_Nodes.cpp /********************************************************************************* * File Name : Count_Complete_Tree_Nodes.cpp * Created By : laosiaudi * Creation Date : [2015-10-18 23:33] * Last Modified : [2015-10-18 23:57] * Description : **********************************************************************************/ /** * * Definition for a binary tree node. * * struct TreeNode { * * int val; * * TreeNode *left; * * TreeNode *right; * * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * * }; * */ //TLE class Solution { public: int countNodes(TreeNode* root) { queue<TreeNode*>q; int cnt = 0; if (root != NULL) q.push(root); while (!q.empty()) { TreeNode* tmp = q.front(); q.pop(); cnt ++; if (tmp->left != NULL) q.push(tmp->left); if (tmp->right != NULL) q.push(tmp->right); } return cnt; } }; class BetterSolution { public: int countNodes(TreeNode* root) { int depth = 0; TreeNode* node = root; while (node) { depth ++; node = node->left; } if (depth == 0) return 0; int left = 0; int right = (1 << (depth - 1)) - 1; while (left <= right) { int mid = (left + right) >> 1; if (getNode(root, mid, depth)) left = mid + 1; else right = mid - 1; } return (1 << (depth - 1)) + right; } bool getNode(TreeNode* root, int cnt, int depth) { for (int i = depth - 2; i >= 0; i --) { if (cnt & (1 << i)) root = root->right; else root = root->left; } return root != NULL; } }; <file_sep>/Anagrams.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Anagrams.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-04-26 10:07:01 // MODIFIED: 2015-04-26 11:16:03 #include <iostream> using namespace std; //TLE class Solution { public: vector<string> anagrams(vector<string>& strs) { vector<string>v; map<set<char>, int>m; for (int i = 0; i < strs.size(); i ++) { set<char>s; for (int j = 0; j < strs[i].size(); j ++) { s.insert(strs[i][j]); } if (strs[i] == "") s.insert('#'); if (m.find(s) == m.end()) { m[s] = i; } else { v.push_back(strs[m[s]]); v.push_back(strs[i]); } } return v; } }; //Sort and hash class BetterSolution { public: vector<string> anagrams(vector<string>& strs) { vector<string>v; map<string,int>m; set<string>s; for (int i = 0; i < strs.size(); i ++) { string c = strs[i]; sort(c.begin(), c.end()); if (m.find(c) == m.end()) { m[c] = i; } else { if (m[c] >= 0) { v.push_back(strs[m[c]]); m[c] = -1; } v.push_back(strs[i]); } } return v; } }; //也可以为字符串构造hash值,用26个质数代替26个字母的值,这样就保证了hash值唯一 <file_sep>/Shortest_Word_Distance_II.cpp /********************************************************************************* * File Name : Shortest_Word_Distance_II.cpp * Created By : laosiaudi * Creation Date : [2015-11-01 22:53] * Last Modified : [2015-11-01 22:54] * Description : **********************************************************************************/ class WordDistance { public: WordDistance(vector<string> words) { int n = words.size(); for (int i = 0; i < n; i++) wordInd[words[i]].push_back(i); } int shortest(string word1, string word2) { vector<int> indexes1 = wordInd[word1]; vector<int> indexes2 = wordInd[word2]; int m = indexes1.size(), n = indexes2.size(); int i = 0, j = 0, dist = INT_MAX; while (i < m && j < n) { dist = min(dist, abs(indexes1[i] - indexes2[j])); if (indexes1[i] < indexes2[j]) i++; else j++; } return dist; } private: unordered_map<string, vector<int> > wordInd; }; <file_sep>/Binary_Tree_Paths.cpp /********************************************************************************* * File Name : Binary_Tree_Paths.cpp * Created By : laosiaudi * Creation Date : [2015-09-07 13:03] * Last Modified : [2015-09-07 13:19] * Description : **********************************************************************************/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; **/ class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { vector<string>v; if (root == NULL) return v; string tmp = ""; tmp += to_string(root->val); computePath(root, tmp, v); return v; } void computePath(TreeNode* root, string tmp, vector<string> &v) { if (root->left == NULL && root->right == NULL) { v.push_back(tmp); return; } if (root->left != NULL) computePath(root->left, tmp + "->" + to_string(root->left->val), v); if (root->right != NULL) computePath(root->right, tmp + "->" + to_string(root->right->val), v); } }; <file_sep>/Generate_Parentheses.cpp // C/C++ File // AUTHOR: LaoSi // FILE: Generate_Parentheses.cpp // 2014 @laosiaudi All rights reserved // CREATED: 2015-05-15 11:10:10 // MODIFIED: 2015-05-15 13:40:13 #include <iostream> using namespace std; class Solution { public: vector<string> generateParenthesis(int n) { vector<string>v; if (n <= 0) return v; string temp; recursiveGenerate(v, n, n, temp); return v; } void recursiveGenerate(vector<string> &v, int left, int right, string temp) { if (left > right) return; if (left == 0 && right == 0) v.push_back(temp); if (left > 0) { temp.push_back('('); recursiveGenerate(v, left - 1, right, temp); temp.pop_back(); } if (right > 0) { temp.push_back(')'); recursiveGenerate(v, left, right - 1, temp); temp.pop_back(); } } };
b4d76ad42a97f55966edd6a8d27fce4da1e48351
[ "C++" ]
192
C++
laosiaudi/leetcode
372b05fac1b55ae1a2053f40cd28f48f7a260ea2
10802d7ccb69ba287b1db0cd501377054a770ae1
refs/heads/master
<file_sep>import Ws from "ws"; const wss = new Ws.Server({ port: 8080 }); const connections = []; wss.on("connection", (ws): void => { connections.push(ws); ws.on("message", (message): void => { connections.forEach((connection: Ws) => { connection.send(`Received: ${message} at ${new Date().toISOString()}`); }); }); }); <file_sep>export enum Instruments { BD = "BD", } <file_sep>import { Instruments } from "lib/instruments/instruments.types"; interface SoundPathShape extends Record<Instruments, string> {} export const SoundPaths: SoundPathShape = { [Instruments.BD]: "https://s3.amazonaws.com/iamjoshellis-codepen/pens-of-rock/drums/Kick.mp3", };
5b6c5c0aad156dcab722eb3ec9a73d5c85392a7a
[ "TypeScript" ]
3
TypeScript
dcastrodale/socket-drummer
dc4a20f30daadf758e89214b62376a8ea2f98c4e
c5fd1be418a37e8c19805f8e23a9425ceeb8fde6
refs/heads/master
<repo_name>gsrppaladin/pokedex3<file_sep>/pokedex/ViewController.swift // // ViewController.swift // pokedex // // Created by <NAME> on 12/13/16. // Copyright © 2016 simplyAmazingMachines. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UISearchBarDelegate { @IBOutlet weak var collection: UICollectionView! @IBOutlet weak var searchBar: UISearchBar! var pokemon = [Pokemon]() var filteredPokemon = [Pokemon]() var musicPlayer: AVAudioPlayer! var inSearchMode = false override func viewDidLoad() { super.viewDidLoad() collection.dataSource = self collection.delegate = self searchBar.delegate = self searchBar.returnKeyType = UIReturnKeyType.done parsePokemonCSV() initAudio() } func initAudio() { let path = Bundle.main.path(forResource: "music", ofType: "mp3")! do { musicPlayer = try AVAudioPlayer(contentsOf: URL(string: path)!) musicPlayer.prepareToPlay() musicPlayer.numberOfLoops = -1 musicPlayer.play() } catch let err as NSError { print(err.debugDescription) } } func parsePokemonCSV() { let path = Bundle.main.path(forResource: "pokemon", ofType: "csv")! //this is a path to the csv file do { //this parses to pull out the rows and go through each row and pulls out the pokeId and the name let csv = try CSV(contentsOfURL: path) let rows = csv.rows print(rows) for row in rows { let pokeId = Int(row["id"]!)! let name = row["identifier"]! //we then created a pokemon object and then attached that to our pokemon array above. At the end of this, when this is called, we have an array of pokemon filled with 700+ pokemon with their names and ID. let poke = Pokemon(name: name, pokedexId: pokeId) pokemon.append(poke) } } catch let err as NSError { print(err.debugDescription) } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PokeCell", for: indexPath) as? PokeCell{ let poke: Pokemon! if inSearchMode { poke = filteredPokemon[indexPath.row] cell.configureCell(poke) } else { poke = pokemon[indexPath.row] cell.configureCell(poke) } return cell } else { return UICollectionViewCell() } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { var poke: Pokemon! if inSearchMode { poke = filteredPokemon[indexPath.row] } else { poke = pokemon[indexPath.row] } performSegue(withIdentifier: "PokemonDetailVC", sender: poke) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if inSearchMode { return filteredPokemon.count } return pokemon.count } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 105, height: 105) } @IBAction func musicBtnPressed(_ sender: UIButton) { if musicPlayer.isPlaying { musicPlayer.pause() sender.alpha = 0.2 } else { musicPlayer.play() sender.alpha = 1.0 } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { view.endEditing(true) } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchBar.text == nil || searchBar.text == "" { inSearchMode = false collection.reloadData() view.endEditing(true) } else { inSearchMode = true let lower = searchBar.text!.lowercased() filteredPokemon = pokemon.filter({ $0.name.range(of: lower) != nil }) //filtered pokemon list is equal to the original pokemon list that is filtered and how we are filtering it is we are taking the $0 (thought of as a placeholder for any and all objects in the original pokemon array) we are saying we are taking the name value of it and saying is what we put in the searchbar contained in that name, if it is we are putting it into the pokemon filtered list. filtering it based on whether search bar text is included in the range of original name. $0 is just a placveholder for the item in that array. after filtering we need what follows. collection.reloadData() //repopulate collection view witht the data. } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "PokemonDetailVC" { if let detailsVC = segue.destination as? PokemonDetailVC { if let poke = sender as? Pokemon { detailsVC.pokemon = poke } //prepare for segue, and sending anyobject. If the segue indentifier is equal to PokemonDetailVC then we are going to create a variable for detailsVC and the destination is PokemonDetailVC. we are going to create poke which is the sender and is of type Pokemon. then we use detailsVC, which we defined as the destination ViewController and this is the variable we create in the PokemonDetailVC. we are saying the detailsVC that contains the variable pokemon we are setting it to this viewControllers poke, which is created above. } } } }
0c00482ecb159635b23bf55abd12dbc72488e26d
[ "Swift" ]
1
Swift
gsrppaladin/pokedex3
906b6086ef31200d2e6168a075c23836ba9f3d1d
c9fe6b97bf6f2369c777808f06ba90fb6affe12b
refs/heads/master
<repo_name>nuvanda/example-rails-challenge<file_sep>/app/controllers/charges_controller.rb class ChargesController < ApplicationController def index @successfull_charges = Charge.successfull @failed_charges = Charge.failed @disputed_charges = Charge.disputed end end
e1cd16988de7e4f1fc88ceb64bb6335f9534d532
[ "Ruby" ]
1
Ruby
nuvanda/example-rails-challenge
0863843c7b6b0787ec61fb94b8e34bc79ef0f319
e4a5f78cc7eea100e88e4825fcf0e24ed26f6232
refs/heads/master
<repo_name>jhemyson/estudo-react<file_sep>/src/pages/Repository/index.js import React from 'react' export default function Respository(){ return ( <h1>Respository</h1> ) }
f10e8c83e85cfcdc34e487d91439c4e3c5a4b364
[ "JavaScript" ]
1
JavaScript
jhemyson/estudo-react
bc4bbbb2bc0fde5f4c10ae9916a1528b6e97cc79
12a275244f8bce44f13b53a8f857d898ba8321f4
refs/heads/master
<file_sep>package utils; import static org.junit.Assert.*; import org.junit.Test; public class CalculadoraTests { @Test public void testSuma() { int resultado = CalculadoraClass.suma(2,3); int esperado = 5; assertEquals(esperado, resultado); } @Test public void testResta() { int resultado = CalculadoraClass.resta(2,3); int esperado = 5; assertEquals(esperado, resultado); } } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>MyFirstApp</groupId> <artifactId>MyFirstApp</artifactId> <version>0.0.1</version> <packaging>war</packaging> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.3</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.0</version> <dependencies> <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-junit4</artifactId> <version>2.22.0</version> </dependency> </dependencies> <configuration> <includes> <include>**/*.java</include> </includes> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.7.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-project-info-reports-plugin</artifactId> <version>3.0.0</version> </plugin> </plugins> </build> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-report-plugin</artifactId> <version>2.22.0</version> </plugin> </plugins> </reporting> </project>
a90be9f7eadfc3cdb068d233064225dad80d5ed5
[ "Java", "Maven POM" ]
2
Java
camiladevops/ProjectDemo
df0cc2acc949550671ccb2d0f81c8eeeb76a0d15
041bf1421d05ef65b11d78c316f57bd7acd395e4
refs/heads/master
<file_sep>import { Body, Controller, Get, HttpCode, HttpStatus, Post, Query, UseGuards } from '@nestjs/common'; import { ApiBearerAuth, ApiOkResponse, ApiTags } from '@nestjs/swagger'; import { AuthUser } from '@/shared/decorators/auth-user.decorator'; import { AuthGuard } from '@/shared/guards/auth.guard'; import { UserDto } from '../user/dto/UserDto'; import { UserEntity } from '../user/user.entity'; import { AuthService } from './auth.service'; import { LoginPayloadDto } from './dto/LoginPayloadDto'; import { UserLoginDto } from './dto/UserLoginDto'; import { OtpService } from '@/modules/otp/otp.service'; import { VerifyOtpDto } from '@/modules/otp/dto/VerifyOtp.dto'; import { UserService } from '@/modules/user/user.service'; import { UserLoginProvider } from '@/shared/enums/user-login-provider'; import { UserRoleType } from '@/shared/enums/user-role-type'; import { UserRegisterDto } from '@/modules/auth/dto/UserRegisterDto'; @Controller('auth') @ApiTags('auth') export class AuthController { constructor( private readonly authService: AuthService, private readonly userService: UserService, private readonly otpService: OtpService, ) { } @Post('login') @HttpCode(HttpStatus.OK) @ApiOkResponse({ type: LoginPayloadDto, description: 'User info with access token', }) async userLogin( @Body() userLoginDto: UserLoginDto, ): Promise<LoginPayloadDto> { const userEntity = await this.authService.validateUser(userLoginDto); const token = await this.authService.createToken(userEntity); return new LoginPayloadDto(userEntity.toDto(), token); } @Post('register') @HttpCode(HttpStatus.OK) @ApiOkResponse({ type: UserDto, description: 'Successfully Registered' }) async userRegister( @Body() userRegisterDto: UserRegisterDto, ): Promise<UserDto> { const createdUser = await this.userService.createUser( userRegisterDto, ); return createdUser.toDto(); } @Post('verify-email') @HttpCode(HttpStatus.OK) @ApiOkResponse({ type: Object, description: 'User Provider', }) async verifyEmail( @Body() userLoginDto: UserLoginDto, ): Promise<{ provider: UserLoginProvider, role: UserRoleType }> { const userEntity = await this.authService.validateUserEmail(userLoginDto); // if otp is provider than send an otp if (userEntity.provider === UserLoginProvider.Otp) { await this.otpService.sendOtp(userLoginDto.email); } return { provider: userEntity.provider, role: userEntity.role }; } @Post('verify-otp') async verifyOtp( @Body() verifyOtpDto: VerifyOtpDto, ): Promise<LoginPayloadDto> { // verify otp const user = await this.authService.validateUserByOtp(verifyOtpDto); // create token const token = await this.authService.createToken(user); return new LoginPayloadDto(user.toDto(), token); } @Get('resend-otp') async resendOtp( @Query('email') email: string, ): Promise<{ message: string }> { await this.otpService.sendOtp(email); return { message: 'Otp Sent Successfully' }; } @Get('me') @HttpCode(HttpStatus.OK) @UseGuards(AuthGuard) @ApiBearerAuth() @ApiOkResponse({ type: UserDto, description: 'current user info' }) async getCurrentUser(@AuthUser() user: UserEntity): Promise<UserDto> { return user.toDto(); } } <file_sep>## Environment 1. Replace **.sample.env** with **.dev.env** or if you are running production build than with **.prod.env** ## Installation ```bash $ yarn | npm install ``` ## Running the app ```bash # development $ yarn start | npm run start # watch mode $ yarn start:dev | npm run start:dev # production mode $ yarn start:prod | npm run start:prod ``` ## Test ```bash # unit tests $ yarn test | npm run test # e2e tests $ yarn test:e2e | npm run test:e2e # test coverage $ yarn test:cov | npm run test:cov ``` ## Document 1. ```yarn start | npm run start``` 2. <a href="http://localhost:3000/documentation">localhost:3000/documentation</a> <file_sep>import { BadRequestException, Injectable, InternalServerErrorException } from '@nestjs/common'; import { AbstractService } from '@/shared/services/abstract.service'; import { OtpRepository } from '@/modules/otp/otp.repository'; import { OtpEntity } from '@/modules/otp/otp.entity'; import { EntityManager } from 'typeorm'; import { UtilsService } from '@/shared/utils/utils.service'; import { VerifyOtpDto } from '@/modules/otp/dto/VerifyOtp.dto'; import { MailerService } from '@nestjs-modules/mailer'; import { ConfigService } from '@/shared/services/config.service'; @Injectable() export class OtpService extends AbstractService<OtpRepository, OtpEntity> { constructor( protected readonly otpRepository: OtpRepository, private readonly configService: ConfigService, // private readonly mailService: MailerService, ) { super(otpRepository); } /** * get latest otp * returns latest otp for an email id * @param {string} email * @return {Promise<OtpEntity[]>} */ async getLatestOtpByEmail(email: string): Promise<OtpEntity> { return this.findOne({ where: { email, isExpired: false, }, order: { createdAt: 'DESC', }, }); } /** * send otp * resends new otp * @param email * @return {Promise<OtpEntity>} */ async sendOtp(email: string): Promise<OtpEntity> { return this.withTransaction(async (manager: EntityManager) => { return this.createOtp(email); }); } /** * resend otp * resends new otp * @param email * @return {Promise<OtpEntity>} */ async resendOtp(email: string): Promise<OtpEntity> { return this.withTransaction(async (manager: EntityManager) => { // expire all existing opts await this.expireExistingRequests(email); return this.createOtp(email); }); } /** * expire existing otp * expires existing otp request for email id * @param email */ async expireExistingRequests(email: string) { return this.updateMultiple({ email }, { isExpired: true }); } /** * verify otp * verifies an otp by checking email * @param {VerifyOtpDto} dto * @returns {Promise<boolean>} */ async verifyOtp(dto: VerifyOtpDto): Promise<OtpEntity> { const otpDetails = await this.findOne({ email: dto.email, otp: dto.otp, isExpired: false, isApproved: false }); if (!otpDetails) { throw new BadRequestException('Invalid otp'); } // update otp request and mark it as approved await this.updateById(otpDetails.id, { isApproved: true, isExpired: true }); return otpDetails; } /** * create otp * creates new otp * @param email * @return {Promise<OtpEntity>} */ private async createOtp(email: string): Promise<OtpEntity> { const otpModel = new OtpEntity(); otpModel.email = email; otpModel.otp = UtilsService.generateRandomCode(); const otpEntity = await this.createRecord(otpModel); if (!otpEntity) { throw new InternalServerErrorException(); } // this.mailService.sendMail({ // to: email, // subject: 'One time password', // template: 'send-otp', // context: { // code: otpModel.otp, // }, // }); return otpEntity; } } <file_sep>import { IsEmail, IsNotEmpty, IsNumber } from 'class-validator'; import { Transform } from 'class-transformer'; export class VerifyOtpDto { @IsNotEmpty() @Transform(val => parseInt(val)) @IsNumber() otp: number; @IsNotEmpty() @IsEmail() email: string; } <file_sep>import { OtpEntity } from '../otp.entity'; import { AbstractDto } from '@/shared/dto/AbstractDto'; export class OtpDto extends AbstractDto { constructor(otp: OtpEntity) { super(otp); } } <file_sep>'use strict'; import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; import { IsEmail, IsIn, IsNotEmpty, IsOptional, IsString } from 'class-validator'; import { UserRoleType } from '@/shared/enums/user-role-type'; export class UserCreateDto { @IsString() @IsNotEmpty() @ApiProperty() firstName: string; @IsString() @IsNotEmpty() @ApiProperty() lastName: string; @IsString() @IsEmail() @IsNotEmpty() @ApiProperty() email: string; @IsOptional() @IsString() @ApiPropertyOptional() contactNo?: string; @ApiProperty({ enum: UserRoleType, enumName: 'RoleType' }) @IsIn(Object.values(UserRoleType)) role?: UserRoleType; } <file_sep>import { Module } from '@nestjs/common'; import { OtpService } from './otp.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import { OtpRepository } from '@/modules/otp/otp.repository'; @Module({ imports: [ TypeOrmModule.forFeature([OtpRepository]), ], providers: [OtpService], exports: [OtpService], }) export class OtpModule { } <file_sep>import { AbstractDto } from '@/shared/dto/AbstractDto'; import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; import { UserDto } from '@/modules/user/dto/UserDto'; import { BookEntity } from '@/modules/book/book.entity'; export class BookDto extends AbstractDto { @ApiProperty() name: string; @ApiProperty({ type: () => UserDto }) author: UserDto; @ApiPropertyOptional({ type: () => UserDto }) createdBy: UserDto; @ApiPropertyOptional({ type: () => UserDto }) modifiedBy: UserDto; constructor(params: BookEntity) { super(params); if (params) { this.name = params.name; if (params.author) { this.author = params.author.toDto(); } if (params.createdBy) { this.createdBy = params.createdBy.toDto(); } if (params.modifiedBy) { this.modifiedBy = params.modifiedBy.toDto(); } } } } <file_sep>import { ClassSerializerInterceptor, ValidationPipe } from '@nestjs/common'; import { NestFactory, Reflector } from '@nestjs/core'; import { NestExpressApplication } from '@nestjs/platform-express'; import * as helmet from 'helmet'; import * as morgan from 'morgan'; import { AppModule } from '@/app.module'; import { ConfigService } from '@/shared/services/config.service'; import { SharedModule } from '@/shared/shared.module'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; declare const module: any; async function bootstrap(): Promise<void> { const app = await NestFactory.create<NestExpressApplication>(AppModule, { cors: true, bodyParser: true, }); app.use(helmet()); app.use(morgan('combined')); const reflector = app.get(Reflector); app.useGlobalInterceptors(new ClassSerializerInterceptor(reflector)); app.useGlobalPipes( new ValidationPipe({ whitelist: true, transform: true, }), ); const configService = app.select(SharedModule).get(ConfigService); if (['dev'].includes(configService.nodeEnv)) { const options = new DocumentBuilder() .setTitle('API') .setVersion('0.0.1') .addBearerAuth() .build(); const document = SwaggerModule.createDocument(app, options); SwaggerModule.setup('documentation', app, document); } const port = configService.getNumber('PORT'); await app.listen(port); console.info(`server running on port ${port}`); if (module.hot) { module.hot.accept(); module.hot.dispose(() => app.close()); } } void bootstrap(); <file_sep>import { Injectable } from '@nestjs/common'; import { EntityManager, FindConditions, FindOneOptions, UpdateResult } from 'typeorm'; import { UsersPageDto } from './dto/UsersPageDto'; import { UsersPageOptionsDto } from './dto/UsersPageOptionsDto'; import { UserEntity } from './user.entity'; import { UserRepository } from './user.repository'; import { AbstractService } from '@/shared/services/abstract.service'; import { UserCreateDto } from '@/modules/user/dto/UserCreateDto'; @Injectable() export class UserService extends AbstractService<UserRepository, UserEntity> { constructor( protected readonly userRepository: UserRepository, ) { super(userRepository); } async findByUsernameOrEmail( options: Partial<{ username: string; email: string }>, ): Promise<UserEntity | undefined> { const query: FindConditions<UserEntity> = {}; const queryBuilder = this.createQueryBuilder('user'); if (options.email) { queryBuilder.orWhere('user.email = :email', { email: options.email, }); } if (options.username) { queryBuilder.orWhere('user.username = :username', { username: options.username, }); } return queryBuilder.getOne(); } async findUserById(id: number | string, options?: FindOneOptions<UserEntity>) { return this.findById(id, options ); } async createUser( userCreateDto: UserCreateDto, ): Promise<UserEntity> { return this.withTransaction(async (manager: EntityManager) => { // create user object const user = { ...new UserEntity(), ...userCreateDto }; // create record return await this.createRecord(user); }); } async getUsers(pageOptionsDto: UsersPageOptionsDto): Promise<UsersPageDto> { const queryBuilder = this.userRepository.createQueryBuilder('user'); const { items, pageMetaDto } = await this.getAllPaginated(queryBuilder, pageOptionsDto); return new UsersPageDto(items.toDtos(), pageMetaDto); } /** * update user by id * @param {string | number} id * @param {Partial<UserEntity>} user * @returns {Promise<UpdateResult>} */ updateUserById(id: string | number, user: Partial<UserEntity>): Promise<UpdateResult> { return this.updateById(id, user); } } <file_sep>'use strict'; import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; import { UserRoleType } from '@/shared/enums/user-role-type'; import { AbstractDto } from '@/shared/dto/AbstractDto'; import { UserEntity } from '../user.entity'; import { UserLoginProvider } from '@/shared/enums/user-login-provider'; export class UserDto extends AbstractDto { @ApiProperty() firstName: string; @ApiProperty() lastName: string; @ApiPropertyOptional() contactNo: string; @ApiProperty({ enum: UserRoleType }) role: UserRoleType; @ApiProperty({ enum: UserLoginProvider }) provider: UserLoginProvider; @ApiProperty() email: string; @ApiPropertyOptional() profileUrl: string; @ApiProperty() receivePushNotification: boolean; @ApiPropertyOptional() lastLogin: Date; @ApiProperty() receiveTextMessageNotification: boolean; @ApiProperty() isAdmin: boolean; @ApiPropertyOptional() meta: any; @ApiPropertyOptional({ type: () => UserDto }) createdBy: UserDto; @ApiPropertyOptional({ type: () => UserDto }) modifiedBy: UserDto; constructor(user: UserEntity) { super(user); this.firstName = user.firstName; this.lastName = user.lastName; this.role = user.role; this.provider = user.provider; this.email = user.email; this.contactNo = user.contactNo; this.lastLogin = user.lastLogin; this.profileUrl = user.profileUrl; if (user.createdBy) { this.createdBy = user.createdBy.toDto(); } if (user.modifiedBy) { this.createdBy = user.modifiedBy.toDto(); } } } <file_sep>import { BadRequestException, Injectable } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { UtilsService } from '@/shared/utils/utils.service'; import { ConfigService } from '@/shared/services/config.service'; import { UserDto } from '../user/dto/UserDto'; import { UserEntity } from '../user/user.entity'; import { UserService } from '../user/user.service'; import { TokenPayloadDto } from './dto/TokenPayloadDto'; import { UserLoginDto } from './dto/UserLoginDto'; import { VerifyOtpDto } from '@/modules/otp/dto/VerifyOtp.dto'; import { AbstractService } from '@/shared/services/abstract.service'; import { OtpService } from '@/modules/otp/otp.service'; import { UserNotFoundException } from '@/shared/exceptions/user-not-found.exception'; @Injectable() export class AuthService extends AbstractService<null, null> { constructor( private readonly jwtService: JwtService, private readonly configService: ConfigService, private readonly userService: UserService, private readonly otpService: OtpService, ) { super(null); } /** * create jwt token * creates new jwt token using user's id and user's client id * @param {UserEntity | UserDto} user * @returns {Promise<TokenPayloadDto>} */ async createToken(user: UserEntity | UserDto): Promise<TokenPayloadDto> { return new TokenPayloadDto({ expiresIn: this.configService.getNumber('JWT_EXPIRATION_TIME'), accessToken: await this.jwtService.signAsync({ id: user.id }), }); } /** * validate user by email and password * @param userLoginDto */ async validateUser(userLoginDto: UserLoginDto): Promise<UserEntity> { await this.withTransaction(async () => { const user = await this.userService.findOne({ email: userLoginDto.email, }); const isPasswordValid = await UtilsService.validateHash( userLoginDto.password, user && user.password, ); if (!user || !isPasswordValid) { throw new UserNotFoundException(); } return user; }); // get updated user return await this.userService.findByUsernameOrEmail({ email: userLoginDto.email, }); } /** * validates user email * @param {UserLoginDto} userLoginDto * @returns {Promise<UserEntity>} */ async validateUserEmail(userLoginDto: UserLoginDto): Promise<UserEntity> { const user = await this.userService.findByUsernameOrEmail({ email: userLoginDto.email, }); if (!user) { throw new BadRequestException('This email is not registered with us'); } return user; } /** * validate user by otp * first checks is valid otp * than check user already have account than use that account to create token * if user don't have an account than creates a new account * @param dto */ async validateUserByOtp(dto: VerifyOtpDto): Promise<UserEntity> { await this.withTransaction(async () => { // verify otp await this.otpService.verifyOtp(dto); // expire all other pending otp await this.otpService.expireExistingRequests(dto.email); // get user by email const user = await this.userService.findByUsernameOrEmail({ email: dto.email, }); if (!user) { throw new UserNotFoundException(); } // update users last login await this.userService.updateUserById(user.id, { lastLogin: UtilsService.generateUtcDate() }); }); // get updated user return await this.userService.findByUsernameOrEmail({ email: dto.email, }); } } <file_sep>import { Repository } from 'typeorm'; import { EntityRepository } from 'typeorm/decorator/EntityRepository'; import { BookEntity } from '@/modules/book/book.entity'; @EntityRepository(BookEntity) export class BookRepository extends Repository<BookEntity> { } <file_sep>import { IsInt, IsNotEmpty, IsString, Min } from 'class-validator'; import { Transform } from 'class-transformer'; import { ApiProperty } from '@nestjs/swagger'; export class GetBookDto { @ApiProperty() @IsNotEmpty() @IsString() bookId: string; } <file_sep>import { AbstractEntity } from '@/shared/entity/abstract.entity'; import { BookDto } from '@/modules/book/dto/BookDto'; import { Column, Entity, ManyToOne } from 'typeorm'; import { UserEntity } from '@/modules/user/user.entity'; @Entity({ name: 'books' }) export class BookEntity extends AbstractEntity<BookDto> { @Column() name: string; @ManyToOne(type => UserEntity, { eager: false, }) createdBy: UserEntity; @ManyToOne(type => UserEntity, { eager: false, }) modifiedBy: UserEntity; @ManyToOne(type => UserEntity, { eager: false, }) author: UserEntity; dtoClass = BookDto; } <file_sep>export class FileModel { fieldname: string; originalname: string; encoding: string; mimetype: string; size: string; storageUrl?: string; } <file_sep>import { Injectable } from '@nestjs/common'; import { AbstractService } from '@/shared/services/abstract.service'; import { BookEntity } from '@/modules/book/book.entity'; import { BookRepository } from '@/modules/book/book.repository'; import { EntityManager, FindOneOptions, UpdateResult } from 'typeorm'; import { UsersPageOptionsDto } from '@/modules/user/dto/UsersPageOptionsDto'; import { BooksPageDto } from '@/modules/book/dto/BooksPageDto'; import { BookCreateDto } from '@/modules/book/dto/BookCreateDto'; import { UserEntity } from '@/modules/user/user.entity'; import { UserService } from '@/modules/user/user.service'; import { UserNotFoundException } from '@/shared/exceptions/user-not-found.exception'; import { UtilsService } from '@/shared/utils/utils.service'; @Injectable() export class BookService extends AbstractService<BookRepository, BookEntity> { constructor( protected readonly bookRepository: BookRepository, private userService: UserService, ) { super(bookRepository); } /** * finds book by id * @param id * @param options */ async getBookById(id: number | string, options?: FindOneOptions<BookEntity>) { return this.findById(id, options); } /** * create new book * @param dto * @param loggedInUser */ async createBook( dto: BookCreateDto, loggedInUser: UserEntity, ): Promise<BookEntity> { return this.withTransaction(async (manager: EntityManager) => { const author = await this.userService.findUserById(dto.authorId); if (!author) { throw new UserNotFoundException('author not found'); } // create book object const book = new BookEntity(); book.name = dto.name; book.createdBy = loggedInUser; book.author = author; // create record return await this.createRecord(book); }); } /** * get all books * @param pageOptionsDto */ async getBooks(pageOptionsDto: UsersPageOptionsDto): Promise<BooksPageDto> { const queryBuilder = this.bookRepository.createQueryBuilder('books'); queryBuilder.where(UtilsService.likeQueryHelper('name', pageOptionsDto.query)); const { items, pageMetaDto } = await this.getAllPaginated(queryBuilder, pageOptionsDto); return new BooksPageDto(items.toDtos(), pageMetaDto); } /** * update book by id * @param {string | number} id * @param {Partial<BookEntity>} book * @param loggedInUser * @returns {Promise<UpdateResult>} */ updateBookById(id: string | number, book: Partial<BookEntity>, loggedInUser: UserEntity): Promise<UpdateResult> { return this.updateById(id, book); } /** * delete book * @param id */ async deleteBook(id: number | string): Promise<string> { await this.deleteById(id); return 'Book Deleted Successfully'; } /** * delete book * @param id */ async restoreBook(id: number | string): Promise<string> { await this.restoreById(id); return 'Book Restored Successfully'; } } <file_sep>import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common'; import { HttpExceptionFilter } from '@/shared/filters/bad-request.filter'; import { QueryFailedFilter } from '@/shared/filters/query-failed.filter'; import { Response } from 'express'; import { STATUS_CODES } from 'http'; import { WINSTON_MODULE_PROVIDER } from 'nest-winston'; import { Logger } from 'winston'; import { QueryFailedError } from 'typeorm'; import { ErrorResponseModel } from '@/shared/models/error-response.model'; import { APP_INTERNAL_SERVER_ERROR } from '@/shared/constants/app.constant'; @Catch() @Injectable() export class GenericExceptionFilter implements ExceptionFilter { constructor(@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger) { } catch(exception: any, host: ArgumentsHost): any { this.logger.error(exception, [{ stack: exception }]); if (exception instanceof HttpException) { new HttpExceptionFilter().catch(exception, host); } else if (exception instanceof QueryFailedError) { new QueryFailedFilter().catch(exception, host); } else { const ctx = host.switchToHttp(); const response = ctx.getResponse<Response>(); const errorResponse = new ErrorResponseModel(); errorResponse.statusCode = HttpStatus.INTERNAL_SERVER_ERROR; if (exception instanceof Error) { errorResponse.message = APP_INTERNAL_SERVER_ERROR; } else { errorResponse.statusCode = exception.getStatus(); errorResponse.message = exception.message; } errorResponse.error = STATUS_CODES[errorResponse.statusCode]; response.status(errorResponse.statusCode).json(errorResponse); } } } <file_sep>import { EntitySubscriberInterface, EventSubscriber, InsertEvent, UpdateEvent } from 'typeorm'; import { UserEntity } from '@/modules/user/user.entity'; import { UtilsService } from '@/shared/utils/utils.service'; @EventSubscriber() export class UserSubscriber implements EntitySubscriberInterface<UserEntity> { listenTo() { return UserEntity; } beforeInsert(event: InsertEvent<UserEntity>) { if (event.entity.password) { event.entity.password = <PASSWORD>Service.<PASSWORD>Hash( event.entity.password, ); } } beforeUpdate(event: UpdateEvent<UserEntity>) { if (event.entity.password !== event.databaseEntity.password) { event.entity.password = <PASSWORD>Service.<PASSWORD>( event.entity.password, ); } } } <file_sep>require('./src/boilerplate.polyfill'); const dotenv = require('dotenv'); const SnakeNamingStrategy = require('./src/snake-naming.strategy'); if (!(module).hot /* for webpack HMR */) { process.env.NODE_ENV = process.env.NODE_ENV || 'dev'; } dotenv.config({ path: `.${process.env.NODE_ENV}.env`, }); // Replace \\n with \n to support multiline strings in AWS for (const envName of Object.keys(process.env)) { process.env[envName] = process.env[envName].replace(/\\n/g, '\n'); } module.exports = { type: 'mysql', host: process.env.DB_HOST, port: +process.env.DB_PORT, username: process.env.DB_USERNAME, password: <PASSWORD>, database: process.env.DB_DATABASE, namingStrategy: new SnakeNamingStrategy.SnakeNamingStrategy(), entities: ['src/modules/**/*.entity{.ts,.js}'], migrations: ['src/migrations/*{.ts,.js}'], }; <file_sep>import './boilerplate.polyfill'; import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { I18nJsonParser, I18nModule } from 'nestjs-i18n'; import * as path from 'path'; import { AuthModule } from '@/modules/auth/auth.module'; import { UserModule } from '@/modules/user/user.module'; import { ConfigService } from '@/shared/services/config.service'; import { SharedModule } from '@/shared/shared.module'; import { APP_FILTER } from '@nestjs/core'; import { GenericExceptionFilter } from '@/shared/filters/generic-exception.filter'; import { MailerModule } from '@nestjs-modules/mailer'; import { WinstonModule } from 'nest-winston'; import * as winston from 'winston'; import { BookModule } from '@/modules/book/book.module'; import { OtpModule } from '@/modules/otp/otp.module'; @Module({ imports: [ AuthModule, OtpModule, UserModule, BookModule, TypeOrmModule.forRootAsync({ imports: [SharedModule], useFactory: (configService: ConfigService) => configService.typeOrmConfig, inject: [ConfigService], }), I18nModule.forRootAsync({ useFactory: (configService: ConfigService) => ({ fallbackLanguage: configService.fallbackLanguage, parserOptions: { path: path.join(__dirname, '/i18n/'), watch: configService.isDevelopment, }, }), imports: [SharedModule], parser: I18nJsonParser, inject: [ConfigService], }), // MailerModule.forRootAsync({ // useFactory: (configService: ConfigService) => // configService.nestMailerConfig, // imports: [SharedModule], // inject: [ConfigService], // }), WinstonModule.forRoot({ level: 'error', format: winston.format.combine( winston.format.timestamp({ format: 'DD-MMM-YYYY hh:mm:ss a', }), winston.format.prettyPrint(), winston.format.align(), winston.format.errors({ stack: true }), ), transports: [ // new (winston.transports as any).DailyRotateFile({ // filename: 'error-%DATE%.log', // datePattern: 'DD-MM-YYYY-hh-MM', // maxFiles: '10d', // zippedArchive: true // }), new winston.transports.File({ tailable: true, maxFiles: 2, filename: './error.log', }), ], }), ], providers: [ { provide: APP_FILTER, useClass: GenericExceptionFilter, }, ], }) export class AppModule { } <file_sep>import { SetMetadata } from '@nestjs/common'; import { UserRoleType } from '../enums/user-role-type'; // eslint-disable-next-line @typescript-eslint/naming-convention export const Roles = (...roles: UserRoleType[]) => SetMetadata('roles', roles); <file_sep>import { AbstractEntity } from '@/shared/entity/abstract.entity'; import { OtpDto } from '@/modules/otp/dto/Otp.dto'; import { Column, Entity } from 'typeorm'; @Entity({ name: 'otp-requests' }) export class OtpEntity extends AbstractEntity<OtpDto> { @Column({ unique: false, nullable: false }) email: string; @Column({ nullable: false }) otp: number; @Column({ default: false }) isApproved: boolean; @Column({ default: false }) isExpired: boolean; dtoClass = OtpDto; } <file_sep>import { ApiProperty } from '@nestjs/swagger'; import { PageMetaDto } from '@/shared/dto/PageMetaDto'; import { UserDto } from './UserDto'; export class UsersPageDto { @ApiProperty({ type: UserDto, isArray: true, }) data: UserDto[]; @ApiProperty() meta: PageMetaDto; constructor(data: UserDto[], meta: PageMetaDto) { this.data = data; this.meta = meta; } } <file_sep>export enum UserLoginProvider { Normal = 'Normal', Otp = 'Otp', Google = 'Google', } <file_sep>import { Body, Controller, Get, HttpCode, HttpStatus, NotFoundException, Post, Query, UseGuards } from '@nestjs/common'; import { ApiBearerAuth, ApiOkResponse, ApiResponse, ApiTags } from '@nestjs/swagger'; import { BookDto } from '@/modules/book/dto/BookDto'; import { BookService } from '@/modules/book/book.service'; import { BookCreateDto } from '@/modules/book/dto/BookCreateDto'; import { BooksPageDto } from '@/modules/book/dto/BooksPageDto'; import { BooksPageOptionsDto } from '@/modules/book/dto/BooksPageOptionsDto'; import { DeleteBookDto } from '@/modules/book/dto/DeleteBookDto'; import { GetBookDto } from '@/modules/book/dto/GetBookDto'; import { AuthGuard } from '@/shared/guards/auth.guard'; import { AuthUser } from '@/shared/decorators/auth-user.decorator'; import { UserDto } from '@/modules/user/dto/UserDto'; import { UserEntity } from '@/modules/user/user.entity'; @Controller('book') @ApiTags('books') @UseGuards(AuthGuard) @ApiBearerAuth() export class BookController { constructor(private bookService: BookService) { } @Post('create') @HttpCode(HttpStatus.OK) @ApiOkResponse({ type: BookDto, description: 'Book created successfully', }) async createBook(@Body() dto: BookCreateDto, @AuthUser() user: UserEntity): Promise<BookDto> { // create book const book = await this.bookService.createBook(dto, user); return book.toDto(); } @Get('') @HttpCode(HttpStatus.OK) @ApiResponse({ status: HttpStatus.OK, description: 'Get Book Details', type: BookDto, }) async getBook(@Query() dto: GetBookDto) { const book = await this.bookService.getBookById(dto.bookId, { relations: ['author'] }); if (!book) { throw new NotFoundException('Book not found'); } return book.toDto(); } @Post('get-all') @HttpCode(HttpStatus.OK) @ApiResponse({ status: HttpStatus.OK, description: 'Get All books items', type: BooksPageDto, }) async getBooks(@Body() dto: BooksPageOptionsDto): Promise<BooksPageDto> { return await this.bookService.getBooks(dto); } @Post('delete') @HttpCode(HttpStatus.OK) async deleteBook(@Body() dto: DeleteBookDto) { return await this.bookService.deleteBook(dto.bookId); } } <file_sep>import { ApiProperty } from '@nestjs/swagger'; import { PageMetaDto } from '@/shared/dto/PageMetaDto'; import { BookDto } from './BookDto'; export class BooksPageDto { @ApiProperty({ type: BookDto, isArray: true, }) data: BookDto[]; @ApiProperty() meta: PageMetaDto; constructor(data: BookDto[], meta: PageMetaDto) { this.data = data; this.meta = meta; } } <file_sep>import * as bcrypt from 'bcryptjs'; import * as _ from 'lodash'; import * as moment from 'moment'; import { APP_OTP_EXPIRY } from '@/shared/constants/app.constant'; import { v4 as uuidv4 } from 'uuid'; import { Readable } from 'stream'; export class UtilsService { /** * convert entity to dto class instance * @param {{new(entity: E, options: any): T}} model * @param {E[] | E} entity * @param options * @returns {T[] | T} */ public static toDto<T, E>( model: new (entity: E, options?: any) => T, entity: E, options?: any, ): T; public static toDto<T, E>( model: new (entity: E, options?: any) => T, entity: E[], options?: any, ): T[]; public static toDto<T, E>( model: new (entity: E, options?: any) => T, entity: E | E[], options?: any, ): T | T[] { if (_.isArray(entity)) { return entity.map(u => new model(u, options)); } return new model(entity, options); } /** * generate hash from password or string * @param {string} password * @returns {string} */ static generateHash(password: string): string { return bcrypt.hashSync(password, 10); } /** * generate random string * @param length */ static generateRandomString(length: number): string { return Math.random() .toString(36) .replace(/[^a-zA-Z0-9]+/g, '') .substr(0, length); } /** * validate text with hash * @param {string} password * @param {string} hash * @returns {Promise<boolean>} */ static validateHash(password: string, hash: string): Promise<boolean> { return bcrypt.compare(password, hash || ''); } /** * like query helper * @param {string} columnName * @param {string} keyword * @return {string} */ static likeQueryHelper(columnName: string, keyword: string): string { return `${columnName} LIKE '%${keyword}%'`; } /** * generate utc date * @return date */ static generateUtcDate(): Date { return moment.utc().toDate(); } /** * generate random alphanumeric code up to given digit * @param digit * @returns number */ static generateRandomCode = (digit = 6) => { return Math.floor( Math.pow(10, digit - 1) + Math.random() * (Math.pow(10, digit) - Math.pow(10, digit - 1) - 1), ); }; /** * check whether otp expired or not * @param date * @return boolean */ static isOTPExpired = (date: Date): boolean => { return moment .utc(date) .add(APP_OTP_EXPIRY, 's') .isBefore(moment.utc()); }; /** * generates a unique guid * @example * generateGuid() * @returns {string} */ static generateGuid = (): string => { return uuidv4(); }; /** * get extension name from filename * @example * getExtensionNameFromFileName('file.mp4') * @param {string} fileName * @returns {string} */ static getExtensionNameFromFileName = (fileName: string): string => { return fileName.substr(fileName.lastIndexOf('.') + 1); }; /** * generate fileName * generates a new file name from given original file name * @param {string} originalFileName * @returns {string} */ static generateFileName = (originalFileName: string): string => { return `${UtilsService.generateGuid()}.${UtilsService.getExtensionNameFromFileName(originalFileName)}`; }; /** * get File cdn url from Azure storage url */ static getFileCdnUrl = (fileUrl: string, azureCdnUrl: string, azureContainer: string): string => { const fileName = fileUrl.substr(fileUrl.lastIndexOf('/') + 1); return `${azureCdnUrl}${azureContainer}/${fileName}`; }; /** * Convert a buffer to a stream * * @param buffer Buffer * @returns Readable */ static bufferToStream = (buffer) => { return new Readable({ read() { this.push(buffer); this.push(null); } }); } } <file_sep>// app date format export const APP_DATE_FORMAT = 'DD-MM-YYYY'; // app decimal places export const APP_DECIMAL_PLACES = 2; // app otp expiry in seconds export const APP_OTP_EXPIRY = 86400 // 24; // app Internal server error message export const APP_INTERNAL_SERVER_ERROR = 'Looks like something went wrong!'; <file_sep>import { TypeOrmModuleOptions } from '@nestjs/typeorm'; import * as dotenv from 'dotenv'; import * as path from 'path'; import { SnakeNamingStrategy } from '@/snake-naming.strategy'; import { UserSubscriber } from '@/shared/entity-subscribers/user-subscriber'; import { MailerOptions } from '@nestjs-modules/mailer'; import { EjsAdapter } from '@nestjs-modules/mailer/dist/adapters/ejs.adapter'; export class ConfigService { constructor() { const nodeEnv = this.nodeEnv; dotenv.config({ path: `.${nodeEnv}.env`, }); // Replace \\n with \n to support multiline strings in AWS for (const envName of Object.keys(process.env)) { process.env[envName] = process.env[envName].replace(/\\n/g, '\n'); } } /** * check if environment is development * @return {boolean} */ get isDevelopment(): boolean { return this.nodeEnv === 'dev'; } /** * check if environment is production * @return {boolean} */ get isProduction(): boolean { return this.nodeEnv === 'prod'; } public get(key: string): string { return process.env[key]; } public getNumber(key: string): number { return Number(this.get(key)); } /** * get running node env * @return {string} */ get nodeEnv(): string { return this.get('NODE_ENV') || 'dev'; } /** * get fallback language for i18n * @return {string} */ get fallbackLanguage(): string { return this.get('FALLBACK_LANGUAGE').toLowerCase(); } /** * get typeorm config * @return {TypeOrmModuleOptions} */ get typeOrmConfig(): TypeOrmModuleOptions { let entities = [__dirname + '/../../modules/**/*.entity{.ts,.js}']; let migrations = [__dirname + '/../../migrations/*{.ts,.js}']; if ((module as any).hot) { const entityContext = (require as any).context( './../../modules', true, /\.entity\.ts$/, ); entities = entityContext.keys().map((id) => { const entityModule = entityContext(id); const [entity] = Object.values(entityModule); return entity; }); const migrationContext = (require as any).context( './../../migrations', false, /\.ts$/, ); migrations = migrationContext.keys().map((id) => { const migrationModule = migrationContext(id); const [migration] = Object.values(migrationModule); return migration; }); } return { entities, migrations, keepConnectionAlive: true, type: 'mysql', host: this.get('DB_HOST'), port: this.getNumber('DB_PORT'), username: this.get('DB_USERNAME'), password: <PASSWORD>('<PASSWORD>'), database: this.get('DB_DATABASE'), subscribers: [UserSubscriber], migrationsRun: true, logging: this.isDevelopment, namingStrategy: new SnakeNamingStrategy(), // maxQueryExecutionTime: }; } /** * get nest mailer config * @return {MailerOptions} */ get nestMailerConfig(): MailerOptions { return { defaults: { from: this.get('EMAIL_FROM'), }, template: { dir: path.join(__dirname, '..', '..', 'email-templates'), adapter: new EjsAdapter(), options: { strict: true, }, }, transport: { host: this.get('EMAIL_HOST'), port: this.get('EMAIL_PORT'), secure: true, // upgrade later with STARTTLS auth: { user: this.get('EMAIL_USERNAME'), pass: <PASSWORD>('<PASSWORD>'), }, }, }; } /** * get azure storage url * @returns {string} */ get azureStorageUrl(): string { return this.get('AZURE_STORAGE_URL'); } /** * get azure cdn url * @returns {string} */ get azureCdnUrl(): string { return this.get('AZURE_CDN_URL'); } /** * get azure cdn url * @returns {string} */ get azureContainerName(): string { return this.get('AZURE_STORAGE_CONTAINER'); } } <file_sep>'use strict'; import { Body, Controller, Get, HttpCode, HttpStatus, Post, Query, UseGuards, ValidationPipe } from '@nestjs/common'; import { ApiBearerAuth, ApiResponse, ApiTags } from '@nestjs/swagger'; import { I18nService } from 'nestjs-i18n'; import { AuthGuard } from '@/shared/guards/auth.guard'; import { UsersPageDto } from './dto/UsersPageDto'; import { UsersPageOptionsDto } from './dto/UsersPageOptionsDto'; import { UserService } from './user.service'; import { UserDto } from '@/modules/user/dto/UserDto'; import { UserCreateDto } from '@/modules/user/dto/UserCreateDto'; @Controller('users') @ApiTags('users') @UseGuards(AuthGuard) @ApiBearerAuth() export class UserController { constructor( private _userService: UserService, private readonly _i18n: I18nService, ) { } @Get('users') @HttpCode(HttpStatus.OK) @ApiResponse({ status: HttpStatus.OK, description: 'Get users list', type: UsersPageDto, }) getUsers( @Query(new ValidationPipe({ transform: true })) pageOptionsDto: UsersPageOptionsDto, ): Promise<UsersPageDto> { return this._userService.getUsers(pageOptionsDto); } @Post() @HttpCode(HttpStatus.OK) @ApiResponse({ status: HttpStatus.OK, description: 'Create User', type: UserDto, }) async createUser(@Body() dto: UserCreateDto): Promise<UserDto> { const user = await this._userService.createUser(dto); return user.toDto(); } } <file_sep>import { ClassSerializerInterceptor, ValidationPipe } from '@nestjs/common'; import { NestFactory, Reflector } from '@nestjs/core'; import { ExpressAdapter, NestExpressApplication } from '@nestjs/platform-express'; import * as helmet from 'helmet'; import { initializeTransactionalContext, patchTypeORMRepositoryWithBaseRepository, } from 'typeorm-transactional-cls-hooked'; import { AppModule } from '@/app.module'; import { ConfigService } from '@/shared/services/config.service'; import { SharedModule } from '@/shared/shared.module'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; async function bootstrap() { initializeTransactionalContext(); patchTypeORMRepositoryWithBaseRepository(); const app = await NestFactory.create<NestExpressApplication>( AppModule, new ExpressAdapter(), { cors: true, }, ); app.use(helmet()); const reflector = app.get(Reflector); app.useGlobalInterceptors(new ClassSerializerInterceptor(reflector)); app.useGlobalPipes( new ValidationPipe({ whitelist: true, transform: true, }), ); const configService = app.select(SharedModule).get(ConfigService); if (['dev'].includes(configService.nodeEnv)) { const options = new DocumentBuilder() .setTitle('API') .setVersion('0.0.2') .addBearerAuth() .build(); const document = SwaggerModule.createDocument(app, options); SwaggerModule.setup('documentation', app, document); } const port = configService.getNumber('PORT'); await app.listen(port); console.info(`server running on port ${port}`); } void bootstrap(); <file_sep>import { Column, Entity, ManyToOne, OneToMany } from 'typeorm'; import { AbstractEntity } from '@/shared/entity/abstract.entity'; import { UserRoleType } from '@/shared/enums/user-role-type'; import { UserDto } from './dto/UserDto'; import { UserLoginProvider } from '@/shared/enums/user-login-provider'; @Entity({ name: 'users' }) export class UserEntity extends AbstractEntity<UserDto> { @Column({ nullable: false }) firstName: string; @Column({ nullable: false }) lastName: string; @Column({ nullable: true }) password: string; @Column({ nullable: true }) contactNo: string; @Column({ unique: true, nullable: false }) email: string; @Column({ type: 'enum', enum: UserLoginProvider, default: UserLoginProvider.Normal }) provider: UserLoginProvider; @Column({ type: 'enum', enum: UserRoleType, default: UserRoleType.User }) role: UserRoleType; @Column({ nullable: true }) profileUrl: string; @Column({ type: 'timestamp', nullable: true }) lastLogin: Date; @ManyToOne(type => UserEntity) createdBy: UserEntity; @ManyToOne(type => UserEntity) modifiedBy: UserEntity; dtoClass = UserDto; } <file_sep>import { EntityManager, FindConditions, getConnection, Repository, SelectQueryBuilder, UpdateResult } from 'typeorm'; import { PageOptionsDto } from '@/shared/dto/PageOptionsDto'; import { PageMetaDto } from '@/shared/dto/PageMetaDto'; import { FindOneOptions } from 'typeorm'; import { FindManyOptions } from 'typeorm/find-options/FindManyOptions'; export class AbstractService<TRepository extends Repository<Entity>, Entity> { constructor(protected readonly repository: TRepository) { } /** * find record by id * @param {number | string} id * @param {FindOneOptions<Entity>} options * @return {any} */ findById(id: number | string, options?: FindOneOptions<Entity>) { if (options) { return this.repository.findOne(id, options); } else { return this.repository.findOne(id); } } /** * find record or create a record * @param {<Entity>} criteria * @param {Partial<Entity>} record * @return {Promise<[Entity, boolean]>} */ async findOrCreate( criteria: FindConditions<Entity>, record: Partial<Entity>, ): Promise<[Entity, boolean]> { const existing = await this.repository.findOne(criteria); if (existing) { return [existing, false]; } const newEntry = await this.createRecord(record); return [newEntry, true]; } findOne(options?: FindOneOptions<Entity> | FindConditions<Entity>): Promise<Entity> { return this.repository.findOne(options); } find(options?: FindManyOptions<Entity> | FindConditions<Entity>): Promise<Entity[]> { return this.repository.find(options); } /** * get all paginated data * @param {<Entity>} queryBuilder * @param {PageOptionsDto} pageOptionsDto * @return {Promise<{pageMetaDto: PageMetaDto, items: any[]}>} */ async getAllPaginated(queryBuilder: SelectQueryBuilder<Entity>, pageOptionsDto: PageOptionsDto) { const [items, itemsCount] = await queryBuilder .skip(pageOptionsDto.skip) .take(pageOptionsDto.take) .getManyAndCount(); const pageMetaDto = new PageMetaDto({ pageOptionsDto, itemCount: itemsCount, }); return { items, pageMetaDto }; } /** * create new record * @param {Partial<Entity>} record * @return {any} */ createRecord(record: Partial<Entity>) { const doc = this.repository.create(record as Entity); return this.repository.save(doc); } /** * create multiple records * @param {Partial<Entity[]>} records * @return {any} */ createMultipleRecords(records: Partial<Entity[]>) { const docs = this.repository.create(records as Entity[]); return this.repository.save(docs); } /** * update record by id * @param {number | string} id * @param {Partial<Entity>} record * @return {any} */ updateById(id: number | string, record: Partial<Entity>): Promise<UpdateResult> { return this.repository.update(id, record as Entity); } /** * update multiple records * @param {<Entity>} criteria * @param {Partial<Entity>} record * @return {any} */ updateMultiple(criteria: FindConditions<Entity>, record: Partial<Entity>) { return this.repository.update(criteria, record as Entity); } /** * delete record by id * it performs soft delete * @param {number | string} id * @return {any} */ deleteById(id: number | string) { return this.repository.softDelete(id); } /** * delete multiple records * @param {<Entity>} criteria * @return {any} */ delete(criteria: FindConditions<Entity>) { return this.repository.softDelete(criteria); } /** * restores deleted record * @return {any} * @param id */ restoreById(id: number | string) { return this.repository.restore(id); } /** * restores deleted record * @param {<Entity>} criteria * @return {any} */ restore(criteria: FindConditions<Entity>) { return this.repository.softDelete(criteria); } /** * call a stored procedure * @param {string} spName * @param {any[]} parameters * @example * callSp('insertSp', [5, 'Test', 2]) * @return {Promise<any>} */ async callSp(spName: string, parameters: any[]) { let paramsMapStr = ''; parameters.forEach((param, index) => { paramsMapStr += (typeof param === 'string') ? '\'' + param + '\'' : param; if (index !== parameters.length - 1) { paramsMapStr += ','; } }); return await this.repository.query(`CALL ${spName}(${paramsMapStr})`); } /** * get repository * @return {TRepository} */ getRepo() { return this.repository; } /** * create query builder * creates a query builder instance and returns it * @param {string} alias * @return {any} */ createQueryBuilder(alias = '') { return this.repository.createQueryBuilder(alias); } /** * with transaction wrapper * wraps a function in transaction * @param {Function} txnFn * @return {Promise<any>} */ async withTransaction(txnFn: Function) { return getConnection().transaction(async (transactionalEntityManager: EntityManager) => { try { return await txnFn(transactionalEntityManager); } catch (e) { throw e; } }); } } <file_sep>import { PageOptionsDto } from '@/shared/dto/PageOptionsDto'; export class BooksPageOptionsDto extends PageOptionsDto {}
526c561a546b5877f14c2e980ec5cd53a4f49ed2
[ "Markdown", "TypeScript", "JavaScript" ]
35
TypeScript
app-sphere-softwares-llp/nest-typeorm-boilerplate
52732e5b71225f205e68ad12480af505003dbae4
ad54268286a146f7be76d3256ed50139a5bd2adc
refs/heads/master
<repo_name>Shani679/users<file_sep>/src/store/actions/index.js export{ getRandomUser, setUser, deleteUser, setTooltip } from './app';<file_sep>/src/shared/utility.js export const isValidEmail = (value) => { const pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/; return pattern.test(value) } export const checkImageURL = url => { return(url.match(/\.(jpeg|jpg|gif|png)$/) != null); } const properName = (name) => { return name.toLowerCase().replace(/\s/g, ''); }; export const calculateMatch = (per1, per2) => { const firstLowerCaseName = properName(per1.fullName); const secondLowerCaseName = properName(per2.fullName); const bothNames = firstLowerCaseName + secondLowerCaseName; let stringScore = 0; let alreadyPassedChars = []; for (let currIndex = 0; currIndex < firstLowerCaseName.length; currIndex++) { if (!alreadyPassedChars.includes(firstLowerCaseName[currIndex])) { if (secondLowerCaseName.includes(firstLowerCaseName[currIndex])) { const charInstancesCount = bothNames.split(firstLowerCaseName[currIndex]).length - 1; stringScore += charInstancesCount; } alreadyPassedChars.push(firstLowerCaseName[currIndex]); } } const ageScore = Math.abs(per1.age - per2.age); const finalScore = stringScore / (ageScore / 10); return finalScore; };<file_sep>/src/Components/Overview/User.js import React, {Component} from 'react'; import { styled } from '@material-ui/core/styles'; import Box from '@material-ui/core/Box'; import {UserModal} from './Modal'; import EditTwoToneIcon from '@material-ui/icons/EditTwoTone'; import FullscreenSharpIcon from '@material-ui/icons/FullscreenSharp'; import {withRouter} from 'react-router-dom'; const Container = styled(Box)({ display: "flex", margin: "10px", flexDirection: "column", justifyContent: "space-between", alignItems: "center", width: "250px", borderRadius: "3px", position: "relative", maxWidth: "100%", boxShadow: "rgba(0, 0, 0, 0.4) 0px 2px 7.68px 0.32px, rgba(0, 0, 0, 0.4) 0px 12px 26px 0px", ['@media (max-width:768px)']:{ width: "100%", margin: "10px 0" }, '&:hover > svg':{ display: "initial" }, '& > img': { width: "100%" }, '& > div':{ padding: "15px", width: "100%", boxSizing: "border-box", backgroundColor: "#fff", '& > p': { whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" } }, '& > svg': { position: "absolute", right: "0", cursor: "pointer", display: "none", '&:nth-child(2)': { top: "25px" } } }); class User extends Component{ state = { openModal: false } toggleModal(e, flag){ e.stopPropagation(); this.setState({openModal: flag}) } render(){ const {fullName, picture, email, id, userMatch} = this.props.user; return ( <Container> <EditTwoToneIcon color="secondary" onClick={() => this.props.history.push(`user/${id}`)}/> <FullscreenSharpIcon color="secondary" onClick={e => this.toggleModal(e, true)}/> <img src={picture}/> <div> <p>{fullName}</p> <p>{email}</p> {userMatch && <p>{`${userMatch === Infinity ? "100% Match" : userMatch}`}</p>} </div> {this.state.openModal && <UserModal user={this.props.user} onClose={e => this.toggleModal(e, false)}/>} </Container> ) } } export default withRouter(User);<file_sep>/src/Components/Overview/Users.js import React from 'react'; import { styled } from '@material-ui/core/styles'; import Box from '@material-ui/core/Box'; import User from './User'; import { connect } from 'react-redux'; const Container = styled(Box)({ display: "flex", padding: "30px 0", justifyContent: "flex-start", flexWrap: "wrap", fontFamily: 'Open Sans' }); const Users = (props) => { const {users} = props; return ( <Container> {!!users.length && users.map((user, i) => <User key={i} user={user}/>)} </Container> ) } const mapStateToProps = ({app}) => ({ users: app.users }); export default connect(mapStateToProps)(Users);<file_sep>/src/store/actions/actionTypes.js export const GET_RANDOM_USER_STARTED = 'GET_RANDOM_USER_STARTED'; export const GET_RANDOM_USER_SUCCESS = 'GET_RANDOM_USER_SUCCESS'; export const SET_USER = 'SET_USER'; export const DELETE_USER = 'DELETE_USER'; export const SET_LOADER = 'SET_LOADER'; export const SET_TOOLTIP = 'SET_TOOLTIP';<file_sep>/src/Components/Overview/Modal.js import React from 'react'; import Modal from '@material-ui/core/Modal'; import Box from '@material-ui/core/Box'; import { styled } from '@material-ui/core/styles'; import { makeStyles } from '@material-ui/core/styles'; import moment from 'moment'; const Container = styled(Box)({ width: "400px", background: "#fff", display: "flex", margin: "10px", flexDirection: "column", justifyContent: "flex-start", alignItems: "center", borderRadius: "8px", position: "relative", boxShadow: "rgba(0, 0, 0, 0.75) 15px 13px 19px -19px", '& > img': { width: "100%", borderRadius: "8px 8px 0 0" }, '& > div':{ padding: "15px", width: "100%", boxSizing: "border-box", fontFamily: 'Open Sans', '& span': { color: "#f50057", fontWeight: "bold", textDecoration: "underline" } }, '& > button':{ background: "#fff", padding: "0", position: "absolute", border: "none", right: "2px", top: "2px", fontSize: "22px", borderRadius: "100%", cursor: "pointer", width: "25px", height: "25px", display: "flex", justifyContent: "center", alignItems: "center", outline: "none", '& > span':{ transform: "rotate(135deg)", } } }); const useStyles = makeStyles(theme => ({ modal: { display: 'flex', padding: theme.spacing(1), alignItems: 'center', justifyContent: 'center', } })); export const UserModal = ({user, onClose}) => { const classes = useStyles(); const {fullName, picture, email, birthday, address} = user; return ( <Modal open disableEnforceFocus disableAutoFocus className={classes.modal}> <Container> <button onClick={e => onClose(e)}><span>+</span></button> <img src={picture}/> <div> <p><span>Full name:</span> {fullName}</p> <p><span>Birthday:</span> {moment(birthday).format('LL')}</p> <p><span>Email:</span> {email}</p> <p><span>Address:</span> {address}</p> </div> </Container> </Modal> ) }<file_sep>/src/Components/Overview/Tooltip.js import React from 'react'; import { makeStyles } from '@material-ui/core'; const useStyles = makeStyles({ container: { backgroundColor: props => props.isSuccess ? "#e7fcf7" : "#fdeaea", color: props => props.isSuccess ? "#10bfa0" : "#d42525", padding: "15px 16px", fontSize: "14px", display: "flex", alignItems: "center", width: "100%", maxWidth: "330px", margin: "15px auto 0", justifyContent: "center", borderRadius: "4px", boxSizing: "border-box" }, }); export const Tooltip = (props) => { const { container } = useStyles(props); return ( <div className={container}> {props.message} </div> ) }
e95e5d22932959522a310c8d3e695297c3a25214
[ "JavaScript" ]
7
JavaScript
Shani679/users
eb4d6647eb52b00bbdb72d8e3a747a7bd30faf12
a97507d3b685dc7109b98aca4cfbc976d0fa62c3
refs/heads/master
<file_sep>import React, { useState, useEffect } from 'react'; import TextField from '@material-ui/core/TextField'; import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogTitle from '@material-ui/core/DialogTitle'; import Backdrop from '@material-ui/core/Backdrop'; import CircularProgress from '@material-ui/core/CircularProgress'; import Radio from '@material-ui/core/Radio'; import RadioGroup from '@material-ui/core/RadioGroup'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import FormControl from '@material-ui/core/FormControl'; import FormLabel from '@material-ui/core/FormLabel'; import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles((theme) => ({ backdrop: { zIndex: theme.zIndex.drawer + 1, color: '#fff', }, })); const Room = ({ socket, userList, setRoom }) => { const [open, setOpen] = useState(true); const [userName, setUsername] = useState(''); const [player, setPlayer] = useState(null); const [message, setMessage] = useState(''); const [waiting, setWaiting] = useState(false); const classes = useStyles(); const noPlayers = userList.filter(i => i.id !== socket.id).length < 1; useEffect(() => { socket.on('play', (message) => { setMessage(message); }); socket.on('accepted', (from) => { setWaiting(false); setRoom(`${socket.id}_vs_${from}`); socket.emit('joinRoom', from); }); socket.on('denied', (message) => { setMessage({ message }); setWaiting(false); }); }, [setRoom, socket]); const handleClose = () => { setOpen(false); socket.emit('addUser', userName); }; const handlePlay = () => { setWaiting(true); socket.emit('playRequest', { from: userName, id: socket.id, to: player }) } const handlePlayCancel = () => { setMessage(false); socket.emit('playRequestDeny', { to: message.id }) } const handlePlayJoin = () => { setMessage(false); setRoom(`${message.id}_vs_${socket.id}`); socket.emit('playRequestConfirm', { to: message.id }) } return ( <div className="room"> <Backdrop className={classes.backdrop} open={waiting}> <CircularProgress color="inherit" /> </Backdrop> {userName && !open && <h1>Welcome {userName}!</h1>} <Dialog open={open} onClose={() => {}} aria-labelledby="form-dialog-title"> <DialogTitle id="form-dialog-title">Type a username</DialogTitle> <DialogContent> <TextField autoFocus margin="dense" id="name" label="Username" type="text" fullWidth onChange={(e) => setUsername(e.target.value)} /> </DialogContent> <DialogActions> <Button onClick={handleClose} color="primary"> Join </Button> </DialogActions> </Dialog> <Dialog open={!!message.message} onClose={() => {}} aria-labelledby="form-dialog-title"> <DialogTitle id="form-dialog-title">{message.message}</DialogTitle> {message.from ? <DialogActions> <Button onClick={handlePlayCancel} color="primary"> Cancel </Button> <Button onClick={handlePlayJoin} color="primary"> Join </Button> </DialogActions> : <DialogActions> <Button onClick={() => setMessage({})} color="primary"> Close </Button> </DialogActions>} </Dialog> <FormControl component="fieldset"> <FormLabel component="legend">Online players</FormLabel> <RadioGroup aria-label="gender" name="gender1" value={player} onChange={(e) => setPlayer(e.target.value)}> {noPlayers && <h6 style={{ marginTop: '1em' }}>No players online...</h6>} {userList.filter(i => i.id !== socket.id).map(u => <FormControlLabel value={u.id} control={<Radio />} key={`${u.id}`} label={u.nickname} />)} </RadioGroup> </FormControl> {player && <Button color="primary" className="button__button" onClick={handlePlay}>Play</Button>} </div> ) } export default Room <file_sep>import React, { useState, useEffect } from 'react'; import io from 'socket.io-client' import './App.css'; import TileGrid from './TileGrid'; import Room from './Room'; let socket = io.connect('http://localhost:5000'); if(process.env.NODE_ENV === 'production') { socket = io.connect('https://bingo-game-react.herokuapp.com/') } function App() { const [room, setRoom] = useState(null); const [userList, setUserList] = useState([]); useEffect(() => { socket.on('users', (users) => { setUserList(users); }); }); return ( // BEM <div className="app"> {/* <ColorPicker setColor={setColor} /> */} {room ? <TileGrid width={5} socket={socket} room={room} /> : <Room socket={socket} userList={userList} setRoom={setRoom} /> } </div> ); } export default App; <file_sep>import React from 'react' const EndGameModal = () => { return ( <div className="endGameModal"> </div> ) } export default EndGameModal <file_sep>const express = require('express'); const http = require('http'); const path = require('path'); const socketIo = require('socket.io'); const isDev = process.env.NODE_ENV !== 'production'; const PORT = process.env.PORT || 5000; const app = express(); app.use(express.static(path.resolve(__dirname, './client/build'))); // All remaining requests return the React app, so it can handle routing. app.get('*', function(request, response) { response.sendFile(path.resolve(__dirname, './client/build', 'index.html')); }); const server = http.createServer(app); const io = socketIo(server); let users = []; io.on('connection', socket => { socket.on('move', ({ message, id, room }) => { const players = room.split('_vs_'); const sender = players.find(i => i === id); const receiver = players.find(i => i !== id); io.to(receiver).emit('sendmove', { message, id }); console.log(message, 'from:', users.find(u => u.id === sender).nickname, 'to:', users.find(u => u.id === receiver).nickname); }) socket.on('score', ({ score, id, room }) => { const players = room.split('_vs_'); const receiver = players.find(i => i !== id); io.to(receiver).emit('sendscore', { score, id }); console.log(score, users.find(u => u.id === id).nickname); }) socket.on('addUser', (user) => { socket.join('game'); socket.nickname = user; console.log(socket.nickname, `(${socket.id})`, 'has connected to \'game\'!'); users.push({ id: socket.id, nickname: socket.nickname }); io.in('game').emit('users', users); }) socket.on('playRequest', ({ from, to, id }) => { console.log('play request sent from', from, 'to', to); io.to(to).emit('play', { message: `Player '${from}' wants to play with you. Join game?`, from, id }); }) socket.on('playRequestDeny', ({ to }) => { console.log('play request denied from', socket.id); io.to(to).emit('denied', 'The player denied your invite'); }); socket.on('playRequestConfirm', ({ to }) => { console.log('play request accepted to', to); io.to(to).emit('accepted', socket.id); socket.join(`${to}_vs_${socket.id}`); console.log(socket.id, 'joined', `${to}_vs_${socket.id}`, 'room!'); }); socket.on('joinRoom', (from) => { socket.join(`${socket.id}_vs_${from}`); console.log(socket.id, 'joined', `${socket.id}_vs_${from}`, 'room!'); }); socket.on('disconnect', () => { if (socket.nickname) { users = users.filter(u => u.id !== socket.id); console.log(socket.nickname, `(${socket.id})`, 'has disconnected from \'game\'!', 'Users left:', users); io.in('game').emit('users', users); } }); }) // Priority serve any static files. server.listen(PORT, function () { console.error(`Node ${isDev ? 'dev server' : 'cluster worker '+process.pid}: listening on port ${PORT}`); }); <file_sep>import React, { useEffect, useState } from 'react' import Backdrop from '@material-ui/core/Backdrop'; import CircularProgress from '@material-ui/core/CircularProgress'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogTitle from '@material-ui/core/DialogTitle'; import Button from '@material-ui/core/Button'; import { makeStyles } from '@material-ui/core/styles'; import { shuffle, transpose } from './helpers.js' import Tile from './Tile.js'; const useStyles = makeStyles((theme) => ({ backdrop: { zIndex: theme.zIndex.drawer + 1, color: '#fff', }, })); const TileGrid = ({ width, userColor, socket, room}) => { const [schema, setSchema] = useState([]); const [score, setScore] = useState(0); const [scores, setScores] = useState({ [socket.id]: 0 }); const [open, setOpen] = useState(false); const [reset, setReset] = useState(false); const [moves, setMoves] = useState([]); const [win, setWin] = useState(false); const [lost, setLost] = useState(false); const classes = useStyles(); useEffect(() => { socket.on('sendmove', ({ message, id }) => { setMoves((oldMooves) => [...oldMooves, { id, message }]); }); socket.on('sendscore', ({ score: scr, id }) => { setScores((oldScores) => ({ ...oldScores, [id]: scr })); }); }, [room, socket]); useEffect(() => { const move = moves[moves.length -1] || {}; const { message, id } = move; if (id !== socket.id) { const newSchema = [...schema]; newSchema.forEach((x, i) => x.forEach((y, j) => { if (newSchema[i][j].value === message) { newSchema[i][j].selected = true; } })); setSchema(newSchema); setOpen(false); } }, [moves, socket.id]); useEffect(() => { const players = room.split('_vs_'); const p1 = players.find(p => p === socket.id); const p2 = players.find(p => p !== socket.id); const p1score = scores[p1]; const p2score = scores[p2]; if (p1score >= 5 && p2score < 5) setWin(true); if (p1score < 5 && p2score >= 5) setLost(true); if (p1score >= 5 && p2score >= 5) { if (p1score > p2score) setWin(true); if (p1score < p2score) setLost(true); } }, [scores]); useEffect(() => { const array = [...Array(width * width)].map((x, i) => ({ value: i + 1, selected: false })); const randomArray = shuffle(array); let output = []; [...Array(width)].forEach((x , i) => { output[i] = randomArray.filter((f, j) => j >= (i * width) && j < ((i + 1) * (width))); }); setSchema([...output]); }, [reset, width]); useEffect(() => { let newScore = 0; const columns = transpose(schema); const diagona1 = schema.map((x, i) => x[i]); const diagona2 = schema.map((x, i, all) => x[all.length - 1 - i]); if(diagona1.every(x => x.selected)) { newScore += 1; } if(diagona2.every(x => x.selected)) { newScore += 1; } schema.forEach(f => { if (f.every(x => x.selected)) { newScore += 1; } }) columns.forEach(f => { if (f.every(x => x.selected)) { newScore += 1; } }) setScore(newScore); setScores((oldScores) => ({ ...oldScores, [socket.id]: newScore })) socket.emit('score', { score: newScore, id: socket.id, room }); }, [schema]) const onSelected = (row, column) => { const newSchema = [...schema]; newSchema[row][column].selected = true; setSchema(newSchema); socket.emit('move', { message: schema[row][column].value, id: socket.id, room}); setOpen(true); }; const handleNewGame = () => { setReset(!reset); setOpen(false); setLost(false); setWin(false); setScore(0); setScores({ [socket.id]: 0 } ); }; const renderTile = (row) => { return <div key={`${row}`} className="tileGrid__row">{(schema[row] || []).map((j, i) => <Tile key={`${i}`} reset={reset} color={userColor} value={j.value} selected={j.selected} row={row} column={i} onSelected={onSelected} />)} </div>; } return ( <> <Backdrop className={classes.backdrop} open={open}> <CircularProgress color="inherit" /> </Backdrop> <Dialog open={win || lost} onClose={() => {}} aria-labelledby="form-dialog-title"> <DialogTitle id="form-dialog-title">{win ? 'You win!' : ''}{lost ? 'You Lost!' : ''}</DialogTitle> <DialogActions> <Button onClick={handleNewGame} color="primary"> New Game </Button> </DialogActions> </Dialog> <div className="tileGrid"> {[...Array(width)].map((x, i) => renderTile(i))} </div> <p className="tileGrid__score">Your score: {score}</p> </> ) } export default TileGrid
8c447b3924399a665c6388369b8fd6bcd403aa34
[ "JavaScript" ]
5
JavaScript
mvampa91/bingo-game
458222fa90bc899b13897f64d9d95fdae64f9cb3
66ee9461405bfaacd6bc4ea6bcec298acc62c4ec
refs/heads/master
<file_sep>/* ================================================================== * Matlab call C = cellstrmap(A, B) * where A and B are cell arrays of strings, * return array C of integers such that * A(i) = B(C(i)) if A(i) occurs in B, * C(i) = 0 otherwise * ================================================================== */ #include "mex.h" #include "utils.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mwIndex mA, nA, mB, nB, i, Nstr; mxArray * pStr; double * pC; char * str; /* Check for proper number of input arguments */ if (nrhs != 2) mexErrMsgTxt("cellstrmap: two input args required."); /* Now check types */ if(!mxIsCell(prhs[0]) || !mxIsCell(prhs[1])) mexErrMsgTxt("cellstrmap: inputs must be cell arrays of strings"); mA = mxGetM(prhs[0]); nA = mxGetN(prhs[0]); mB = mxGetM(prhs[1]); nB = mxGetN(prhs[1]); if (min(mA, nA) > 1 || min(mB, nB) > 1) mexErrMsgTxt("cellstrmap: inputs must be vectors"); nA *= mA; nB *= mB; strhash htab(0); unhash unh(0); /* fill a hash map with strings from B pointing to the corresponding index of B */ for (i = 0; i < nB; i++) { pStr = mxGetCell(prhs[1], i); if(!mxIsChar(pStr)) mexErrMsgTxt("cellstrmap: inputs must be cell arrays of strings."); Nstr = mxGetN(pStr); try { str = new char[Nstr+1]; mxGetString(pStr, str, Nstr+1); if (htab.count(str)) { delete [] str; mexErrMsgTxt("cellstrmap: duplicate string in second arg"); } else { htab[str] = i+1; unh.push_back(str); } } catch (std::bad_alloc) { mexErrMsgTxt("cellstrmap: internal allocation error"); } } plhs[0] = mxCreateDoubleMatrix(nA, 1, mxREAL); if (plhs[0] == NULL) { mexErrMsgTxt("cellstrmap: Output array allocation failed"); } pC = mxGetPr(plhs[0]); /* now look up strings from A to get the corresponding index of B */ for (i = 0; i < nA; i++) { pStr = mxGetCell(prhs[0], i); if(!mxIsChar(pStr)) mexErrMsgTxt("cellstrmap: inputs must be cell arrays of strings."); Nstr = mxGetN(pStr); try { str = new char[Nstr+1]; mxGetString(pStr, str, Nstr+1); if (htab.count(str)) { pC[i] = htab[str]; } else { pC[i] = 0; } delete [] str; } catch (std::bad_alloc) { mexErrMsgTxt("cellstrmap: internal allocation error"); } } for (i = 0; i < unh.size(); i++) { delete [] unh[i]; unh[i] = NULL; } } <file_sep>#!/bin/bash export JAVA_OPTS="-Xmx12G -Xms128M" # Set as much memory as possible BIDPARSE_ROOT="${BASH_SOURCE[0]}" if [ ! `uname` = "Darwin" ]; then BIDPARSE_ROOT=`readlink -f "${BIDPARSE_ROOT}"` else BIDPARSE_ROOT=`readlink "${BIDPARSE_ROOT}"` fi BIDPARSE_ROOT=`dirname "$BIDPARSE_ROOT"` BIDPARSE_ROOT="$( echo ${BIDPARSE_ROOT} | sed s+/cygdrive/c+c:+ )" BIDMAT_ROOT="${BIDPARSE_ROOT}/../BIDMat" # Change if needed # export JAVA_HOME="" # Set here if not set in environment # Fix these if needed JCUDA_VERSION="0.5.0" JCUDA_LIBDIR="${BIDMAT_ROOT}/lib" BIDLIB="${BIDMAT_ROOT}/lib" LIBDIR=${BIDPARSE_ROOT}/lib if [ `uname` = "Darwin" ]; then export DYLD_LIBRARY_PATH="${BIDMAT_ROOT}/lib:${BIDPARSE_ROOT}/lib:/usr/local/cuda/lib:${LD_LIBRARY_PATH}" else export LD_LIBRARY_PATH="${BIDMAT_ROOT}/lib:${BIDPARSE_ROOT}/lib:/usr/local/cuda/lib64:${LD_LIBRARY_PATH}" fi BIDMAT_LIBS="${BIDMAT_ROOT}/BIDMat.jar;${BIDLIB}/ptplot.jar;${BIDLIB}/ptplotapplication.jar;${BIDLIB}/jhdf5.jar;${BIDLIB}/commons-math3-3.1.1.jar" JCUDA_LIBS="${JCUDA_LIBDIR}/jcuda-${JCUDA_VERSION}.jar;${JCUDA_LIBDIR}/jcublas-${JCUDA_VERSION}.jar;${JCUDA_LIBDIR}/jcufft-${JCUDA_VERSION}.jar;${JCUDA_LIBDIR}/jcurand-${JCUDA_VERSION}.jar;${JCUDA_LIBDIR}/jcusparse-${JCUDA_VERSION}.jar" export ALL_LIBS="${BIDPARSE_ROOT}/BIDParse.jar;${LIBDIR}/berkeleyparser4BIDParse.jar;${BIDMAT_LIBS};${JCUDA_LIBS};${JAVA_HOME}/lib/tools.jar" if [ ! "$OS" = "Windows_NT" ]; then export ALL_LIBS=`echo "${ALL_LIBS}" | sed 's/;/:/g'` fi cd ${BIDPARSE_ROOT} scala -nobootcp -cp "${ALL_LIBS}" -Yrepl-sync -i ${LIBDIR}/bidparse_init.scala<file_sep> #include <jni.h> #include <cuda_runtime.h> #include "Logger.hpp" #include "JNIUtils.hpp" #include "PointerUtils.hpp" #include "nncallall.h" #include "ntcallall.h" #include "tncallall.h" #include "ttcallall.h" #include "nncallallu.h" #include "ntcallallu.h" #include "ttcallallu.h" #include "BIDMat_PARSE.hpp" extern "C" { JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) { JNIEnv *env = NULL; if (jvm->GetEnv((void **)&env, JNI_VERSION_1_4)) { return JNI_ERR; } jclass cls = NULL; // Initialize the JNIUtils and PointerUtils if (initJNIUtils(env) == JNI_ERR) return JNI_ERR; if (initPointerUtils(env) == JNI_ERR) return JNI_ERR; return JNI_VERSION_1_4; } JNIEXPORT jint JNICALL Java_edu_berkeley_bid_PARSE_nnrules (JNIEnv *env, jobject obj, jobject jP, jobject jL, jobject jR, jobject jScale, jint ndo, jint nthreads) { float *P = (float*)getPointer(env, jP); float *L = (float*)getPointer(env, jL); float *R = (float*)getPointer(env, jR); float *scale = (float*)getPointer(env, jScale); return nncallall(P, L, R, scale, ndo, nthreads); } JNIEXPORT jint JNICALL Java_edu_berkeley_bid_PARSE_ntrules (JNIEnv *env, jobject obj, jobject jP, jobject jL, jobject jR, jobject jScale, jint ndo, jint nthreads) { float *P = (float*)getPointer(env, jP); float *L = (float*)getPointer(env, jL); float *R = (float*)getPointer(env, jR); float *scale = (float*)getPointer(env, jScale); return ntcallall(P, L, R, scale, ndo, nthreads); } JNIEXPORT jint JNICALL Java_edu_berkeley_bid_PARSE_tnrules (JNIEnv *env, jobject obj, jobject jP, jobject jL, jobject jR, jobject jScale, jint ndo, jint nthreads) { float *P = (float*)getPointer(env, jP); float *L = (float*)getPointer(env, jL); float *R = (float*)getPointer(env, jR); float *scale = (float*)getPointer(env, jScale); return tncallall(P, L, R, scale, ndo, nthreads); } JNIEXPORT jint JNICALL Java_edu_berkeley_bid_PARSE_ttrules (JNIEnv *env, jobject obj, jobject jP, jobject jL, jobject jR, jobject jScale, jint ndo, jint nthreads) { float *P = (float*)getPointer(env, jP); float *L = (float*)getPointer(env, jL); float *R = (float*)getPointer(env, jR); float *scale = (float*)getPointer(env, jScale); return ttcallall(P, L, R, scale, ndo, nthreads); } JNIEXPORT jint JNICALL Java_edu_berkeley_bid_PARSE_nnrulesu (JNIEnv *env, jobject obj, jobject jP, jobject jL, jobject jR, jobject jScale, jint ndo, jint nthreads) { float *P = (float*)getPointer(env, jP); float *L = (float*)getPointer(env, jL); float *scale = (float*)getPointer(env, jScale); return nncallallu(P, L, scale, ndo, nthreads); } JNIEXPORT jint JNICALL Java_edu_berkeley_bid_PARSE_ntrulesu (JNIEnv *env, jobject obj, jobject jP, jobject jL, jobject jR, jobject jScale, jint ndo, jint nthreads) { float *P = (float*)getPointer(env, jP); float *L = (float*)getPointer(env, jL); float *scale = (float*)getPointer(env, jScale); return ntcallallu(P, L, scale, ndo, nthreads); } JNIEXPORT jint JNICALL Java_edu_berkeley_bid_PARSE_ttrulesu (JNIEnv *env, jobject obj, jobject jP, jobject jL, jobject jR, jobject jScale, jint ndo, jint nthreads) { float *P = (float*)getPointer(env, jP); float *L = (float*)getPointer(env, jL); float *scale = (float*)getPointer(env, jScale); return ttcallallu(P, L, scale, ndo, nthreads); } JNIEXPORT jint JNICALL Java_edu_berkeley_bid_PARSE_pcopytxin (JNIEnv *env, jobject obj, jobject jiptrs, jobject jin, jobject jout, jint stride, jint nrows, jint ncols) { int *iptrs = (int*)getPointer(env, jiptrs); float *in = (float*)getPointer(env, jin); float *out = (float*)getPointer(env, jout); return pcopy_transpose_in(iptrs, in, out, stride, nrows, ncols); } JNIEXPORT jint JNICALL Java_edu_berkeley_bid_PARSE_pcopytxout (JNIEnv *env, jobject obj, jobject joptrs, jobject jin, jobject jout, jint stride, jint nrows, jint ncols) { int *optrs = (int*)getPointer(env, joptrs); float *in = (float*)getPointer(env, jin); float *out = (float*)getPointer(env, jout); return pcopy_transpose_out(optrs, in, out, stride, nrows, ncols); } JNIEXPORT jint JNICALL Java_edu_berkeley_bid_PARSE_viterbiGPU (JNIEnv *env, jobject obj, jint nnsyms0, jint ntsyms0, jint nnsyms, jint ntsyms, jint ntrees, jint isym, jobject j_wordsb4, jobject j_wordsafter, jobject j_treesb4, jobject j_treesafter, jobject j_iwordptr, jobject j_itreeptr, jobject j_parsetrees, jobject j_parsevals, jobject j_pp, jobject j_darr, jobject j_bval, jint ldp, jobject j_upp, jobject j_uarr, jobject j_uval, jint ldup) { float *wordsb4 = (float*)getPointer(env, j_wordsb4); float *wordsafter = (float*)getPointer(env, j_wordsafter); float *treesb4 = (float*)getPointer(env, j_treesb4); float *treesafter = (float*)getPointer(env, j_treesafter); int *iwordptr = (int*)getPointer(env, j_iwordptr); int *itreeptr = (int*)getPointer(env, j_itreeptr); int *parsetrees = (int*)getPointer(env, j_parsetrees); float *parsevals = (float*)getPointer(env, j_parsevals); int *pp = (int*)getPointer(env, j_pp); int *darr = (int*)getPointer(env, j_darr); float *bval = (float*)getPointer(env, j_bval); int *upp = (int*)getPointer(env, j_upp); int *uarr = (int*)getPointer(env, j_uarr); float *uval = (float*)getPointer(env, j_uval); return viterbi(nnsyms0, ntsyms0, nnsyms, ntsyms, ntrees, isym, wordsb4, wordsafter, treesb4, treesafter, iwordptr, itreeptr, parsetrees, parsevals, pp, darr, bval, ldp, upp, uarr, uval, ldup); } } <file_sep>BIDParse ======== GPU-accelerated natural language parser<file_sep> extern __global__ void transpose(float *in, int instride, float *out, int outstride, int inrows, int incols); extern __global__ void pcopy_transpose(float **in, float *out, int outstride, int nrows, int ncols); extern __global__ void pcopy_setup(int *inds, float **src, float *target, int ncols, int stride); extern __global__ void pcopy(float **src, float *dest, int nrows, int ncols, int stride); extern void testvmax(float *vec, float *cvec, int n, int nreps, int i); const int stride = 8192; const int BLOCKDIM = 32; const int INBLOCK = 4; const int NSYMS = 640; #define DATADIR "c:/data/Grammar/" const char nnfname[] = DATADIR "nnbinrulesx.dat"; const char ntfname[] = DATADIR "ntbinrulesx.dat"; const char tnfname[] = DATADIR "tnbinrulesx.dat"; const char ttfname[] = DATADIR "ttbinrulesx.dat"; <file_sep>/* function [C IA IB ..] = cellstrunion(A, B, ...) * * * * where A, B,... are cell arrays of strings, * * return cell array of strings C containing * * one occurence of each string from A u B... * * * * If LHS index matrices are given, return * * indices IX such that A = C(IA), B = C(IB)... */ #include "mex.h" #include "utils.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mwIndex mA, nA, mB, nB, i, j, Nstr; mxArray *pB, *pC, *pStr; double *dC; char * str; /* Check for proper number of input arguments */ if (nrhs < 1) mexErrMsgTxt("cellstrunion: at least one input arg required."); /* Now check types */ for (i = 0; i < nrhs; i++) { if(!mxIsCell(prhs[i])) mexErrMsgTxt("cellstrunion: inputs must be cell arrays of strings."); } unhash unh(0); strhash htab(0); for (i = 0; i < nrhs; i++) { mA = mxGetM(prhs[i]); nA = mxGetN(prhs[i]); if (i+1 < nlhs) { pC = mxCreateDoubleMatrix(mA ,nA , mxREAL); if (pC == NULL) mexErrMsgTxt("cellstrunion: Index array allocation failed"); plhs[i+1] = pC; dC = mxGetPr(pC); } else { dC = NULL; } for (j = 0; j < mA*nA; j++) { pStr = mxGetCell(prhs[i], j); if(!mxIsChar(pStr)) mexErrMsgTxt("cellstrunion: inputs must be cell arrays of strings."); Nstr = mxGetN(pStr); try { str = new char[Nstr+1]; mxGetString(pStr, str, Nstr+1); if (htab.count(str)) { if (dC) dC[j] = htab[str]; delete [] str; } else { unh.push_back(str); htab[str] = (int)unh.size(); if (dC) dC[j] = (double)unh.size(); } } catch (std::bad_alloc) { mexErrMsgTxt("cellstrunion: internal allocation error"); } } } mB = unh.size(); pB = mxCreateCellMatrix(mB, 1); if (pB == NULL) mexErrMsgTxt("cellstrunion: Cell array allocation failed"); plhs[0] = pB; for (i = 0; i < mB; i++) { pStr = mxCreateString(unh[i]); if (pStr == NULL) mexErrMsgTxt("cellstrunion: String allocation failed"); mxSetCell(pB, i, pStr); delete [] unh[i]; unh[i] = NULL; } } <file_sep> int pcopy_transpose_in(int *iptrs, float *in, float *out, int stride, int nrows, int ncols); int pcopy_transpose_out(int *optrs, float *in, float *out, int stride, int nrows, int ncols); int viterbi(int nnsyms0, int ntsyms0, int nnsyms, int ntsyms, int ntrees, int isym, float *wordsb4, float *wordsafter, float *treesb4, float *treesafter, int *iwordptr, int *itreeptr, int *parsetrees, float *parsevals, int *pp, int *darr, float *bval, int ldp, int *upp, int *uarr, float *uval, int ldup); <file_sep>/* ================================================================== * Matlab call [A B C] = cellstrsplit(X, d) * where X is a cell arrays of n strings, * return sparse mxn array A of indices where A(:,i) are * the indices of the substrings of X{i} split by the delimiter d. * B is a cell array of strings that correspond to the indices in A. * C is an array of counts for each index. * ================================================================== */ #include "mex.h" #include "utils.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mwIndex mA, nA, mB, nB, i, Nstr; mxArray * pStr, * pC; char * str, * delims; /* Check for proper number of input arguments */ if (nrhs != 2) mexErrMsgTxt("cellstrsplit: two input args required."); /* Now check types */ if(!mxIsCell(prhs[0])) mexErrMsgTxt("cellstrsplit: first input must be cell array of strings"); if(!mxIsChar(prhs[1])) mexErrMsgTxt("cellstrsplit: second input must be a string"); mA = mxGetM(prhs[0]); nA = mxGetN(prhs[0]); mB = mxGetM(prhs[1]); nB = mxGetN(prhs[1]); if (min(mA, nA) > 1 || min(mB, nB) > 1) mexErrMsgTxt("cellstrsplit: inputs must be vectors"); nA *= mA; nB *= mB; Nstr = mxGetN(prhs[1]); try { delims = new char[Nstr+1]; str = new char[BUFSIZE]; } catch (std::bad_alloc) { mexErrMsgTxt("cellstrsplit: internal allocation error"); } mxGetString(prhs[1], delims, Nstr+1); stringIndexer si; imatrix im(nA); for (i = 0; i < nA; i++) { pStr = mxGetCell(prhs[0], i); if(!mxIsChar(pStr)) mexErrMsgTxt("cellstrsplit: first input must be cell array of strings."); Nstr = mxGetN(pStr); mxGetString(pStr, str, Nstr+1); im[i] = si.checkstring(str, delims); } plhs[0] = matGetIntVecs2(im); if (plhs[0] == NULL) mexErrMsgTxt("cellstrsplit: Output array allocation failed"); if (nlhs > 1) { plhs[1] = matGetStrings(si.unh); if (plhs[1] == NULL) mexErrMsgTxt("cellstrsplit: Output array allocation failed"); if (nlhs > 2) { plhs[2] = matGetInts(si.count); if (plhs[2] == NULL) mexErrMsgTxt("cellstrsplit: Output array allocation failed"); } } delete [] str; if (delims) delete [] delims; } <file_sep>include Makefile.incl OBJS=$(shell echo rules/*.cu | sed -e s/\.cu/.$(OBJ)/g | sed -e s+rules\/+bin\/+g) bin/BIDMat_PARSE.$(OBJ) bin/xPcopy.$(OBJ) bin/xViterbi.$(OBJ) LIBFILE=$(LIBPREPEND)jniparse$(LIBAPPEND) .SUFFIXES: .$(OBJ) .c all: $(LIBPREPEND)jniparse$(LIBAPPEND) $(LIBPREPEND)jniparse$(LIBAPPEND): $(OBJS) $(LD) $(LDFLAGS) $(OBJS) $(CUDA_LIBS) $(OUTFLG)$@ bin/%.$(OBJ) : %.c $(CC) $(CPPFLAGS) $(CFLAGS) $(OUTFLG)bin/$*.$(OBJ) $*.c bin/%.$(OBJ) : %.cpp $(GCC) $(CPPFLAGS) $(OUTFLG)bin/$*.$(OBJ) $*.cpp bin/%.$(OBJ) : %.cu testSparse.h $(NVCC) $(NVCCFLAGS) -o bin/$*.$(OBJ) $*.cu # L1 caching disabled: bin/%.$(OBJ) : rules/%.cu testSparse.h $(NVCC) $(NVCCFLAGS) -Xptxas -dlcm=cg -o bin/$*.$(OBJ) rules/$*.cu install: ../../lib/$(LIBFILE) ../../lib/$(LIBFILE): $(LIBFILE) cp $(LIBFILE) ../../lib clean: rm -f *.$(OBJ) *.lib *.pdb *$(LIBAPPEND) bin/* distclean: clean rm -f *$(LIBAPPEND) *.exp *.lib *.jnilib Makefile.incl
f239751182e6d92072ca6efe65744919df39d7cd
[ "Markdown", "Makefile", "C", "C++", "Shell" ]
9
C++
chagge/BIDParse
718f09fcb3c1ad159ea928bd1305c41ad8d2840b
9d99704e1dd990fb4aee0fbe3ad428e98a4cc863
refs/heads/master
<repo_name>tnvu210/UTD-Senior-Project<file_sep>/Main.py from controller import Controller from controller import GardenDb import sys sys.path.append('/home/pi/.local/lib/python3.5/site-packages') import time import schedule import logging # setup on boot # create logger logger = logging.getLogger('garden') logger.setLevel(logging.DEBUG) # create file handler fh = logging.FileHandler('garden.log') fh.setLevel(logging.DEBUG) # create console handler ch = logging.StreamHandler() ch.setLevel(logging.ERROR) # create formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) #add handlers to logger logger.addHandler(fh) logger.addHandler(ch) logger.info('creating instance of controller.Controller') controller = Controller.Controller() schedule.clear() #schedule.every(30).minutes.do(controller.adjust_ph).tag("ph") schedule.every(10).minutes.do(controller.record_readings).tag("record") schedule.every(15).minutes.do(controller.adjust_humidity).tag("humidity") schedule.every(15).minutes.do(controller.adjust_temp).tag("temp") schedule.every().hour.do(controller.get_active_grow).tag("update") schedule.every().hour.do(controller.get_active_plants).tag("update") schedule.every().hour.do(controller.get_lighting_type).tag("update") #schedule.every().day.do(controller.adjust_nutrients).tag("nutrients") lighting_times = controller.init_lights() if lighting_times is not None: for lighting_time in lighting_times: if lighting_time.lighting: schedule.every().day.at(lighting_time.lighting_time).do(controller.lights_on).tag("lights") else: schedule.every().day.at(lighting_time.lighting_time).do(controller.lights_off).tag("lights") # run forever while True: while controller.active_grow is not None: # make any updates to scheduling or conditions if needed if controller.change_light_times: lighting_times = controller.init_lights() if lighting_times is not None: for lighting_time in lighting_times: if lighting_time.lighting: schedule.every().day.at(lighting_time.lighting_time).do(controller.lights_on).tag("lights") else: schedule.every().day.at(lighting_time.lighting_time).do(controller.lights_off).tag("lights") controller.change_light_times = False schedule.run_pending() #time.sleep(1) logger.info('No active grow. Sleeping for 5 minutes') time.sleep(60 * 5) controller.get_active_grow()<file_sep>/README.md # AutomatedGarden This project is to build Built an automated indoor garden with minimal water usage and minimal hassle. Use Raspberry Pi to control light, temperature, water level, nutrients...etc. <file_sep>/controller/Controller.py from controller import GardenDb from controller import water_system from controller import environment_system from controller import Singleton import sys sys.path.append('/home/pi/.local/lib/python3.5/site-packages') import wiringpi from datetime import datetime, time import logging import peewee class Controller(): """Interface for scheduling system functions""" def __init__(self): wiringpi.wiringPiSetup() #init all pins wiringpi.pinMode(water_system.FLORAGROW_PIN, 1) wiringpi.pinMode(water_system.FLORABLOOM_PIN, 1) wiringpi.pinMode(water_system.FLORAMICRO_PIN, 1) wiringpi.pinMode(water_system.PH_UP_PIN, 1) wiringpi.pinMode(water_system.PH_DOWN_PIN, 1) wiringpi.pinMode(environment_system.FAN_PIN, 1) wiringpi.pinMode(environment_system.LED_PIN, 1) wiringpi.pinMode(environment_system.DEHUMIDIFIER_PIN, 1) #ensuer all relays are off wiringpi.digitalWrite(environment_system.DEHUMIDIFIER_PIN, 1) wiringpi.digitalWrite(environment_system.FAN_PIN, 1) wiringpi.digitalWrite(water_system.FLORAGROW_PIN, 1) wiringpi.digitalWrite(water_system.FLORABLOOM_PIN, 1) wiringpi.digitalWrite(water_system.FLORAMICRO_PIN, 1) wiringpi.digitalWrite(water_system.PH_DOWN_PIN, 1) wiringpi.digitalWrite(water_system.PH_UP_PIN, 1) # create this objects attributes self.logger = logging.getLogger('garden.controller.Controller') self.logger.info('creating instance of controller.Controller') self.active_grow = None self.active_plants = None self.lighting_type = None self.change_light_times = False self.get_active_plants() self.get_active_grow() self.get_lighting_type() self.led = False self.fan = False self.dehumidifier = False def get_active_plants(self): """Update plant attribute and check if attribute has changed""" if self.active_plants is not None: temp = self.active_plants else: temp = None GardenDb.db.get_conn() self.active_plants = (GardenDb.Plants.select() .join(GardenDb.Plants_Grow) .join(GardenDb.Grow) .where(GardenDb.Grow.is_active == 1)).first() GardenDb.db.close() self.logger.info('active plants just updated from db') if temp is not None: self.logger.info('check if any conditions have changed - not implemented yet') pass return self.active_plants def get_active_grow(self): GardenDb.db.get_conn() self.active_grow = (GardenDb.Grow.select() .where(GardenDb.Grow.is_active == 1)).first() GardenDb.db.close() self.logger.info('active grow just updated from db') return self.active_grow def get_lighting_type(self): if self.lighting_type is not None: temp = self.lighting_type else: temp = None GardenDb.db.get_conn() self.lighting_type = GardenDb.LightingType.select().where(GardenDb.LightingType.lighting_type_id == self.active_grow.lighting_type_id).first() GardenDb.db.close() self.logger.info('lighting type updated from db') if temp is not None: self.logger.info('check if lighs have changed') if temp.lighting_type_id != self.lighting_type.lighting_type_id: self.change_light_times = True return self.lighting_type def record_readings(self): """read all sensors and write values to the db""" GardenDb.db.get_conn() ph_reading = water_system.ph() ec_reading = water_system.ec() humidity_temp = environment_system.humidity_temp() gallons_reading = water_system.gallons() q = GardenDb.GrowLog.insert(reading_time=datetime.now(), temp=humidity_temp[2], humidity=humidity_temp[0], ph=ph_reading, ec=ec_reading, gallons=gallons_reading, grow_id=self.active_grow) q.execute() GardenDb.db.close() self.logger.info('readings recorded to db') def pump_ph(self, pin, amount): if pin: water_system.pump(water_system.PH_UP_PIN, amount) else: water_system.pump(water_system.PH_DOWN_PIN, amount) def adjust_ph(self): self.logger.info('calling water_system.dispense_ph()') ideal_ph = self.active_plants.ph_target water_system.dispense_ph(ideal_ph, self.active_grow) self.logger.info('finished water_system.dispense_ph()') def adjust_humidity(self): self.logger.info('checking current humdidity against ideal') ideal_humidity = self.active_plants.humidity_max reading = environment_system.humidity_temp() if self.dehumidifier: #if dehumidifer is on turn off when humidity less than ideal if reading[0] < ideal_humidity: environment_system.dehumidifier_off() self.dehumidifier = False else: #if dehumidifier is off turn on when humidity is more than ideal if reading[0] > ideal_humidity: environment_system.dehumidifier_on() self.dehumidifier = True def adjust_temp(self): self.logger.info('checking current temp agasint ideal') max_temp = self.active_plants.temp_max reading = environment_system.humidity_temp() if self.fan: #if fan is on turn off when temp is below max if reading[2] < max_temp: environment_system.fan_off() self.fan = False else: #if fan is off turn on when temp is above max if reading[2] > max_temp: environment_system.fan_on() self.fan = True def adjust_nutrients(self): self.logger.info('calling water_system.dispense_ph()') ideal_ec = 0.3283143 water_system.pump_nutrients_adjust(ideal_ec, self.active_grow) self.logger.info('finished water_system.dispense_ph()') def full_feeding(self): water_system.pump_nutrients_full_feeding(self.active_grow) def lights_on(self): self.logger.info('calling environment_system.lights_on()') environment_system.lights_on() self.led = True self.logger.info('finished environment_system.lights_on()') def lights_off(self): self.logger.info('calling environment_system.lights_off()') environment_system.lights_off() self.led = False self.logger.info('finished environment_system.lights_off()') def init_lights(self): """Turns lights on if they should be, returns times""" if self.lighting_type.lighting_type == '12-12': # 12-12 lights 10am-10pm default now = datetime.now() time_on = [] time_off = [] light_times = GardenDb.LightingTimes.select().where( GardenDb.LightingTimes.lighting_type_id == self.lighting_type.lighting_type_id) for light_time in light_times: if light_time.lighting: time_on = light_time.split(':') else: time_off = light_time.split(':') if time(int(time_on[0]),int(time_on[1])) <= now.time() <= time(int(time_off[0]),int(time_off[1])): self.logger.info('turning lights on during init (daytime)') self.lights_on() else: self.logger.info('keeping lights off during init (nighttime)') self.lights_off() return light_times elif self.lighting_type.lighting_type == '24 hour': # 24 hour on self.logger.info('turning lights on (24 hour)') self.lights_on() return None elif self.lighting_type.lighting_type == "6-2": #6 on 2 off now = datetime.now() light_times = GardenDb.LightingTimes.select().where( GardenDb.LightingTimes.lighting_type_id == self.lighting_type.lighting_type_id) time_on = [] time_off =[] for light_time in light_times: if light_time.lighting: temp = light_time.lighting_time.split(':') time_on.append(temp[0]) time_on.append(temp[1]) else: temp = light_time.lighting_time.split(':') time_off.append(temp[0]) time_off.append(temp[1]) if time(int(time_on[0]),int(time_on[1])) <= now.time() <= time(int(time_off[0]),int(time_off[1])): self.lights_on() elif time(int(time_on[2]),int(time_on[3])) <= now.time() <= time(int(time_off[2]),int(time_off[3])): self.lights_on() elif time(int(time_on[4]),int(time_on[5])) <= now.time() <= time(int(time_off[4]),int(time_off[5])): self.lights_on() else: self.lights_off() return light_times<file_sep>/controller/GardenDb.py import sys sys.path.append('/home/pi/.local/lib/python3.5/site-packages') import pymysql import datetime from peewee import * from playhouse.pool import PooledMySQLDatabase db = PooledMySQLDatabase('garden', max_connections=32, stale_timeout=300, host='localhost', user='garden', passwd='<PASSWORD>') class BaseModel(Model): """A base model that will use our MySQL database""" class Meta: database = db class LightingType(BaseModel): lighting_type_id = PrimaryKeyField() lighting_type = CharField() class Meta: db_table = 'LightingType' class LightingTimes(BaseModel): lighting_times_id = PrimaryKeyField() lighting_type_id = ForeignKeyField(LightingType, db_column='lighting_type_id') lighting = BooleanField() lighting_time = CharField() class Meta: db_table = 'LightingTimes' class Plants(BaseModel): plant_id = PrimaryKeyField() plant_name = CharField() humidity_max = FloatField() temp_min = FloatField() temp_max = FloatField() ph_target = FloatField() seedling_days = SmallIntegerField() vege_days = SmallIntegerField() flower_days = SmallIntegerField() class Meta: db_table = 'Plants' class Stage(BaseModel): stage_id = PrimaryKeyField() stage = CharField() class Meta: db_table = 'Stage' class Grow(BaseModel): grow_id = PrimaryKeyField() start_date = DateField(default=datetime.date.today()) end_date = DateField() is_active = BooleanField() lighting_type_id = ForeignKeyField(LightingType, db_column='lighting_type_id') stage_id = ForeignKeyField(Stage, db_column='stage_id') class Meta: db_table = 'Grow' class GrowLog(BaseModel): log_id = PrimaryKeyField() reading_time = DateTimeField(default=datetime.datetime.now()) temp = FloatField() humidity = FloatField() ph = FloatField() ec = FloatField() gallons = FloatField() grow_id = ForeignKeyField(Grow, db_column='grow_id') class Meta: db_table = 'GrowLog' class Plants_Grow(BaseModel): plants_grow_id = PrimaryKeyField() grow_id = ForeignKeyField(Grow, db_column='grow_id') plant_id = ForeignKeyField(Plants, db_column='plant_id') class Meta: db_table = 'Plants_Grow' class PumpLog(BaseModel): pump_log_id = PrimaryKeyField() grow_id = ForeignKeyField(Grow, db_column='grow_id') dispense_time = DateTimeField(default=datetime.datetime.now()) ph_up_ml = FloatField() ph_down_ml = FloatField() tiger_bloom_ml = FloatField() big_bloom_ml = FloatField() grow_ml = FloatField() class Meta: db_table = 'PumpLog' class FeedingLog(BaseModel): feeding_log_id = PrimaryKeyField() pump_log_id = ForeignKeyField(PumpLog, db_column='pump_log_id') record = DateField(default=datetime.date.today()) class Meta: db_table = 'FeedingLog' class Flags(BaseModel): flag_id = PrimaryKeyField() flag_name = CharField() flag = BooleanField() last_changed = DateTimeField(default=datetime.datetime.now()) class Meta: db_table = 'Flags'<file_sep>/controller/water_system.py from controller import GardenDb import sys sys.path.append('/home/pi/.local/lib/python3.5/site-packages') import Adafruit_ADS1x15 import wiringpi import time import numpy import logging ADC = Adafruit_ADS1x15.ADS1115() FLORAGROW_PIN = 7 FLORABLOOM_PIN = 15 FLORAMICRO_PIN = 16 PH_UP_PIN = 0 PH_DOWN_PIN = 1 ML_PER_SEC = 5 / 3 PERCENT_ERROR = .035 logger = logging.getLogger('garden.controller.water_system') def _convert_adc_volts(reading, fsr): """fsr: full scale range of adc""" logger.info('converting adc value to voltage') adc_resolution = 32767 return reading * (fsr / adc_resolution) def _percent_error(ideal, actual): return abs(ideal - actual) / abs(ideal) def _water_lvl(): def voltage_to_resistance(voltage): return -(voltage * 560) / (voltage - 5) def resistance_to_inches(res): return (-7/1100)*res+(116/11) logger.info('reading water lvl from adc') reading = [] for i in range(10): reading.append(ADC.read_adc(2, 1)) time.sleep(0.25) volts = _convert_adc_volts(numpy.mean(reading), 4.096) logger.info(str(volts) + 'V') resistance = voltage_to_resistance(volts) return resistance_to_inches(resistance) def gallons(): logger.info('converting water level to gallons') gallons_per_cubic_inch = 0.004329 volume = 15.9 * 23.9 * _water_lvl() return volume * gallons_per_cubic_inch def ph(): def volts_to_ph(volts): return 0.008217 * (volts**2) + 3.562 * volts - 0.191 logger.info('reading ph voltage from adc') reading = [] for i in range(10): reading.append(ADC.read_adc(0, 1)) time.sleep(0.25) volts = _convert_adc_volts(numpy.mean(reading), 4.096) logger.info(str(volts) + 'V') return volts_to_ph(volts) def ec(): def volts_to_ec(volts): return 9.938992 * volts - 0.169312 logger.info('reading ec from adc') reading = [] for i in range(10): reading.append(ADC.read_adc(1, 1)) time.sleep(0.5) volts = _convert_adc_volts(numpy.mean(reading), 4.096) logger.info(str(volts) + 'V') return volts_to_ec(volts) def record_nutrient_log(grow, tiger, big_bloom, big_grow): GardenDb.db.get_conn() pump_log = GardenDb.PumpLog.create(grow_id=grow, tiger_bloom_ml=tiger, big_bloom_ml=big_bloom, grow_ml=big_grow) pump_log.save() q = GardenDb.FeedingLog.insert(pump_log_id=pump_log) q.execute() GardenDb.db.close() def pump(pin, amount): dispense_time = amount / ML_PER_SEC wiringpi.digitalWrite(pin, 0) time.sleep(dispense_time) wiringpi.digitalWrite(pin, 1) def dispense_ph(ideal_ph, active_grow): def record_pump_log(amount, up_or_down): """up_or_down is a boolean True for up False for down""" GardenDb.db.get_conn() if up_or_down: GardenDb.PumpLog.insert(grow_id=active_grow, ph_up_ml=amount).execute() else: GardenDb.PumpLog.insert(grow_id=active_grow, ph_down_ml=amount).execute() logger.info('recorded amount dispensed to db') GardenDb.db.close() logger.info('checking current ph against ideal') reading = ph() if _percent_error(ideal_ph, reading) <= PERCENT_ERROR: # if ph is within error% of ideal do nothing logger.info('ph is within percent error. no action') pass else: # dispense 1 ml of solution per gallon logger.info('dispensing 1 ml of solution per gallon') if abs(reading-ideal_ph) > 2: if reading < 9: ml_per_gallon = 2 else: ml_per_gallon = 1 liquid = gallons() if reading < ideal_ph: pump(PH_UP_PIN, liquid * ml_per_gallon) record_pump_log(liquid * ml_per_gallon, True) else: pump(PH_DOWN_PIN, liquid * ml_per_gallon) record_pump_log(liquid * ml_per_gallon, False) def pump_nutrients_full_feeding(active_grow): """full_feeding try to pump a total dose false to adjsut""" tea_spoon_ml = 5 logger.info('dispense a full feeding dosage') # Calculate amount and time for flowering state floraGro_tea_per_gal = 1 floraBloom_tea_per_gal = 1 floraMicro_tea_per_gal = 1 liquid = gallons() floraGro_dispense = (floraGro_tea_per_gal * tea_spoon_ml * liquid) floraBloom_dispense = (floraBloom_tea_per_gal * tea_spoon_ml * liquid) floraMicro_dispense = (floraMicro_tea_per_gal * tea_spoon_ml * liquid) # dispense tiger bloom pump(FLORAGROW_PIN, floraGro_dispense) # dispense big bloom pump(FLORABLOOM_PIN,floraBloom_dispense) # dispense big grow pump(FLORAMICRO_PIN, floraMicro_dispense) # log amount dispensed record_nutrient_log(active_grow, floraGro_dispense, floraBloom_dispense, floraMicro_dispense) def pump_nutrients_adjust(ideal_ec, active_grow): tea_spoon_ml = 5 reading = ec() if _percent_error(ideal_ec, reading) < PERCENT_ERROR: pass else: floraGrow_tea_per_gal = 0.5 floraBloom_tea_per_gal = 0.5 floraMicro_tea_per_gal = 0.5 liquid = gallons() floraGrow_dispense = (floraGrow_tea_per_gal * tea_spoon_ml * liquid) floraBloom_dispense = (floraBloom_tea_per_gal * tea_spoon_ml * liquid) floraMicro_dispense = (floraMicro_tea_per_gal * tea_spoon_ml * liquid) # dispense tiger bloom pump(FLORAGROW_PIN, floraGrow_dispense) # dispense big bloom pump(FLORABLOOM_PIN, floraBloom_dispense) # dispense big grow pump(FLORAMICRO_PIN, floraMicro_dispense) # log amount dispensed record_nutrient_log(active_grow, floraGrow_dispense, floraBloom_dispense, floraMicro_dispense)<file_sep>/controller/environment_system.py import sys sys.path.append('/home/pi/.local/lib/python3.5/site-packages') from aosong import am2315 import wiringpi import logging SENSOR = am2315.Sensor() FAN_PIN = 3 LED_PIN = 2 DEHUMIDIFIER_PIN = 4 logger = logging.getLogger('garden.controller.environment_system') def humidity_temp(): logger.info('reading from temp humidity sensor') while True: try: reading = SENSOR.data() except (AssertionError, TypeError): continue logger.info('bad reading assertion or type error') else: if reading is None: logger.info('bad reading nonetype') continue else: break logger.info('reading successful') return reading def lights_on(): logger.info('turning lights on') wiringpi.digitalWrite(LED_PIN, 0) def lights_off(): logger.info('turning lights off') wiringpi.digitalWrite(LED_PIN, 1) def dehumidifier_on(): logger.info('turning dehumidifier on') wiringpi.digitalWrite(DEHUMIDIFIER_PIN, 0) def dehumidifier_off(): logger.info('turning dehumidifier off') wiringpi.digitalWrite(DEHUMIDIFIER_PIN, 1) def fan_on(): logging.info('turning fan on') wiringpi.digitalWrite(FAN_PIN, 0) def fan_off(): logging.info('turning fan off') wiringpi.digitalWrite(FAN_PIN, 1) <file_sep>/controller/Gardendb.sql DROP DATABASE IF EXISTS garden; CREATE DATABASE garden; USE garden; CREATE TABLE LightingType ( lighting_type_id int NOT NULL AUTO_INCREMENT, lighting_type VARCHAR(255) NOT NULL, PRIMARY KEY(lighting_type_id) ); CREATE TABLE LightingTimes ( lighting_times_id int NOT NULL AUTO_INCREMENT, lighting_type_id int, lighting BOOL, lighting_time VARCHAR(5), PRIMARY KEY(lighting_times_id), FOREIGN KEY (lighting_type_id) REFERENCES LightingType(lighting_type_id) ); CREATE TABLE Plants ( plant_id int NOT NULL AUTO_INCREMENT, plant_name varchar(255) NOT NULL, humidity_max float NOT NULL, temp_min float NOT NULL, temp_max float NOT NULL, ph_target float NOT NULL, seedling_days int NOT NULL, vege_days int NOT NULL, flower_days int NOT NULL, PRIMARY KEY (plant_id) ); CREATE TABLE Stage ( stage_id int NOT NULL AUTO_INCREMENT, stage varchar(255), PRIMARY KEY(stage_id) ); CREATE TABLE Grow ( grow_id int NOT NULL AUTO_INCREMENT, start_date DATE NOT NULL, end_date DATE, stage_id int, lighting_type_id int NOT NULL, is_active BOOL, PRIMARY KEY (grow_id), FOREIGN KEY (stage_id) REFERENCES Stage(stage_id), FOREIGN KEY (lighting_type_id) REFERENCES LightingType(lighting_type_id) ); CREATE TABLE Plants_Grow ( plants_grow_id int NOT NULL AUTO_INCREMENT, grow_id int NOT NULL, plant_id int NOT NULL, PRIMARY KEY (plants_grow_id), FOREIGN KEY (grow_id) REFERENCES Grow(grow_id), FOREIGN KEY (plant_id) REFERENCES Plants(plant_id) ); CREATE TABLE GrowLog ( log_id int NOT NULL AUTO_INCREMENT, reading_time DATETIME NOT NULL, temp float NOT NULL, humidity float NOT NULL, ph float NOT NULL, ec float NOT NULL, gallons float NOT NULL, grow_id int NOT NULL, PRIMARY KEY (log_id), FOREIGN KEY (grow_id) REFERENCES Grow(grow_id) ); CREATE TABLE PumpLog ( pump_log_id int NOT NULL AUTO_INCREMENT, grow_id int NOT NULL, dispense_time DATETIME NOT NULL, ph_up_ml FLOAT, ph_down_ml FLOAT, tiger_bloom_ml FLOAT, big_bloom_ml FLOAT, grow_ml FLOAT, PRIMARY KEY (pump_log_id), FOREIGN KEY (grow_id) REFERENCES Grow(grow_id) ); CREATE TABLE Flags ( flag_id int NOT NULL AUTO_INCREMENT, flag_name VARCHAR(255) NOT NULL, flag BOOL NOT NULL, last_changed DATETIME NOT NULL, PRIMARY KEY (flag_id) ); INSERT INTO LightingType (lighting_type) VALUES ('12-12'); SET @lighting_12 = LAST_INSERT_ID(); INSERT INTO LightingType(lighting_type) VALUES ('24 hour'); SET @lighting_24 = LAST_INSERT_ID(); INSERT INTO LightingType(lighting_type) VALUES ('6-2') ; SET @lighting_62 = LAST_INSERT_ID(); INSERT INTO LightingTimes (lighting_type_id, lighting, lighting_time) VALUES (@lighting_12, TRUE, '10:00'); INSERT INTO LightingTimes (lighting_type_id, lighting, lighting_time) VALUES (@lighting_12, FALSE, '22:00'); INSERT INTO LightingTimes (lighting_type_id, lighting, lighting_time) VALUES (@lighting_62, TRUE, '10:00'); INSERT INTO LightingTimes (lighting_type_id, lighting, lighting_time) VALUES (@lighting_62, FALSE, '16:00'); INSERT INTO LightingTimes (lighting_type_id, lighting, lighting_time) VALUES (@lighting_62, TRUE, '18:00'); INSERT INTO LightingTimes (lighting_type_id, lighting, lighting_time) VALUES (@lighting_62, False, '00:00'); INSERT INTO LightingTimes (lighting_type_id, lighting, lighting_time) VALUES (@lighting_62, TRUE, '2:00'); INSERT INTO LightingTimes (lighting_type_id, lighting, lighting_time) VALUES (@lighting_62, FALSE, '8:00'); INSERT INTO Plants (plant_name, humidity_max, temp_min, temp_max, ph_target,seedling_days,vege_days,flower_days) VALUES ('Lettuce', 50, 60, 75, 6.5, 17, 28, 0); SET @plant_id = LAST_INSERT_ID(); INSERT INTO Stage (stage) VALUES ('Seedling'); INSERT INTO Stage (stage) VALUES ('Vegetative'); SET @stage_id = LAST_INSERT_ID(); INSERT INTO Stage (stage) VALUES ('Flowering'); INSERT INTO Grow (start_date, is_Active, stage_id, lighting_type_id) VALUES (CURRENT_DATE, TRUE, @stage_id, @lighting_62); SET @grow_id = LAST_INSERT_ID(); INSERT INTO Plants_Grow (grow_id, plant_id) VALUES (@grow_id, @plant_id); INSERT INTO Flags (flag_name, flag, last_changed) VALUES ('water low', FALSE, CURRENT_DATE);
2711816ac271b0febfc27b1203b6f9e59bae17d6
[ "Markdown", "SQL", "Python" ]
7
Python
tnvu210/UTD-Senior-Project
1ca4455e462ccaab5bf5c56aa0b3cda0cd240efe
edd3593589764d86c2ea2730d0b90088f5fda8e7
refs/heads/master
<repo_name>IvanPJF/job4j_rest<file_sep>/db/update_001.sql drop table if exists person; drop table if exists employee; create table employee ( id serial, first_name varchar(2000), last_name varchar(2000), inn bigint unique not null, date_employment timestamp not null default now(), primary key (id) ); create table person ( id serial, login varchar(2000) unique not null, password varchar(2000), employee_id integer, primary key (id) ); insert into employee(first_name, last_name, inn) values ('John', 'Connor', 111), ('Man', 'Manning', 222); insert into person (login, password, employee_id) values ('root', '123', (select id from employee where inn = 111)), ('other', '123', (select id from employee where inn = 111)), ('man', '123', (select id from employee where inn = 222));<file_sep>/README.md # job4j_rest RESTful [![Build Status](https://travis-ci.org/IvanPJF/job4j_rest.svg?branch=master)](https://travis-ci.org/IvanPJF/job4j_rest)
2db25669023a7460c43b5a999734910a549c2633
[ "Markdown", "SQL" ]
2
SQL
IvanPJF/job4j_rest
baed55e8b51c8f32da8bc312f75df56fc3a0896d
1408b2c2dc46ffe88d4b3166264dd1bd33b28ace
refs/heads/master
<repo_name>dksingh481/XebiaAssignment<file_sep>/src/com/xebia/yakshop/parser/XMLParser.java package com.xebia.yakshop.parser; import java.io.InputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import com.xebia.yakshop.model.Herd; public class XMLParser implements Parser{ private Herd herd; @Override public Herd parse(InputStream ins) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(Herd.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); herd = (Herd) unmarshaller.unmarshal(ins); return herd; } } <file_sep>/src/com/xebia/yakshop/parser/ParserFactory.java package com.xebia.yakshop.parser; public class ParserFactory { public static Parser getXMLParser() { return new XMLParser(); } } <file_sep>/src/com/xebia/yakshop/main/YakShop.java package com.xebia.yakshop.main; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import com.xebia.yakshop.model.Herd; import com.xebia.yakshop.model.LabYak; import com.xebia.yakshop.parser.ParserFactory; import com.xebia.yakshop.service.IService; import com.xebia.yakshop.service.ServiceImpl; import com.xebia.yakshop.util.Util; public class YakShop { public static void main(String args[]) throws IOException{ InputStream ins=null; try { if(args.length<2) { throw new IllegalArgumentException("Invalid number of arguments, Use: java YakShop 'file path' 'number of days'"); } ins=new FileInputStream(new File(args[0])); if(!Util.isNumeric(args[1])) { throw new NumberFormatException("Second argument should be numeric"); } Integer T=Integer.parseInt(args[1]); Herd herd=ParserFactory.getXMLParser().parse(ins); IService service=new ServiceImpl(); System.out.println("In Stock:"); System.out.printf("%10.3f liters of milk\n", service.getMilkProduction(herd, T)); System.out.printf("%10d skins of wool\n", service.getSkinOfWool(herd, T)); System.out.println("Herd:"); for(LabYak labyak:herd.getLabYaks()) { System.out.printf("%10s %.2f years old \n", labyak.getName(),service.getYakFutureAge(labyak, T)); } }catch(IllegalArgumentException exp) { exp.printStackTrace(); System.out.println("\nSample: java YakShop herd.xml 13"); }catch(FileNotFoundException exp) { exp.printStackTrace(); }catch(Exception exp) { exp.printStackTrace(); }finally { if(ins!=null) { ins.close(); } } } } <file_sep>/README.md # XebiaAssignment #To Run: java YakShop herd.xml 13 #Assignment Input and Output Input herd.xml: <herd> <labyak name="Betty-1" age="4" sex="f"/> <labyak name="Betty-2" age="8" sex="f"/> <labyak name="Betty-3" age="9.5" sex="f"/> </herd> N.B. The age is given in standard Yak years Your program should take 2 parameters: 1. The XML file to read 2. An integer T, representing the elapsed time in days. N.B. T=13 means that day 12 has elapsed, but day 13 has yet to begin Output for T = 13: In Stock: 1104.480 liters of milk 3 skins of wool Herd: Betty-1 4.13 years old Betty-2 8.13 years old Betty-3 9.63 years old Output for T = 14: In Stock: 1188.810 liters of milk 4 skins of wool Herd: Betty-1 4.14 years old Betty-2 8.14 years old Betty-3 9.64 years old <file_sep>/src/com/xebia/yakshop/parser/Parser.java package com.xebia.yakshop.parser; import java.io.InputStream; import javax.xml.bind.JAXBException; import com.xebia.yakshop.model.Herd; public interface Parser { public Herd parse(InputStream ins) throws JAXBException; } <file_sep>/src/com/xebia/yakshop/service/ServiceImpl.java package com.xebia.yakshop.service; import com.xebia.yakshop.model.Herd; import com.xebia.yakshop.model.LabYak; public class ServiceImpl implements IService { @Override public Double getMilkProduction(Herd herd, Integer T) { Double milk=0.0; for(LabYak labyak:herd.getLabYaks()) { if(labyak.getSex().equalsIgnoreCase("f")) { long futureAge=Math.round(getYakFutureAge(labyak,T)*100); long currentAge=Math.round(labyak.getAge()*100); for(long i=currentAge;i<futureAge;i++) { milk=milk+(50-i*0.03); } } } return milk; } @Override public Integer getSkinOfWool(Herd herd, Integer T) { Integer skin=0; for(LabYak labyak:herd.getLabYaks()) { long currentAge=Math.round(labyak.getAge()*100); if(currentAge>100) { skin++; long futureAge=Math.round(getYakFutureAge(labyak,T)*100); long dayForSkin=Math.round(8+currentAge*0.01); while(currentAge+dayForSkin+1<futureAge) { currentAge=currentAge+dayForSkin; skin++; } } } return skin; } @Override public Double getYakFutureAge(LabYak labyak, Integer T) { Double age=0.0; age=(labyak.getAge()*100+T)/100; if(age>10.0) { return 10.0; } return age; } }
5148ee0ce0c6457c0a4fb7b1e4ce2961d8c2253e
[ "Markdown", "Java" ]
6
Java
dksingh481/XebiaAssignment
66cc46452f45420f8c995d13a34653468a4760f9
40c2ea8964d56d36c12ff54de4100faa16ef8916
refs/heads/master
<file_sep>CMAKE_MINIMUM_REQUIRED(VERSION 2.8) ENABLE_TESTING(TRUE) find_package(Qt4 REQUIRED) add_definitions(${QT_DEFINITIONS}) SET(${QT_USE_QTTEST} TRUE) include(${QT_USE_FILE}) #include_directories("../../src/backend") #set(PARSETEST_SRCS parsetest.cpp) #QT4_AUTOMOC(${PARSETEST_SRCS}) ADD_EXECUTABLE(ParseTest parsetest.cpp YmpParser.cpp package.cpp repository.cpp) TARGET_LINK_LIBRARIES(ParseTest ${QT_LIBRARIES} ${QT_QTTEST_LIBRARY} ${PARSETEST_SRCS}) ADD_TEST(NAME ParseTest COMMAND ParseTest) <file_sep>project(backend) cmake_minimum_required(VERSION 2.8) find_package(Qt4 REQUIRED) include(${QT_USE_FILE}) add_definitions(${QT_DEFINITIONS}) set(backend_SOURCES package.cpp repository.cpp YmpParser.cpp) #add_executable(backend ${QT_LIBRARIES} ${backend_SOURCES}) target_link_libraries(backend ${QT_LIBRARIES}) include_directories(${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${qt4_include_dir}) <file_sep>project(oneclickui) cmake_minimum_required(VERSION 2.8) find_package(Qt4 REQUIRED) include(${QT_USE_FILE}) add_definitions(${QT_DEFINITIONS}) set(oneclickui_SOURCES main.cpp mainwindow.cpp firstscreen.cpp settings.cpp) set(oneclickui_HEADERS mainwindow.h firstscreen.h settings.h) QT4_WRAP_CPP(oneclickui_HEADERS_MOC ${oneclickui_HEADERS}) add_executable(oneclickui ${QT_LIBRARIES} ${oneclickui_SOURCES} ${oneclickui_HEADERS} ${oneclickui_HEADERS_MOC}) target_link_libraries(oneclickui ${QT_LIBRARIES}) include_directories(${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${qt4_include_dir}) <file_sep>#ifndef YMPPARSER_H #define YMPPARSER_H #include <QXmlStreamReader> #include <QList> #include "package.h" #include "repository.h" namespace OCI{ class YmpParser { public: YmpParser( const QString& ympfile ); void parse(); QList< OCI::Package* > packages() const; QList< OCI::Repository* > repositories() const; void printRepoList(); void printPackageList(); private: QList< OCI::Package* > packageList; QList< OCI::Repository* > repositoryList; QString fileName; }; }; #endif <file_sep>#include "mainwindow.h" MainWindow::MainWindow(QObject *parent) { m_info = new QLabel( "This installer will install and download packages" ); QVBoxLayout *mainLayout = new QVBoxLayout; m_stageWidget = new FirstScreen; mainLayout->addWidget( m_info ); mainLayout->addWidget( m_stageWidget ); setLayout( mainLayout ); setWindowTitle( "One Click Install" ); show(); } <file_sep>#include <QApplication> #include "YmpParser.h" int main(int argc,char *argv[]) { QApplication app(argc,argv); YmpParser x(argv[1]); x.parse(); x.printRepoList(); x.printPackageList(); return 0; } <file_sep>#ifndef REPOSITORY_H #define REPOSITORY_H #include <QString> namespace OCI{ class Repository { public: //Repository(QString recommended,QString name,QString summary,QString description,QString url); Repository(); QString name() const; QString description() const; QString summary() const; QString url() const; QString recommended() const; void setRecommended( const QString& recommmended ); void setName( const QString& name ); void setDescription( const QString& description ); void setSummary( const QString& summary ); void setUrl( const QString& url ); private: QString m_recommended; QString m_name; QString m_description; QString m_summary; QString m_url; }; } #endif <file_sep>#include <iostream> #include <QApplication> #include <QXmlStreamReader> #include <QFile> #include <QList> #include <QDebug> #include <QStringList> #include "repository.h" #include "package.h" #include <QUrl> #include <zypp/RepoManager.h> #include <zypp/base/Algorithm.h> #include <zypp/ResFilters.h> #include <zypp/ResStatus.h> #include <zypp/ResPool.h> #include <zypp/target/rpm/RpmDb.h> #include <zypp/target/TargetException.h> #include <zypp/ZYppCommit.h> #include <zypp/base/Regex.h> #include <zypp/sat/WhatProvides.h> #include <zypp/ZYppFactory.h> namespace zypp { typedef std::list< PoolItem > PoolItemList; } int main( int argc,char *argv[] ) { QApplication app( argc,argv ); QFile file( argv[1] ); QList< Package* > packageList; QList< Repository* > repositoryList; zypp::RepoManager rman; if( !file.open( QIODevice::ReadOnly ) ){ qDebug() << "Could not open File"; return 0; } QString fileData( file.readAll() ); //qDebug()<<fileData; QXmlStreamReader xml( fileData ); while( !xml.atEnd() && xml.name() != "software" ){ xml.readNextStartElement(); if( xml.name() == "repository" && !xml.isEndElement() ){ Repository *repo = new Repository; //Set whether recommended or not repo->setRecommended( xml.attributes().value( "recommended" ).toString() ); xml.readNextStartElement(); //Read the Name of the Repository if( xml.name() == "name" ){ //qDebug()<<"Name"<<xml.readElementText(); repo->setName( xml.readElementText() ); } xml.readNextStartElement(); //Read the Summary if( xml.name() == "summary" ){ //qDebug()<<"Summary"<<xml.readElementText(); repo->setSummary( xml.readElementText() ); } xml.readNextStartElement(); //Read Description if( xml.name() == "description" ){ //qDebug()<<"Description"<<xml.readElementText(); repo->setDescription( xml.readElementText() ); } xml.readNextStartElement(); //Read Url if(xml.name()=="url"){ repo->setUrl( xml.readElementText() ); } //Add Repository to the List or Repositories repositoryList.append( repo ); } } while( !xml.atEnd() && !( xml.name() == "software" && xml.isEndElement() ) ){ xml.readNextStartElement(); if( xml.name() =="name" && !xml.isEndElement() ){ Package *pkg = new Package; //Read Element Text pkg->setName( xml.readElementText() ); xml.readNextStartElement(); //Read Summary if( xml.name() == "summary" ) pkg->setSummary( xml.readElementText() ); xml.readNextStartElement(); //Read Description if( xml.name() == "description" ) pkg->setDescription(xml.readElementText()); packageList.append( pkg ); } } qDebug() << "***List of Repositories***" ; foreach( Repository *repo,repositoryList ){ qDebug() << repo->name(); qDebug() << repo->recommended(); qDebug() << repo->summary(); qDebug() << repo->description(); qDebug() << repo->url(); //Add Repository /*zypp::RepoInfo repoinfo; std::cout<<"Std Url is "<<repo->url().toStdString()<<std::endl; repoinfo.addBaseUrl(zypp::Url(repo->url().toStdString())); repoinfo.setAlias(repo->url().toStdString()); repoinfo.setGpgCheck(false); rman.addRepository(repoinfo); rman.refreshMetadata(repoinfo,zypp::RepoManager::RefreshIfNeeded); rman.buildCache(repoinfo); rman.loadFromCache(repoinfo);*/ } qDebug() << "***List of Packages***" ; foreach( Package *pack,packageList ){ qDebug() << pack->name(); qDebug() << pack->summary(); qDebug() << pack->description(); } zypp::ResPoolProxy selectablePool( zypp::ResPool::instance().proxy() ); zypp::ui::Selectable::Ptr s = zypp::ui::Selectable::get( zypp::ResKind::package,packageList.at(0)->name().toStdString() ); for_(avail_it,s->availableBegin(), s->availableEnd() ){ s->setCandidate( *avail_it ); s->setToInstall( zypp::ResStatus::USER ); } return 0; } <file_sep>#ifndef PACKAGE_H #define PACKAGE_H #include <QString> namespace OCI{ class Package { public: Package( QString name, QString summary, QString description ); Package(); QString name() const; QString summary() const; QString description() const; void setName( const QString& name ); void setSummary( const QString& summary ); void setDescription( const QString& description ); private: QString m_name; QString m_summary; QString m_description; }; } #endif <file_sep>#include "repository.h" /*Repository::Repository(QString recommended,QString name,QString summary,QString description,QString url) { m_recommended = recommended; m_name = name; m_summary = summary; m_description = description; m_url = url; }*/ OCI::Repository::Repository() { } QString OCI::Repository::recommended() const { return m_recommended; } QString OCI::Repository::name() const { return m_name; } QString OCI::Repository::summary() const { return m_summary; } QString OCI::Repository::description() const { return m_description; } QString OCI::Repository::url() const { return m_url; } void OCI::Repository::setName( const QString& name ) { m_name = name; } void OCI::Repository::setRecommended( const QString& recommended ) { m_recommended = recommended; } void OCI::Repository::setSummary( const QString& summary ) { m_summary = summary; } void OCI::Repository::setDescription( const QString& description ) { m_description = description; } void OCI::Repository::setUrl( const QString& url ) { m_url = url; } <file_sep>#ifndef MAINWINDOW_H #define MAINWINDIW_H #include <QDialog> #include <QLabel> #include <QVBoxLayout> #include "firstscreen.h" class MainWindow : public QDialog { public: MainWindow( QObject *parent = 0 ); private: QLabel *m_info; QWidget *m_stageWidget; //This will load the corresponding widget to the layout depending on the stage of the installation }; #endif <file_sep>#ifndef FIRSTSCREEN_H #define FIRSTSCREEN_H #include <QWidget> #include <QPushButton> #include <QLabel> #include <QVBoxLayout> #include <QComboBox> #include <QHBoxLayout> #include "settings.h" class FirstScreen : public QWidget { Q_OBJECT private: QLabel *m_warning; QPushButton *m_trust; QPushButton *m_settings; QPushButton *m_cancel; QPushButton *m_install; public: FirstScreen( QObject *parent = 0 ); private slots: void showSettings(); }; #endif <file_sep>#ifndef PARSETEST_H #define PARSETEST_H #include "YmpParser.h" #include "repository.h" #include "package.h" class ParseTest : public QObject { Q_OBJECT private slots: void parse(); }; #endif <file_sep>#include "package.h" /*Package::Package(QString name,QString summary,QString description) { m_name = name; m_summary = summary; m_description = description; }*/ OCI::Package::Package() { } QString OCI::Package::name() const { return m_name; } QString OCI::Package::summary() const { return m_summary; } QString OCI::Package::description() const { return m_description; } void OCI::Package::setName( const QString& name ) { m_name = name; } void OCI::Package::setSummary( const QString& summary ) { m_summary = summary; } void OCI::Package::setDescription( const QString& description ) { m_description = description; } <file_sep>#include <QApplication> #include "mainwindow.h" int main( int argc, char *argv[] ) { QApplication app( argc,argv ); MainWindow m; return app.exec(); } <file_sep>#include "firstscreen.h" FirstScreen::FirstScreen( QObject *parent ) { //Create Layouts QVBoxLayout *warningLayout = new QVBoxLayout; QVBoxLayout *installLayout = new QVBoxLayout; QHBoxLayout *buttonLayout = new QHBoxLayout; QVBoxLayout *mainLayout = new QVBoxLayout; //Create Interface Elemenets m_warning = new QLabel( "This is a warning Message" ); //This should be done only if repositories to be added need to be trusted m_trust = new QPushButton( "Trust" ); // Same as above m_settings = new QPushButton( "Settings" ); m_cancel = new QPushButton( "Cancel" ); m_install = new QPushButton( "Install" ); //Add Elements to corresponding Layouts; warningLayout->addWidget( m_warning ); warningLayout->addWidget( m_trust ); buttonLayout->addWidget( m_settings ); buttonLayout->addWidget( m_cancel ); buttonLayout->addWidget( m_install ); mainLayout->addLayout( warningLayout ); mainLayout->addLayout( installLayout ); mainLayout->addLayout( buttonLayout ); //Signal Slot connections QObject::connect( m_settings,SIGNAL( clicked() ),this, SLOT( showSettings() ) ); setLayout( mainLayout ); show(); } void FirstScreen::showSettings() { new Settings(); } <file_sep>project(src) cmake_minimum_required(VERSION 2.8) add_subdirectory(ui) #add_subdirectory(backend)<file_sep>#include "YmpParser.h" #include <QDebug> #include <QFile> OCI::YmpParser::YmpParser( const QString& ympfile ) { fileName = ympfile; } QList< OCI::Package* > OCI::YmpParser::packages() const { return packageList; } QList< OCI::Repository* > OCI::YmpParser::repositories() const { return repositoryList; } void OCI::YmpParser::parse() { QFile file( fileName ); if( !file.open( QIODevice::ReadOnly ) ){ qDebug()<<"Could not open File"; return; } QString fileData( file.readAll() ); //qDebug()<<fileData; QXmlStreamReader xml( fileData ); while( !xml.atEnd() && xml.name() != "software" ){ xml.readNextStartElement(); if( xml.name()=="repository" && !xml.isEndElement() ){ OCI::Repository *repo = new OCI::Repository; //Set whether recommended or not repo->setRecommended( xml.attributes().value( "recommended" ).toString() ); xml.readNextStartElement(); //Read the Name of the Repository if( xml.name() == "name" ){ //qDebug()<<"Name"<<xml.readElementText(); repo->setName( xml.readElementText() ); } xml.readNextStartElement(); //Read the Summary if( xml.name()=="summary" ){ //qDebug()<<"Summary"<<xml.readElementText(); repo->setSummary( xml.readElementText() ); } xml.readNextStartElement(); //Read Description if( xml.name() == "description" ){ //qDebug()<<"Description"<<xml.readElementText(); repo->setDescription( xml.readElementText() ); } xml.readNextStartElement(); //Read Url if( xml.name() == "url" ){ repo->setUrl( xml.readElementText() ); } //Add Repository to the List or Repositories repositoryList.append( repo ); } } while( !xml.atEnd() && !( xml.name() == "software" && xml.isEndElement() ) ){ xml.readNextStartElement(); if( xml.name() == "name" && !xml.isEndElement() ){ OCI::Package *pkg = new Package; //Read Element Text pkg->setName( xml.readElementText() ); xml.readNextStartElement(); //Read Summary if( xml.name() == "summary" ) pkg->setSummary( xml.readElementText() ); xml.readNextStartElement(); //Read Description if( xml.name() == "description" ) pkg->setDescription( xml.readElementText() ); packageList.append( pkg ); } } } void OCI::YmpParser::printRepoList() { foreach( OCI::Repository* repo, repositoryList ){ qDebug() << repo->name(); qDebug() << repo->description(); qDebug() << repo->url(); qDebug() << repo->summary(); qDebug() << repo->recommended(); } } void OCI::YmpParser::printPackageList() { foreach( OCI::Package* pack, packageList ){ qDebug() << pack->name(); qDebug() << pack->description(); qDebug() << pack->summary(); } } <file_sep>#ifndef SETTINGS_H #define SETTINGS_H #include <QDialog> #include <QPushButton> #include <QLabel> #include <QCheckBox> #include <QVBoxLayout> class Settings : public QDialog { public: Settings( QObject *parent = 0 ); private: QPushButton *m_confirm; QCheckBox *m_subscribe; QCheckBox *m_trust; QPushButton *m_close; QLabel *m_repos; }; #endif <file_sep>#include "settings.h" Settings::Settings( QObject *parent ) { //Create Layouts QVBoxLayout *mainLayout = new QVBoxLayout; //Create Interface Elements m_repos = new QLabel( "Repository Sources" ); m_subscribe = new QCheckBox( "Subscribe to new Repository Sources automatically", this ); m_trust = new QCheckBox( "Trust and import repository public keys by default", this ); m_close = new QPushButton( "Close" ); //Add elements to Layout mainLayout->addWidget( m_repos ); mainLayout->addWidget( m_subscribe ); mainLayout->addWidget( m_trust ); mainLayout->addWidget( m_close ); setLayout( mainLayout ); setWindowTitle( "One Click Install Settings" ); show(); } <file_sep>#include <QtTest/QTest> #include "parsetest.h" void ParseTest::parse() { OCI::YmpParser parser("geany.ymp"); parser.parse(); QList<OCI::Package*> packageList = parser.packages(); QList<OCI::Repository*> repositoryList = parser.repositories(); QCOMPARE(packageList.at(0)->name(),QString("geany")); QCOMPARE(repositoryList.at(0)->name(),QString("openSUSE:12.1")); } QTEST_MAIN(ParseTest) #include "parsetest.moc"
09d99d5378a7bcc5471fad5531c5404d98965f4e
[ "CMake", "C++" ]
21
CMake
saurabhsood91/one-click-installer
7786d24b8e796936067d7efe0cca7cdf8564a235
2c493a77bbc6ba616b09439a9981c37efef9625b
refs/heads/master
<file_sep>All documents can be stored into a mongodb collection.and then we can perform any type of operation we want.<file_sep> /** * Module dependencies. */ var express = require('express') , routes = require('./routes') , fs = require('fs') , user = require('./routes/user') , http = require('http') ,request = require("request") , jf = require('jsonfile') , util = require('util') , path = require('path'); var app = express(); var mongoose = require('mongoose'); // all environments var db = mongoose.connect('mongodb://localhost/mcafee'); var schema = mongoose.Schema({key : JSON}); //var db = mongoose.connect('mongodb://localhost/mcafee'); app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/users', user.list); var url = 'http://mcafee.0x10.info/api/app?type=json'; var documents=''; request({ url: url, json: false }, function (error, response, body) { if (!error && response.statusCode === 200) { var destination = fs.createWriteStream('./sampleData.json'); var jsonObj = JSON.parse(body); //console.log(jsonObj.length); console.log(jsonObj); var Json = mongoose.model('JSON', schema); toSave = new Json({key : jsonObj}); toSave.save(function(err){ 'use strict'; if (err) { throw err; } console.log('woo!'); }); request(url).pipe(destination); console.log('file created SuccessFully'); // Print the json response } }); app.get('/getalldocuments',function(req,res){ var file = './sampleData.json' jf.readFile(file, function(err, obj) { console.log(util.inspect(obj)) res.render('index',{ Products:obj }) }) }) app.get('/show',function(req,res){ var Json = mongoose.model('JSON', schema); Json.find(function(err,products){ if(err){res.send('not found');} res.send(products); }) }); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
d6ebf45e168fb914e4ec3553dc78700feb51eeb4
[ "JavaScript", "Text" ]
2
Text
deepak254/demo
579d7b3d91a5a3ffab595737eacebb5e36137373
d2be0e039c774f3719d311322847766375ac6126
refs/heads/master
<repo_name>Redicoding/Yazilim-Yapimi-Project<file_sep>/README.md # PROJE AMACI Alıcıyla satıcıyı buluşturan bir platform oluşturmak. Bakiye yüklenmesi ve ürün eklenmesi gibi özellikler var olup bu işlemler admin panelinde admin tarafından kontrol edilmektedir. Admin onayı olmadan bir ürün satışa çıkamaz veya bakiye kontrolü yapılamaz. Alıcı almak istediği ürünü ve adedini belirtip sistem tarafından ürün alımı gerçekleşir ve alıcı satıcı arasında bakiye transferi olur. Alıcı fiyat emri koyarak istediği ürünü istediği fiyata düşmesini bekleyip alabilir. Alıcıdan %1 komisyon kesilip admin kasasına aktarılır. Alıcı daha önce yaptığı alımları listeleyebilir ve .PDF formatında PDF çıktısı alabilir. ## Kullanılan Teknolojiler ve Programlar * C# - .NET * Visual Studio * Windows Form * Microsoft SQL Server * Entity Framework ## Content * [**GitHub Yazilim-Yapimi-Project**](https://github.com/Redicoding/Yazilim-Yapimi-Project) - Proje dosylarını inceleyebilirsiniz. <file_sep>/FrmUserPanel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; namespace Yazılım_Yapımı_Project { public partial class FrmUserPanel : Form { public FrmUserPanel() { InitializeComponent(); } YazilimYapimiEntities en = new YazilimYapimiEntities(); public string kullaniciadi; void SatısEmir() { double fiyat = Convert.ToDouble((from x in en.Tbl_Emir from y in en.Tbl_Urun where x.EmirUrun == y.URUNAD && x.EmirFiyat == y.URUNFIYAT && x.EmirDurum == false && x.EmirKilo <= y.URUNSTOK select x.EmirFiyat * x.EmirKilo).FirstOrDefault()); double kilo = Convert.ToDouble((from x in en.Tbl_Emir from y in en.Tbl_Urun where x.EmirUrun == y.URUNAD && x.EmirFiyat == y.URUNFIYAT && x.EmirDurum == false && x.EmirKilo <= y.URUNSTOK select x.EmirKilo).FirstOrDefault()); int idalici = Convert.ToInt32((from x in en.Tbl_Emir from y in en.Tbl_Urun where x.EmirUrun == y.URUNAD && x.EmirFiyat == y.URUNFIYAT && x.EmirDurum == false && x.EmirKilo <= y.URUNSTOK select x.EmirUser).FirstOrDefault()); int idsatici = Convert.ToInt32((from x in en.Tbl_Emir from y in en.Tbl_Urun where x.EmirUrun == y.URUNAD && x.EmirFiyat == y.URUNFIYAT && x.EmirDurum == false && x.EmirKilo <= y.URUNSTOK select y.KULLANICI).FirstOrDefault()); int idurun = Convert.ToInt32((from x in en.Tbl_Emir from y in en.Tbl_Urun where x.EmirUrun == y.URUNAD && x.EmirFiyat == y.URUNFIYAT && x.EmirDurum == false && x.EmirKilo <= y.URUNSTOK select y.Urunid).FirstOrDefault()); int idsatıs = Convert.ToInt32((from x in en.Tbl_Emir from y in en.Tbl_Urun where x.EmirUrun == y.URUNAD && x.EmirFiyat == y.URUNFIYAT && x.EmirDurum == false && x.EmirKilo <= y.URUNSTOK select x.EmirId).FirstOrDefault()); var komisyon = en.Tbl_admin.Find(1); komisyon.komisyon += (fiyat * (0.01)); en.SaveChanges(); double fiyatk = fiyat + (fiyat * (0.01)); if (fiyat != 0) { var musteri = en.Tbl_User.Find(idalici); musteri.Bakiye -= Convert.ToInt32(fiyatk); en.SaveChanges(); var satici = en.Tbl_User.Find(idsatici); satici.Bakiye += Convert.ToInt32(fiyat); en.SaveChanges(); var urun = en.Tbl_Urun.Find(idurun); urun.URUNSTOK -= kilo; en.SaveChanges(); var durum = en.Tbl_Emir.Find(idsatıs); durum.EmirDurum = true; en.SaveChanges(); } } private void FrmUserPanel_Load(object sender, EventArgs e) { SatısEmir(); var isim = from x in en.Tbl_User where x.KAd == kullaniciadi select x.Ad+ " " + x.Soyad; var bakiye = from x in en.Tbl_User where x.KAd == kullaniciadi select x.Bakiye; lblAd.Text = isim.FirstOrDefault(); lblbakiye.Text = bakiye.FirstOrDefault().ToString(); txtUyari.Text = "BAKİYE yükleme ve ÜRÜN ekleme işlemlerinin ADMİN tarafından onaylanması gerekmektedir. Buna göre işlem yapınız!!!!"; dataGridView1.DataSource = (from x in en.Tbl_Urun where x.URUNDURUM == true select new { x.Urunid, x.URUNAD, x.URUNFIYAT, x.URUNSTOK }).ToList(); string kurlar = "https://www.tcmb.gov.tr/kurlar/today.xml"; var xmldoc = new XmlDocument(); xmldoc.Load(kurlar); string usd = xmldoc.SelectSingleNode("Tarih_Date/Currency[@Kod='USD']/BanknoteSelling").InnerXml; lblUSD.Text = usd; string str = xmldoc.SelectSingleNode("Tarih_Date/Currency[@Kod='GBP']/BanknoteSelling").InnerXml; lblSTR.Text = str; string jpy = xmldoc.SelectSingleNode("Tarih_Date/Currency[@Kod='JPY']/BanknoteSelling").InnerXml; lblJPY.Text = jpy; } private void btnSatıs_Click(object sender, EventArgs e) { Tbl_Urun ur = new Tbl_Urun(); ur.URUNAD = txtUrunAd.Text; ur.URUNFIYAT = Convert.ToInt32(txtUrunFiyat.Text); ur.URUNSTOK = Convert.ToInt32(txtUrunStok.Text); ur.KULLANICI = (from x in en.Tbl_User where x.KAd == kullaniciadi select x.Kid).FirstOrDefault(); ur.URUNDURUM = false; en.Tbl_Urun.Add(ur); en.SaveChanges(); MessageBox.Show("Ürün Başarıyla Eklendi Admin Onayından Sonra Satışa Çıkacaktır...","Ekleme Başarılı",MessageBoxButtons.OK,MessageBoxIcon.Information); } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { int secilen = dataGridView1.SelectedCells[0].RowIndex; txtID.Text = dataGridView1.Rows[secilen].Cells[0].Value.ToString(); txtAD.Text = dataGridView1.Rows[secilen].Cells[1].Value.ToString(); } private void btnSatınAl_Click(object sender, EventArgs e) { int id = Convert.ToInt32(txtID.Text); int idmusteri = Convert.ToInt32((from x in en.Tbl_User where x.KAd == kullaniciadi select x.Kid).FirstOrDefault()); int idsatici = Convert.ToInt32((from x in en.Tbl_Urun where x.Urunid == id select x.KULLANICI).FirstOrDefault()); int kg = Convert.ToInt32(txtKG.Text); int kgfiyat = Convert.ToInt32((from x in en.Tbl_Urun where x.Urunid == id select x.URUNFIYAT).FirstOrDefault()); int urunkg = Convert.ToInt32((from x in en.Tbl_Urun where x.Urunid == id select x.URUNSTOK).FirstOrDefault()); int bakiye = Convert.ToInt32((from x in en.Tbl_User where x.KAd == kullaniciadi select x.Bakiye).FirstOrDefault()); int fiyat = kg * kgfiyat; bakiye = bakiye - fiyat; urunkg = urunkg - kg; var gnc = en.Tbl_User.Find(idmusteri); gnc.Bakiye = bakiye; en.SaveChanges(); var gnc2 = en.Tbl_Urun.Find(id); gnc2.URUNSTOK = urunkg; en.SaveChanges(); var gnc3 = en.Tbl_User.Find(idsatici); gnc3.Bakiye += fiyat; en.SaveChanges(); var yenile = from x in en.Tbl_User where x.KAd == kullaniciadi select x.Bakiye; lblbakiye.Text = yenile.FirstOrDefault().ToString(); dataGridView1.DataSource = (from x in en.Tbl_Urun where x.URUNDURUM == true select new { x.Urunid, x.URUNAD, x.URUNFIYAT, x.URUNSTOK }).ToList(); MessageBox.Show("Satın Alma İşlemi Başarılı Bakiyenizi Kontrol Ediniz !"); } private void btnYukle_Click(object sender, EventArgs e) { int idmusteri = Convert.ToInt32((from x in en.Tbl_User where x.KAd == kullaniciadi select x.Kid).FirstOrDefault()); var bky = txtBakiye.Text; var gncby = en.Tbl_User.Find(idmusteri); gncby.BAKIYEYUKLE = Convert.ToInt32(bky); en.SaveChanges(); MessageBox.Show("Yüklediğiniz Tutar Admin Onayından Sonra Bakiyenize Eklenecektir !"); } private void btnUSD_Click(object sender, EventArgs e) { double usd = Convert.ToDouble(lblUSD.Text); int idmusteri = Convert.ToInt32((from x in en.Tbl_User where x.KAd == kullaniciadi select x.Kid).FirstOrDefault()); var bky = txtBakiye.Text; var gncby = en.Tbl_User.Find(idmusteri); double a = Convert.ToDouble(bky) * usd; gncby.BAKIYEYUKLE = Convert.ToInt32(a); en.SaveChanges(); MessageBox.Show("Yüklediğiniz Tutar Admin Onayından Sonra Bakiyenize Eklenecektir !"); } private void btnSTR_Click(object sender, EventArgs e) { double str = Convert.ToDouble(lblSTR.Text); int idmusteri = Convert.ToInt32((from x in en.Tbl_User where x.KAd == kullaniciadi select x.Kid).FirstOrDefault()); var bky = txtBakiye.Text; var gncby = en.Tbl_User.Find(idmusteri); double a = Convert.ToDouble(bky) * str; gncby.BAKIYEYUKLE = Convert.ToInt32(a); en.SaveChanges(); MessageBox.Show("Yüklediğiniz Tutar Admin Onayından Sonra Bakiyenize Eklenecektir !"); } private void btnJpy_Click(object sender, EventArgs e) { double jpy = Convert.ToDouble(lblJPY.Text); int idmusteri = Convert.ToInt32((from x in en.Tbl_User where x.KAd == kullaniciadi select x.Kid).FirstOrDefault()); var bky = txtBakiye.Text; var gncby = en.Tbl_User.Find(idmusteri); double a = Convert.ToDouble(bky) * jpy; gncby.BAKIYEYUKLE = Convert.ToInt32(a); en.SaveChanges(); MessageBox.Show("Yüklediğiniz Tutar Admin Onayından Sonra Bakiyenize Eklenecektir !"); } private void btnEmir_Click(object sender, EventArgs e) { Tbl_Emir em = new Tbl_Emir(); em.EmirUrun = txtAD.Text; em.EmirKilo = Convert.ToDouble(txtKG.Text); em.EmirFiyat = Convert.ToDouble(txtFIYAT.Text); em.EmirTarih = "16/06/2021"; em.EmirDurum = false; em.EmirUser = (from x in en.Tbl_User where x.KAd == kullaniciadi select x.Kid).FirstOrDefault(); en.Tbl_Emir.Add(em); en.SaveChanges(); MessageBox.Show("Ürün Fiyat Emri Başarıyla Eklendi.. (Alım işlemi gerçekleşirse %1 komisyon ücreti alınacaktır)"); } private void button1_Click(object sender, EventArgs e) { FrmRapor frmr = new FrmRapor(); frmr.Show(); } } } <file_sep>/FrmAdminPanel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Yazılım_Yapımı_Project { public partial class FrmAdminPanel : Form { public FrmAdminPanel() { InitializeComponent(); } YazilimYapimiEntities en = new YazilimYapimiEntities(); private void FrmAdminPanel_Load(object sender, EventArgs e) { datagridurun.DataSource = (from x in en.Tbl_Urun where x.URUNDURUM == false select new { x.Urunid, x.URUNAD, x.URUNFIYAT, x.URUNSTOK }).ToList(); datagridbakiye.DataSource = (from x in en.Tbl_User where x.BAKIYEYUKLE != null select new { x.Ad, x.Soyad, x.BAKIYEYUKLE }).ToList(); lblKomisyon.Text = (from x in en.Tbl_admin select x.komisyon).FirstOrDefault().ToString() + " TL "; } private void datagridurun_CellClick(object sender, DataGridViewCellEventArgs e) { int secilen = datagridurun.SelectedCells[0].RowIndex; txtID.Text = datagridurun.Rows[secilen].Cells[0].Value.ToString(); txtURUNAD.Text = datagridurun.Rows[secilen].Cells[1].Value.ToString(); } private void datagridbakiye_CellClick(object sender, DataGridViewCellEventArgs e) { int secilen = datagridbakiye.SelectedCells[0].RowIndex; txtISIM.Text = datagridbakiye.Rows[secilen].Cells[0].Value.ToString(); txtBAKIYE.Text = datagridbakiye.Rows[secilen].Cells[2].Value.ToString(); } private void btnUrunOnayla_Click(object sender, EventArgs e) { int id = int.Parse (txtID.Text); var gncu = en.Tbl_Urun.Find(id); gncu.URUNDURUM = true; en.SaveChanges(); datagridurun.DataSource = (from x in en.Tbl_Urun where x.URUNDURUM == false select new { x.Urunid, x.URUNAD, x.URUNFIYAT, x.URUNSTOK }).ToList(); MessageBox.Show("ÜRÜN PAZARA BAŞARIYLA EKLENDİ !!!"); } private void btnBakiyeOnayla_Click(object sender, EventArgs e) { var id = (from x in en.Tbl_User where x.Ad == txtISIM.Text select x.Kid).FirstOrDefault(); int bakiye =Convert.ToInt32((from x in en.Tbl_User where x.Ad == txtISIM.Text select x.Bakiye).FirstOrDefault()); int ybakiye = int.Parse(txtBAKIYE.Text); int toplambakiye = bakiye + ybakiye; var gncb = en.Tbl_User.Find(id); gncb.Bakiye = toplambakiye; gncb.BAKIYEYUKLE = null; en.SaveChanges(); datagridbakiye.DataSource = (from x in en.Tbl_User where x.BAKIYEYUKLE != null select new { x.Ad, x.Soyad, x.BAKIYEYUKLE }).ToList(); MessageBox.Show("BAKİYE KULLANICININ HESABINA BAŞARIYLA GÖNDERİLDİ !"); } } } <file_sep>/FrmUserKayit.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Yazılım_Yapımı_Project { public partial class FrmUserKayit : Form { public FrmUserKayit() { InitializeComponent(); } private void ExitButton_Click(object sender, EventArgs e) { this.Hide(); } private void btnKayıt_Click(object sender, EventArgs e) { YazilimYapimiEntities en = new YazilimYapimiEntities(); Tbl_User u = new Tbl_User(); u.Ad = txtAd.Text; u.Soyad = txtSoyad.Text; u.KAd = txtKullanici.Text; u.Password = <PASSWORD>; u.TC = txtTC.Text; u.Tel = txtTel.Text; u.Mail = txtMail.Text; u.Bakiye = 0; en.Tbl_User.Add(u); en.SaveChanges(); MessageBox.Show("Kayıt Başarılı Sisteme Giriş Yapabilirsiniz..."); } } } <file_sep>/FrmRapor.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; namespace Yazılım_Yapımı_Project { public partial class FrmRapor : Form { public FrmRapor() { InitializeComponent(); } YazilimYapimiEntities en = new YazilimYapimiEntities(); private void FrmRapor_Load(object sender, EventArgs e) { dataRapor.DataSource = (from x in en.Tbl_Emir where x.EmirDurum == true select new { TARİH = x.EmirTarih, URUN = x.EmirUrun, TUTAR = x.EmirFiyat, MIKTAR = x.EmirKilo }).ToList(); } public static void PDF_Disa_Aktar(DataGridView dataGridView1) { SaveFileDialog save = new SaveFileDialog(); save.OverwritePrompt = false; save.Title = "PDF Dosyaları"; save.DefaultExt = "pdf"; save.Filter = "PDF Dosyaları (*.pdf)|*.pdf|Tüm Dosyalar(*.*)|*.*"; if (save.ShowDialog() == DialogResult.OK) { PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount); pdfTable.DefaultCell.Padding = 3; pdfTable.WidthPercentage = 80; pdfTable.HorizontalAlignment = Element.ALIGN_LEFT; pdfTable.DefaultCell.BorderWidth = 1; foreach (DataGridViewColumn column in dataGridView1.Columns) { PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText)); cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240); pdfTable.AddCell(cell); } try { foreach (DataGridViewRow row in dataGridView1.Rows) { foreach (DataGridViewCell cell in row.Cells) { pdfTable.AddCell(cell.Value.ToString()); } } } catch (NullReferenceException) { } using (FileStream stream = new FileStream(save.FileName + ".pdf", FileMode.Create)) { Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f); PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); pdfDoc.Add(pdfTable); pdfDoc.Close(); stream.Close(); } } } private void btnPDF_Click(object sender, EventArgs e) { PDF_Disa_Aktar(dataRapor); } } } <file_sep>/AnaForm.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Yazılım_Yapımı_Project { public partial class AnaForm : Form { public AnaForm() { InitializeComponent(); } private void btnAdmin_Click(object sender, EventArgs e) { AdminGiris admn = new AdminGiris(); admn.Show(); this.Hide(); } private void btnUser_Click(object sender, EventArgs e) { UserGiris usr = new UserGiris(); usr.Show(); this.Hide(); } private void ExitButton_Click(object sender, EventArgs e) { Application.Exit(); } } } <file_sep>/UserGiris.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Yazılım_Yapımı_Project { public partial class UserGiris : Form { public UserGiris() { InitializeComponent(); } private void ExitButton_Click(object sender, EventArgs e) { Application.Exit(); } YazilimYapimiEntities en = new YazilimYapimiEntities(); private void btnGiris_Click(object sender, EventArgs e) { var sorgu = from x in en.Tbl_User where x.KAd == txtKullanici.Text && x.Password == <PASSWORD> select x; if (sorgu.Any()) { FrmUserPanel frmu = new FrmUserPanel(); frmu.kullaniciadi = txtKullanici.Text; frmu.Show(); this.Hide(); } else { MessageBox.Show("Kullanıcı Adı Veya Şifre Hatalı !", "HATALI GİRİŞ", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void btnUyeOl_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { FrmUserKayit frmk = new FrmUserKayit(); frmk.Show(); } private void UserGiris_Load(object sender, EventArgs e) { } } }
fd93ed2bab0aa90b7c9898d190a8f528d2de7ef1
[ "Markdown", "C#" ]
7
Markdown
Redicoding/Yazilim-Yapimi-Project
bc065a6425de3babc3c5bb95d9d290e90c5841f8
c1645c8e99c090974e15a4d132ec456c250a11ef
refs/heads/master
<file_sep>var app = angular.module("exercise",["ngResource"]); app.value("dummy",{defined: true}); app.factory("Topic",function($resource){ return $resource("/api/topics/:id",{id: "@id"}); }); app.controller("todo",function($scope,Topic) { $scope.topicList = Topic.query(); }) app.controller("topicList",function($scope,Topic) { }); app.controller("addItem",function($scope,Topic) { $scope.addItem = function(item) { var topic = new Topic(item); topic.$save().then(function() { $scope.topicList.push(topic); }) $scope.item = {}; }; }); app.filter("titleMatch",function() { return function(input,glob) { debugger if(!glob) return input; return input.filter(function(topic) { return topic.title.indexOf(glob) !== -1 }) } });<file_sep># ngapp Basic Angular App for learning purposes. Use Python Simple HTTP Server to Run.
9247019caff6dee202c9c8a506fb8c4a35bcec0b
[ "JavaScript", "Markdown" ]
2
JavaScript
nelsonic/ngapp
34e0feffbda05fbfa4169888e87c6eaf453e505b
e7bf928aa2927b204c35d62dbaba4109960f5086
refs/heads/master
<repo_name>h3x89/flask<file_sep>/sqlite.py """Sqlite 3 and python.""" import sqlite3 conn = sqlite3.connect("database/sqlite3.db") conn.execute("CREATE TABLE student (name TXT, addr TXT, pin TXT)") print("Create Table") conn.close() <file_sep>/cookie_session.py """Flask - Sending Form Data to Template using cookie and sessions.""" from flask import Flask, render_template, request, make_response, redirect, url_for app = Flask(__name__) @app.route('/student') def student(): """Main function.""" return render_template('student.html') @app.route('/result', methods=['POST', 'GET']) def result(): """Grab form from student.html and send to result.html.""" if request.method == 'POST': result = request.form return render_template("result2.html", result=result) else: # result = str(request.args.get) """why does not work?.""" result = dict(request.args.get) return render_template("result2.html", result=result) """COOKIE""" @app.route('/cookie') def cookie(): """Fist cookie.""" return render_template('cookie.html') @app.route('/setcookie', methods=['POST', 'GET']) def setcookie(): """Function to set cookie.""" if request.method == 'POST': user = request.form['nm'] resp = make_response(render_template('readcookie.html')) resp.set_cookie('userID', user) return resp @app.route('/getcookie') def getcookie(): """GET COOKIE.""" name = request.cookies.get('userID') return '<h1>welcome ' + name + '</h1>' """SESSION""" @app.route('/session_login') def session_login(): """Session login example.""" session['username'] = 'admin' # return str(session) return redirect(url_for('session')) @app.route('/session_logout') def session_logout(): """Session logout example.""" if 'username' in session: session.pop('username') # return str(session) return redirect(url_for('session')) @app.route('/') def index(): """Session example.""" if 'username' in session: username = session['username'] return 'Logged in as ' + username + '<br>' + "<b><a href = '/logout'>click here to log out</a></b>" return "You are not logged in <br><a href = '/login'></b>" + "click here to log in</b></a>" @app.route('/login', methods=['GET', 'POST']) def login(): """Login.""" if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) # return login return ''' <html> <body> <form action = "login" method="POST"> <p>username <input type="text" name="username" /></p> <p><input type="submit" value="submit" /></p> </form> </body> </html> ''' @app.route('/logout') def logout(): """Logout.""" # remove the username from the session if it is there session.pop('username', None) return redirect(url_for('index')) if __name__ == '__main__': session = {} app.secret_key = 'asdasdas' app.run(debug=True) <file_sep>/hello.py """hello.py.""" from flask import Flask # """Main Framework""" from flask import url_for # """Test function""" from flask import request # """GET and POST""" from flask import render_template # """HTTP Templates""" from flask import redirect # """Redirection""" from flask import abort # """Errors""" """First Hello World app in Flask.""" """Author: h3x89""" app = Flask(__name__) @app.route("/") def hello(): """Hello World.""" return "Hello World!" @app.route('/robert') def robert(): """Hi Robert.""" return 'Hi Robert' @app.route('/user/<username>') def username(username): """Hi USERNAME.""" """Possible to put strin and int""" return ('Hi %s' % username) @app.route('/post/<int:post_id>') def show_post(post_id): """Post ID.""" """Only int""" return('Post %d' % post_id) ############################################################################### @app.route('/error') def error(): """Error function.""" abort(401) print 'error' @app.route('/pass/<my_pass>') def my_pass(my_pass): """Pass test.""" if my_pass != '<PASSWORD>': return error() else: return redirect(url_for('username', username=my_pass)) ############################################################################### @app.route('/login', methods=['GET', 'POST']) def login(): """GET and POST.""" def do_the_login(): """Test login.""" return 'do the login return' def show_the_login_form(): """Test login form.""" return 'show the login form return' if request.method == 'GET': answer = do_the_login() else: answer = show_the_login_form() return ("answer is: %s" % answer) ############################################################################### @app.route('/templates/') @app.route('/templates/<name>') def templates(name=None): """HTTP Templates.""" return render_template('hello.html', name=name) @app.route('/redirection') def redirection(): """Redirection.""" return redirect(url_for('login')) ############################################################################### @app.route('/result') def result(): """More adventages templates.""" dict = {'phy': 50, 'che': 60, 'maths': 70} return render_template('result.html', result=dict) ############################################################################### @app.route("/static") def index(): """Static files.""" return render_template("index.html") ############################################################################### with app.test_request_context(): """Test function""" print url_for('hello') print url_for('robert') print url_for('username', username='John') print url_for('show_post', post_id=12) '''WRONG REQUEST - just for tests''' # print url_for('username') # print url_for('username', next='/') # print url_for('show_post') # print url_for('show_post', post_id='test') ############################################################################### # app.route(rule, options) # app.run(host, port, debug, options) ############################################################################### if __name__ == "__main__": # app.run() # app.run(host, port, debug, options) app.run(host="0.0.0.0", port=5000, debug=True)
ce821c2bee0fca5c5cfc2fbd056e07c981ebb3ec
[ "Python" ]
3
Python
h3x89/flask
700645733d19d5d78645e3f143caba6b524d90f0
f9456d5329de7ccf6accbe08bc34fd9d1428d06a
refs/heads/main
<repo_name>cjlee0217/covid19_mask_detection<file_sep>/기획/[회의록] 20201119.md # [회의록] 20201119 - 1 ### 1. 강사님 피드백 * 사람 1명 있는 이미지 & 모델을 만드는 것에 집중해서 진행 * 정상적인 이미지 사용 * 측면 이미지의 경우? 추가적인 코딩이 필요할 수 있음 * 프로젝트 흐름 & 방향 => good * 확장방안 * YOLO : 영상에서 사람이 마스크를 벗었는지 안 벗었는지 탐지 * 텍스트 생성 : 마스크를 벗는 motion을 추가해서 "지금 마스크를 벗고 있다" 메시지 띄우기 (지금 연구 중인 분야...! 이번 프로젝트에 적용은 어려울듯) ### 2. 진행상황 * 이미지 데이터셋 : 마스크, 코마스크, 턱마스크 합성하는 코드 완료 * 사진에서 눈 검출하는 코드 작성 중 * 측면 얼굴 탐지 자료 조사 중 ### 3. 할일 * 이미지 데이터셋 만들기 (동현님) * https://www.kaggle.com/greatgamedota/ffhq-face-data-set * 마스크 / 턱마스크 / 코마스크 / 노마스크 -> 각 50장씩 생성해서 구글 드라이브에 업로드 * 눈 탐지 : 로직 마무리 & 테스트 (동재님, 지원님) * 측면 상태에서 눈이 탐지가 되는지 확인 (성훈님) * profile faces xml ---------------------------------------------------------------------------------------------------------------------------------------- # [회의록] 20201119 - 2 * 마스크 / 턱마스크 / 코마스크 / 노마스크 -> 눈 탐지 결과 * 마스크로 얼굴을 가릴 수록 얼굴 인식 & 눈 검출이 안됨 * 눈 검출이 2개가 아닐 경우 -> 안경 썼을 경우로 돌림 -> 그래도 안된다면, 이미지를 버리는 것으로 로직 진행 * xml 적용해도 괜찮을듯? xml이 다른 코드보다 눈 검출이 잘되는 것으로 보임... * 내일 각 카테고리 별로 1000개씩 생성 계획 (**서버컴 활용) * 결과 보고 이미지 카테고리를 4개 -> 3개로 할지 말지 결정하기 * 내일부터 모델 & 검증 : LeNet, AlexNet, VGGNet, GoogleNet, ResNet | 사람 | 모델 | | ------ | --------- | | 정성훈 | LeNet | | 박지원 | AlexNet | | 김동현 | VGGNet | | 이동재 | GoogleNet | | 이찬주 | ResNet | <file_sep>/기획/[회의록] 20201118.md # [회의록] 20201118 ### 1. 조사한 자료 공유 * Face recognition에서 문제 - 두 눈의 좌표를 미리 알고 있을 때 alignment하는 방법 조사 필요 - 전처리/학습 단계에서 사진 1장에 인원 여러명 일 경우 고려 - 눈 여러쌍 추출 -> 각기 다른 얼굴로 취급 * 동영상에서 실시간 detection * 영상을 프레임별로 잘라서(=이미지) 처리 후 하나로 합치는 방식 * 이미지에서 먼저 분류 -> 동영상 가능 * 이미지로 학습 & 동영상으로 테스트 - & 모델 완성 후 테스트&프로젝트 발표 때 시연 영상에 활용 * Tensorflow 가상환경 : 버전 관리 -> 우리 프로젝트에는 관련 없을듯 * 이미지 데이터셋 * 사람 얼굴에 full mask, nose mask, chin mask, no mask 합성해서 데이터셋 만들 수 있을 듯? * 안 되면 팀원든 사진 찍어서 증식 * YOLO, 동영상에서 object detection -> 깃허브>샘플코드 폴더 내 공유된 레퍼런스 확인 ### 2. 내일까지 찬주 - 마스크 데이터셋 만들기 지원 & 동재 & 동현 - 마스크 영역 추출 성훈 - opencv로 이미지 1개에서 여러 명의 얼굴이 잡히는지 알아보기 (multi detection) <file_sep>/기획/[회의록] 20201115.md # [회의록] 20201115 ### 1. 조사한 자료 공유 * 마스크 인식기 : Tensorflow의 object detection api을 활용하여 만든 마스크 인식기 * https://velog.io/@kjyggg/Few-Shot-Object-Detection * 마스크 탐지기 : 딥러닝 기반의 마스크 착용 판별 * 공유된 논문 pdf 파일 참조 * 사진 합성 : * https://utokorea.blogspot.com/2019/06/python-deep-learning_28.html?m=1 * CNN을 위한 이미지 데이터 증식 및 모델링 관련 * https://tykimos.github.io/2017/06/10/CNN_Data_Augmentation/ * https://tykimos.github.io/2017/03/08/CNN_Getting_Started/ * FaceNet : 얼굴 인식 * https://jkisaaclee.kro.kr/keras/facenet/deep%20learning/computer%20vision/2019/10/01/how_to_develop_a_face_recognition_system_using_facenet_in_keras_ko/ ### 2. 회의 내용 * 마스크를 썼다 vs 안 썼다 분류 + 안 썼을 경우 얼만큼 안 썼는지 판별하여 맞춤형 경고메시지 띄우기 * 예) "마스크를 코까지 올려서 착용해주세요." * 얼굴 인식(FaceNet) 적용을 통해 사람과 사람이 아닌 object 구별해서 제대로 판별하기 * 마스크 미착용자에게 산소마스크 합성 시켜주는 아이디어 * 협업 방식 : 깃허브에 코드 공유 ### 3. 할일 * 2020/11/16 ~ 2020/11/17 : 프로젝트 기획안 작성 * 월요일 저녁에 관련해서 회의 가능 : 역할 분담, 사용할 기술 등 * ~ 2020/11/17 : 이미지 데이터를 수치화/배열 형태로 바꾸는 법 각자 연습 * -> 위의 자료 참조 (CNN을 위한 이미지 데이터 증식 및 모델링 관련) <file_sep>/README.md # :mask: Facial mask-Area-Detection 을 활용한 올바른 마스크 착용 여부 판단 모델링 :lock: ​ \+ 멀티캠퍼스 딥러닝 기반 AI 엔지니어링 세미 2차 프로젝트 (CNN) ​ - __참여__ : [__ineed-coffee__](https://github.com/ineed-coffee) , [__cjlee0217__](https://github.com/cjlee0217) , [__okyou1000__](https://github.com/okyou1000) , [__Parkjiwonha__](https://github.com/Parkjiwonha) , [__ikeven94__](https://github.com/ikeven94) - __기간__ : 2020.11.12~2020.11.23 - __주제__ : Facial mask-Area-Detection 을 활용한 올바른 마스크 착용 여부 판단 - __결과보고서(전체 내용)__ : [Here](https://drive.google.com/file/d/1-IWaciQrFbH6eN0UEdoTkQCWkAuaM9o2/view?usp=sharing) <a><img src="https://media.giphy.com/media/mFknMI76h9WHmuukXw/giphy.gif" width="40px"></a> *** # 결과보고서 요약<file_sep>/결과보고서/예측 시뮬레이터/Covid19.py class MaskAreaDetector(): def __init__(self): import cv2 self.face_cascade = cv2.CascadeClassifier('haarcascade_frontface.xml') self.eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') self.glass_cascade = cv2.CascadeClassifier('haarcascade_eye_tree_eyeglasses.xml') self.eyesplit_cascade = cv2.CascadeClassifier('haarcascade_lefteye_2splits.xml') return def advanced_eye_detect(self,img,cascade=None,info='normal'): import cv2 if info=='normal': cascade = self.eye_cascade ret_val=[] img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = self.face_cascade.detectMultiScale(img_gray) if len(faces)!=1: return ret_val for (x,y,w,h) in faces: roi_gray = img_gray[y:y+h, x:x+w] eyes =cascade.detectMultiScale(roi_gray,1.1,4) if not (len(eyes)==2): if info == 'normal': return self.advanced_eye_detect(img,self.eyesplit_cascade,'split') elif info == 'split': return self.advanced_eye_detect(img,self.glass_cascade,'glasses') elif info == 'glasses': return ret_val ret_val = eyes return ret_val def get_rotated_image(self,img,eyes): import cv2 import numpy as np eye_1 , eye_2 = eyes if eye_1[0] < eye_2[0]: left_eye = eye_1 right_eye = eye_2 else: left_eye = eye_2 right_eye = eye_1 left_eye_center = (int(left_eye[0] + (left_eye[2] / 2)), int(left_eye[1] + (left_eye[3] / 2))) right_eye_center = (int(right_eye[0] + (right_eye[2]/2)), int(right_eye[1] + (right_eye[3]/2))) left_eye_x , left_eye_y = left_eye_center right_eye_x , right_eye_y = right_eye_center delta_x = right_eye_x - left_eye_x delta_y = right_eye_y - left_eye_y if not delta_x or delta_y: return img angle=np.arctan(delta_y/delta_x) angle = (angle * 180) / np.pi h, w = img.shape[:2] center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, (angle), 1.0) rotated_img = cv2.warpAffine(img, M, (w, h)) return rotated_img def calculate_rotated_eyes(self,rotated_img,cascade=None,info='normal'): import cv2 import numpy as np if info=='normal': cascade = self.eye_cascade ret_val=[] rotated_gray = cv2.cvtColor(rotated_img, cv2.COLOR_BGR2GRAY) faces = self.face_cascade.detectMultiScale(rotated_gray, 1.1, 4) if len(faces)!=1: return ret_val for (x,y,w,h) in faces: black=np.zeros(rotated_gray.shape,dtype='uint8') black[y:y+h, x:x+w]=rotated_gray[y:y+h, x:x+w] rotated_eyes =cascade.detectMultiScale(black,1.1,4) if not (len(rotated_eyes)==2): if info == 'normal': return self.calculate_rotated_eyes(rotated_img,self.eyesplit_cascade,'split') elif info == 'split': return self.calculate_rotated_eyes(rotated_img,self.glass_cascade,'glasses') elif info == 'glasses': return ret_val ret_val = rotated_eyes return ret_val def extract_facial_mask_area(self,rotated_img,rotated_eyes): import cv2 import numpy as np eye_1 , eye_2 = rotated_eyes if eye_1[0] < eye_2[0]: left_eye = eye_1 right_eye = eye_2 else: left_eye = eye_2 right_eye = eye_1 left_eye_center = (int(left_eye[0] + (left_eye[2] / 2)), int(left_eye[1] + (left_eye[3] / 2))) right_eye_center = (int(right_eye[0] + (right_eye[2]/2)), int(right_eye[1] + (right_eye[3]/2))) left_eye_x , left_eye_y = left_eye_center right_eye_x , right_eye_y = right_eye_center delta_x = right_eye_x - left_eye_x delta_y = right_eye_y - left_eye_y L = np.sqrt(delta_x**2 + delta_y**2) xpad_L , xpad_R = int(0.6*L) , int(1.6*L) ypad_U , ypad_D = int(0.6*L) , int(1.8*L) ROI = rotated_img[left_eye_y-ypad_U:left_eye_y+ypad_D,left_eye_x-xpad_L:left_eye_x+xpad_R] ROI_resized = cv2.resize(ROI,(120,140)) mask_area = ROI_resized[50:140,0:120] return mask_area <file_sep>/샘플 코드/object_detection link.md ### 영상 속 객체 검출 관련 사이트 - OpenCV, Object Detection - Video Detection - https://m.blog.naver.com/PostView.nhn?blogId=handuelly&logNo=221835111866&targetKeyword=&targetRecommendationCode=1 - https://m.blog.naver.com/PostView.nhn?blogId=handuelly&logNo=221837207646&targetKeyword=&targetRecommendationCode=1 - 웹캠을 이용한 실시간 사물 인식 - https://ukayzm.github.io/python-object-detection-tensorflow/ - https://nitr0.tistory.com/266 - https://jamessong.tistory.com/3?category=803410 - [Mask R-CNN] Python과 Keras를 이용한 실시간 객체 탐지 알고리즘 구현 - https://deep-eye.tistory.com/4?category=401242
4338596a28643a5ac44cd9efa325d6a4f1d6d354
[ "Markdown", "Python" ]
6
Markdown
cjlee0217/covid19_mask_detection
1680707f3220074da7cc231d0e904cdc02a37cab
c59a79f00b9aaffdeb8ea1de49d45fde377b9431
refs/heads/master
<file_sep>/* * Copyright (C) 2015, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment * platform is licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package gov.nasa.jpf.constraints.solvers.dreal; import java.util.List; import gov.nasa.jpf.constraints.api.ConstraintSolver.Result; public class DrealResult { private final Result result; private List<DrealValuationResult> valuations; private double delta = -1; public DrealResult(Result result) { this.result = result; } public DrealResult(Result result, List<DrealValuationResult> valuations, double delta) { this.result = result; this.valuations = valuations; this.delta = delta; } public List<DrealValuationResult> getValuations() { return this.valuations; } public double getDelta() { return this.delta; } public DrealValuationResult getValuation(String variableName) { for(DrealValuationResult var : this.valuations) { if(var.getVariableName().equals(variableName)) return var; } return null; } public Result getResult() { return this.result; } } <file_sep># jConstraints-dReal # This adds support for the dReal constraint solver in jConstraints. Please consult the [dReal](https://dreal.github.io/) website for more information. **NOTE** This plugin is at the moment very experimental with some features being incomplete. ## Installation ## First, get dReal from [dReal website](https://dreal.github.io/). Then: * Go to the *jConstraints-dreal* folder and run ``` mvn install ```. It should run a lot of test cases - hopefully everything works. * If the compilation was successful, the jConstraints-dreal library can be found in the JAR file target/jConstraints-dreal[VERSION].jar * jConstraints loads extensions automatically from the ~/.jconstraints/extensions folder in a users home directory. Create this directory and copy jConstraints-dreal-[version].jar into this folder. ## Usage and Configuration ## To use dreal, simply put the following in your .jpf file. ```txt symbolic.dp=dreal dreal.path=/path/to/dReal/executable ``` More options will be added soon. ## Known Issues ## Does NOT return a valuation. Cannot handle (Coral can): ```txt (set-logic QF_NRA) (declare-fun y () Real) (declare-fun x () Real) (assert (= y ( cos x)) ) (check-sat) (exit) ``` or ```txt (set-logic QF_NRA) (declare-fun x1 () Real) (declare-fun x2 () Real) (assert (= (- ( sin x1) ( cos x2)) 0.0) ) (check-sat) (exit) ```<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>gov.nasa</groupId> <artifactId>jConstraints-dReal</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>jConstraints-dReal</name> <url>https://bitbucket.org/luckow/jconstraints-coral/</url> <description>dReal plugin for jConstraints</description> <issueManagement> <url>https://bitbucket.org/luckow/jconstraints-coral/issues</url> <system>BitBucket Issues</system> </issueManagement> <developers> <developer> <id>ksluckow</id> <name><NAME></name> <email><EMAIL></email> </developer> </developers> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <jconstraints.version>0.9.1-SNAPSHOT</jconstraints.version> <testng.version>6.8</testng.version> <compiler-plugin.version>3.1</compiler-plugin.version> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${compiler-plugin.version}</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>gov.nasa</groupId> <artifactId>jconstraints</artifactId> <version>${jconstraints.version}</version> </dependency> </dependencies> </project> <file_sep>/* * Copyright (C) 2015, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment * platform is licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package gov.nasa.jpf.constraints.solvers.dreal; import java.util.Random; import gov.nasa.jpf.constraints.solvers.dreal.DrealValuationResult.Interval; public class RandomValueSelector implements ValueSelector { private Random rgen; public RandomValueSelector() { rgen = new Random(); } public RandomValueSelector(int seed) { rgen = new Random(seed); } @Override public double getValue(Interval val) { double min, max; if(Double.isInfinite(val.start)) min = Double.MIN_VALUE; else min = val.start; if(Double.isInfinite(val.end)) max = Double.MAX_VALUE; else max = val.end; return min + (max - min) * rgen.nextDouble(); } }
68514a73b7d8ef8b24cf59f0bc122a20a4089cf4
[ "Markdown", "Java", "Maven POM" ]
4
Java
terminiter/jconstraints-dreal
b78ba4e2b9c00006b273aa3c579c598078e62cce
74fbfa8030e58f7f76360f773839f54eb3e7226a
refs/heads/master
<repo_name>taq-f/flask-boilerplate<file_sep>/app.py """Flask app boilerplate""" # -*- coding: utf-8 -*- from datetime import datetime, timedelta import logging from logging.handlers import RotatingFileHandler import os import random import string from flask import (Flask, jsonify, make_response, render_template, request, session) def get_secret_key(app, filename='secret_key'): """Get, or generate if not available, secret key for cookie encryption. Key will be saved in a file located in the application directory. """ filename = os.path.join(app.root_path, filename) try: return open(filename, 'r').read() except IOError: k = ''.join([ random.choice(string.punctuation + string.ascii_letters + string.digits) for i in range(64) ]) with open(filename, 'w', encoding='utf-8') as f: f.write(k) return k def init_logger(app): """Initialize logger for application""" log_dir = os.path.join(app.root_path, 'logs') if not os.path.exists(log_dir): os.makedirs(log_dir, True) formatter = logging.Formatter('%(asctime)s\t%(levelname)s\t%(message)s') # Access log access_log_file = os.path.join(app.root_path, 'logs', 'access.log') access_log_file_handler = RotatingFileHandler( access_log_file, maxBytes=10000000, backupCount=10) access_log_file_handler.setLevel(logging.INFO) access_log_file_handler.setFormatter(formatter) app.logger.addHandler(access_log_file_handler) # Error log error_log = os.path.join(app.root_path, 'logs', 'error.log') error_log_file_handler = RotatingFileHandler( error_log, maxBytes=10000000, backupCount=10) error_log_file_handler.setLevel(logging.ERROR) error_log_file_handler.setFormatter(formatter) app.logger.addHandler(error_log_file_handler) app.logger.setLevel(logging.INFO) def remote_addr(): """Workaround for retriving client ip address when reverse proxy in the middle""" return request.access_route[-1] # ****************************************************************************** # Decorator # ****************************************************************************** def skip_session_check(func): """Register the given function into skip session list. It won't be wrapped. """ if 'IGNORE_SESSION_CHECK' not in app.config: app.config['IGNORE_SESSION_CHECK'] = [] app.config['IGNORE_SESSION_CHECK'].append(func.__name__) return func # ****************************************************************************** # Initialize Application # ****************************************************************************** app = Flask(__name__) app.config['IGNORE_SESSION_CHECK'] = ['static'] app.config['TEMPLATES_AUTO_RELOAD'] = True app.config['SECRET_KEY'] = get_secret_key(app) init_logger(app) # ****************************************************************************** # Web # ****************************************************************************** # ************************************* # Before each requst # ************************************* @app.before_request def write_access_log(): """Write access log""" app.logger.info('{ip}\t{method}\t{path}\trequest start'.format( ip=remote_addr(), method=request.method, path=request.path)) return @app.before_request def check_session(): """Inspect session. Return 401 if session has not establised yet. If the endpoint (function) is in skip session list, does nothing. """ if request.endpoint in app.config['IGNORE_SESSION_CHECK']: return session_check_result = session.get('login_id') if session_check_result: return return make_response('login required', 401) # ************************************* # After each requst # ************************************* @app.after_request def add_no_cache_header(res): """Disable caching of any content""" # uncomment followings to enable this feature # res.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # res.headers["Pragma"] = "no-cache" # res.headers["Expires"] = "0" # res.headers['Cache-Control'] = 'public, max-age=0' return res @app.after_request def static_cache(res): """Set response headers about caching for static resources A year later is set in this example as advised here: https://developers.google.com/speed/docs/insights/LeverageBrowserCaching It may be better to store the expiration date somewhere else and reuse it since this example calculate the date in every request. """ if request.endpoint == 'static': expires = datetime.now() + timedelta(days=365) res.headers['Expires'] = expires.isoformat() return res @app.after_request def write_access_result_log(res): """Write access log with response status code""" app.logger.info( '{ip}\t{method}\t{path}\treqeust end\t{status_code}'.format( ip=remote_addr(), method=request.method, path=request.path, status_code=res.status_code)) return res # ************************************* # Routes # ************************************* @app.route('/api/return_json_response', methods=['GET']) def return_json_response(): """Return json response sample""" return jsonify({'this is': 'sample'}) @app.route('/api/return_error_response', methods=['GET']) def return_error_response(): """Return error response sample""" return make_response(jsonify({}), 403) @app.route('/', methods=['GET']) @skip_session_check def index(): """Handler for index page""" session['login_id'] = 'something' # render_template searches templates directory by default return render_template('index.html', name='World') @app.errorhandler(Exception) def handle_error(error): """Error handler when a routed function raises unhandled error""" import traceback for i, line in enumerate(traceback.format_exc().split('\n')): app.logger.error( '{line_no}\t{message}'.format(line_no=i + 1, message=line)) return 'Internal Server Error', 500 if __name__ == '__main__': app.run(host='localhost', port=5000) <file_sep>/README.md # flask-boilerplate A boilerplate for Flask web application
b7964e3f2249e46f0a5d97e6b51ae3c128c85051
[ "Markdown", "Python" ]
2
Python
taq-f/flask-boilerplate
9a2e926263bfa8df15c717cf8c467eb19b4b77d5
5abcab82744a67d7a2893e2dab289d9f4006af19
refs/heads/master
<file_sep>'use strict'; try { angular.module("openshiftUI") } catch(e) { angular.module("openshiftUI", []) } angular.module("openshiftUI").requires.push("kubernetesUI"); angular.module('openshiftUI') .filter('imageRepoReference', function(){ return function(objectRef, tag){ tag = tag || "latest"; var ns = objectRef.namespace || ""; ns = ns == "" ? ns : ns + "/"; var ref = ns + objectRef.name; ref += " [" + tag + "]"; return ref; }; }) .run(function(KubernetesObjectDescriber) { KubernetesObjectDescriber.registerKind("Build", "views/build.html") KubernetesObjectDescriber.registerKind("DeploymentConfig", "views/deployment-config.html") KubernetesObjectDescriber.registerKind("Route", "views/route.html") }); angular.module('kubernetesUI').run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('views/build.html', "<div>\n" + " <kubernetes-object-describe-header resource=\"resource\" kind=\"kind\"></kubernetes-object-describe-header>\n" + " <dl class=\"dl-horizontal\">\n" + " <dt>Name</dt>\n" + " <dd>{{resource.metadata.name}}</dd>\n" + " <dt>Namespace</dt>\n" + " <dd>{{resource.metadata.namespace}}</dd>\n" + " <dt>Created</dt>\n" + " <dd>{{resource.metadata.creationTimestamp | date:'medium'}}</dd>\n" + " </dl> \n" + " <h3>Build Configuration</h3>\n" + " <dl class=\"dl-horizontal\" style=\"margin-bottom: 0;\">\n" + " <dt>Strategy</dt>\n" + " <dd>{{resource.parameters.strategy.type}}</dd>\n" + " </dl> \n" + " <div ng-switch=\"resource.parameters.strategy.type\">\n" + " <div ng-switch-when=\"STI\">\n" + " <div ng-if=\"resource.parameters.strategy.stiStrategy.image\">\n" + " <dl class=\"dl-horizontal\" style=\"margin-bottom: 0;\">\n" + " <dt>Builder image</dt>\n" + " <dd>{{resource.parameters.strategy.stiStrategy.image}}</dd>\n" + " </dl>\n" + " </div>\n" + " <div ng-if=\"resource.parameters.strategy.stiStrategy.from\">\n" + " <dl class=\"dl-horizontal\" style=\"margin-bottom: 0;\">\n" + " <dt>Builder image repo [tag]</dt>\n" + " <dd>{{resource.parameters.strategy.stiStrategy.from | imageRepoReference : resource.parameters.strategy.stiStrategy.tag}}\n" + " </dd> \n" + " </dl>\n" + " </div>\n" + " </div>\n" + " <div ng-switch-when=\"Docker\">\n" + " <div ng-if=\"resource.parameters.strategy.dockerStrategy.image\">\n" + " <dl class=\"dl-horizontal\" style=\"margin-bottom: 0;\">\n" + " <dt>Builder image</dt>\n" + " <dd>{{resource.parameters.strategy.dockerStrategy.image}}</dd>\n" + " </dl>\n" + " </div>\n" + " </div>\n" + " <div ng-switch-when=\"Custom\">\n" + " <dl class=\"dl-horizontal\" style=\"margin-bottom: 0;\">\n" + " <dt>Builder image</dt>\n" + " <dd>{{resource.parameters.strategy.customStrategy.image}}</dd>\n" + " </dl>\n" + " </div>\n" + " </div> \n" + " <div ng-if=\"resource.parameters.source\">\n" + " <div ng-if=\"resource.parameters.source.type == 'Git'\">\n" + " <dl class=\"dl-horizontal\" style=\"margin-bottom: 0;\">\n" + " <dt>Source repo</dt>\n" + " <dd>{{resource.parameters.source.git.uri}}</dd>\n" + " </dl>\n" + " </div>\n" + " </div>\n" + " <h3>Status</h3>\n" + " <dl class=\"dl-horizontal\">\n" + " <dt>Phase</dt>\n" + " <dd>{{resource.status}}</dd>\n" + " <dt>Started</dt>\n" + " <dd>\n" + " <span ng-if=\"resource.startTimestamp\">{{resource.startTimestamp | date:'medium'}}</span>\n" + " <span ng-if=\"!resource.startTimestamp\"><em>not started</em></span>\n" + " </dd>\n" + " <dt>Completed</dt>\n" + " <dd>\n" + " <span ng-if=\"resource.completionTimestamp\">{{resource.completionTimestamp | date:'medium'}}</span>\n" + " <span ng-if=\"!resource.completionTimestamp\"><em>not complete</em></span>\n" + " </dd>\n" + " </dl>\n" + " <kubernetes-object-describe-labels resource=\"resource\"></kubernetes-object-describe-labels>\n" + " <kubernetes-object-describe-annotations resource=\"resource\"></kubernetes-object-describe-annotations>\n" + " <kubernetes-object-describe-footer resource=\"resource\"></kubernetes-object-describe-footer>\n" + "</div>\n" ); $templateCache.put('views/deployment-config.html', "<div>\n" + " <kubernetes-object-describe-header resource=\"resource\" kind=\"kind\"></kubernetes-object-describe-header>\n" + " <dl class=\"dl-horizontal\">\n" + " <dt>Name</dt>\n" + " <dd>{{resource.metadata.name}}</dd>\n" + " <dt>Namespace</dt>\n" + " <dd>{{resource.metadata.namespace}}</dd>\n" + " <dt>Created</dt>\n" + " <dd>{{resource.metadata.creationTimestamp | date:'medium'}}</dd>\n" + " </dl>\n" + " <h3>Triggers</h3>\n" + " <dl class=\"dl-horizontal\" ng-repeat=\"trigger in resource.triggers\">\n" + " <dt>Type</dt>\n" + " <dd>{{trigger.type}}</dd>\n" + " <dt ng-if-start=\"trigger.type == 'ImageChange'\">Image</dt>\n" + " <dd ng-if-end>{{trigger.imageChangeParams.from.name}}:{{trigger.imageChangeParams.tag}}</dd>\n" + " </dl>\n" + " <h3>Replication Settings</h3>\n" + " <dl class=\"dl-horizontal\">\n" + " <dt>Replicas</dt>\n" + " <dd>{{resource.template.controllerTemplate.replicas}}</dd> \n" + " </dl>\n" + " <h4>Selector</h4>\n" + " <dl class=\"dl-horizontal\">\n" + " <dt ng-repeat-start=\"(selectorKey, selectorValue) in resource.template.controllerTemplate.replicaSelector\">{{selectorKey}}</dt>\n" + " <dd ng-repeat-end>{{selectorValue}}</dd>\n" + " </dl> \n" + " <kubernetes-object-describe-pod-template template=\"resource.template.controllerTemplate.podTemplate.desiredState.manifest\"></kubernetes-object-describe-pod-template> \n" + " <kubernetes-object-describe-labels resource=\"resource\"></kubernetes-object-describe-labels>\n" + " <kubernetes-object-describe-annotations resource=\"resource\"></kubernetes-object-describe-annotations>\n" + " <kubernetes-object-describe-footer resource=\"resource\"></kubernetes-object-describe-footer>\n" + "</div>\n" ); $templateCache.put('views/route.html', "<div>\n" + " <kubernetes-object-describe-header resource=\"resource\" kind=\"kind\"></kubernetes-object-describe-header>\n" + " <dl class=\"dl-horizontal\">\n" + " <dt>Name</dt>\n" + " <dd>{{resource.metadata.name}}</dd>\n" + " <dt>Namespace</dt>\n" + " <dd>{{resource.metadata.namespace}}</dd>\n" + " <dt>Created</dt>\n" + " <dd>{{resource.metadata.creationTimestamp | date:'medium'}}</dd>\n" + " <dt>Host</dt>\n" + " <dd>{{resource.host}}</dd>\n" + " <dt>Path</dt>\n" + " <dd>{{resource.path || 'None'}}</dd>\n" + " <dt>Service Name</dt>\n" + " <dd>{{resource.serviceName}}</dd>\n" + " </dl>\n" + " <div ng-if=\"resource.tls && resource.tls.termination\">\n" + " <dl class=\"dl-horizontal\">\n" + " <dt>TLS Termination</dt>\n" + " <dd>{{resource.tls.termination}}</dd>\n" + " <dt>Certificate</dt>\n" + " <dd>{{(resource.tls.certificate) ? '*****' : 'None'}}</dd>\n" + " <dt>Key</dt>\n" + " <dd>{{(resource.tls.key) ? '*****' : 'None'}}</dd>\n" + " <dt>CA Certificate</dt>\n" + " <dd>{{(resource.tls.caCertificate) ? '*****' : 'None'}}</dd>\n" + " <dt>Destination CA Cert</dt>\n" + " <dd>{{(resource.tls.destinationCACertificate) ? '*****' : 'None'}}</dd>\n" + " </dl>\n" + " </div>\n" + " <kubernetes-object-describe-labels resource=\"resource\"></kubernetes-object-describe-labels>\n" + " <kubernetes-object-describe-annotations resource=\"resource\"></kubernetes-object-describe-annotations>\n" + " <kubernetes-object-describe-footer resource=\"resource\"></kubernetes-object-describe-footer>\n" + "</div>\n" ); }]); <file_sep>window.EXAMPLE_DEP_CONFIG = { "kind": "DeploymentConfig", "apiVersion": "v1beta1", "metadata": { "name": "frontend", "namespace": "test", "selfLink": "/osapi/v1beta1/deploymentConfigs/frontend?namespace=test", "uid": "3626ef31-e208-11e4-bdc4-54ee75107c12", "resourceVersion": "146", "creationTimestamp": "2015-04-13T18:09:22Z", "labels": { "template": "application-template-stibuild" } }, "triggers": [ { "type": "ImageChange", "imageChangeParams": { "automatic": true, "containerNames": [ "ruby-helloworld" ], "from": { "kind": "ImageRepository", "name": "origin-ruby-sample" }, "tag": "latest", "lastTriggeredImage": "172.30.73.77:5000/test/origin-ruby-sample:7d7d7af5551062c36e680a81bfbd6598c9934b41139d9ed6c8ef13a64b9ffe72" } }, { "type": "ConfigChange" } ], "template": { "strategy": { "type": "Recreate" }, "controllerTemplate": { "replicas": 1, "replicaSelector": { "name": "frontend" }, "podTemplate": { "desiredState": { "manifest": { "version": "v1beta2", "id": "", "volumes": null, "containers": [ { "name": "ruby-helloworld", "image": "172.30.73.77:5000/test/origin-ruby-sample:7d7d7af5551062c36e680a81bfbd6598c9934b41139d9ed6c8ef13a64b9ffe72", "ports": [ { "containerPort": 8080, "protocol": "TCP" } ], "env": [ { "name": "ADMIN_USERNAME", "key": "ADMIN_USERNAME", "value": "admin4OS" }, { "name": "ADMIN_PASSWORD", "key": "ADMIN_PASSWORD", "value": "<PASSWORD>" }, { "name": "MYSQL_USER", "key": "MYSQL_USER", "value": "userTJW" }, { "name": "MYSQL_PASSWORD", "key": "MYSQL_PASSWORD", "value": "<PASSWORD>" }, { "name": "MYSQL_DATABASE", "key": "MYSQL_DATABASE", "value": "root" } ], "resources": {}, "terminationMessagePath": "/dev/termination-log", "imagePullPolicy": "PullIfNotPresent", "capabilities": {} } ], "restartPolicy": { "always": {} }, "dnsPolicy": "ClusterFirst" } }, "labels": { "name": "frontend", "template": "application-template-stibuild" } } } }, "latestVersion": 1, "details": { "causes": [ { "type": "ImageChange", "imageTrigger": { "repositoryName": "172.30.73.77:5000/test/origin-ruby-sample:7d7d7af5551062c36e680a81bfbd6598c9934b41139d9ed6c8ef13a64b9ffe72", "tag": "latest" } } ] } };<file_sep>window.EXAMPLE_BUILD = { "kind": "Build", "apiVersion": "v1beta1", "metadata": { "name": "ruby-sample-build-1", "namespace": "test", "selfLink": "/osapi/v1beta1/builds/ruby-sample-build-1?namespace=test", "uid": "3905d694-e208-11e4-bdc4-54ee75107c12", "resourceVersion": "161", "creationTimestamp": "2015-04-13T18:09:27Z", "labels": { "buildconfig": "ruby-sample-build", "name": "ruby-sample-build", "template": "application-template-stibuild" } }, "parameters": { "source": { "type": "Git", "git": { "uri": "git://github.com/openshift/ruby-hello-world.git" } }, "strategy": { "type": "STI", "stiStrategy": { "builderImage": "openshift/ruby-20-centos7:latest", "image": "openshift/ruby-20-centos7:latest" } }, "output": { "to": { "kind": "ImageStream", "name": "origin-ruby-sample" }, "dockerImageReference": "172.30.73.77:5000/test/origin-ruby-sample", "imageTag": "test/origin-ruby-sample", "registry": "172.30.73.77:5000" } }, "status": "Complete", "startTimestamp": "2015-04-13T18:09:30Z", "completionTimestamp": "2015-04-13T18:11:30Z", "config": { "kind": "BuildConfig", "namespace": "test", "name": "ruby-sample-build" } };<file_sep>'use strict'; try { angular.module("openshiftUI") } catch(e) { angular.module("openshiftUI", []) } angular.module("openshiftUI").requires.push("kubernetesUI"); angular.module('openshiftUI') .filter('imageRepoReference', function(){ return function(objectRef, tag){ tag = tag || "latest"; var ns = objectRef.namespace || ""; ns = ns == "" ? ns : ns + "/"; var ref = ns + objectRef.name; ref += " [" + tag + "]"; return ref; }; }) .run(function(KubernetesObjectDescriber) { KubernetesObjectDescriber.registerKind("Build", "views/build.html") KubernetesObjectDescriber.registerKind("DeploymentConfig", "views/deployment-config.html") KubernetesObjectDescriber.registerKind("Route", "views/route.html") });
a91bcebba868ebbdb74695b7b9cbfa99f8c2f32c
[ "JavaScript" ]
4
JavaScript
liggitt/openshift-object-describer
f6d12915fe1ba42cc72f86aa0fd5049a51ff97ad
4ab0e169403f0487cd509808c62b06fcf04eceb4
refs/heads/main
<file_sep>#!/bin/bash echo "start the docker compose" docker-compose -p zipkin-monitoring -f zipkin-compose.yml up -d --remove-orphans<file_sep>package com.example.springredisdood.bill; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import javax.annotation.Resource; import java.util.Optional; /** * @author aroussi * @version %I% %G% */ @Service class BillService { @Resource(name = "redisTemplate") private ValueOperations<String, Object> valueOps; public void saveBill(Bill bill) { Assert.notNull(bill, "Bill should not be null"); valueOps.set(bill.getRef(), bill); } public Optional<Bill> findBillById(String ref) { Assert.notNull(ref, "ref should not be null"); return Optional.ofNullable((Bill)valueOps.get(ref)); } } <file_sep>spring.redis.host=localhost spring.redis.port=6379 spring.application.name=spring-dood spring.jackson.serialization.write-dates-as-timestamps=false spring.jackson.deserialization.adjust-dates-to-context-time-zone=true spring.jackson.deserialization.accept-empty-string-as-null-object=true spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=aroussi spring.rabbitmq.password=<PASSWORD> spring.rabbitmq.virtual-host=rabbitmq_vhost spring.zipkin.service.name=spring-redis-dood spring.zipkin.rabbitmq.addresses=localhost:5672 spring.zipkin.rabbitmq.queue=zipkin_queue spring.zipkin.sender.type=rabbit <file_sep># POC for spring boot / Redis and zipkin This POC demonstrate the use of spring boot application that store data in Redis and that is monitored using zipkin. ### Before running the application You should have a running zipkin server on localhost or simply use the docker compose manifest inside `docker-compose` folder. compose file can be run via the sh : ```sh ./docker-compose/start-docker.sh ``` > make sure that the sh file is executable. > The zipkin server start on port 9411, you can access zipkin ui using `http://localhost:9411`. Then you can start the application using : ```sh ./gradlew bootRun ``` #### Endpoints: > GET a bill : ```sh curl -H "Content-Type: application/json" http://localhost:8080/bills/123 ``` > CREATE a bill ```sh curl -H "Content-Type: application/json" -X POST -d '{"ref":"123", "amount":123.5}' http://localhost:8080/bills ``` <file_sep>package com.example.springredisdood.bill; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; /** * @author aroussi * @version %I% %G% */ @RequestMapping(value = "/bills") @RestController @RequiredArgsConstructor class BillController { private final BillService billService; @GetMapping(value = "/{ref}") public ResponseEntity findBillByRef(@PathVariable String ref) { return billService.findBillById(ref).map(ResponseEntity::ok).orElse(ResponseEntity.badRequest().build()); } @PostMapping public ResponseEntity saveBill(@RequestBody Bill bill) { billService.saveBill(bill); return ResponseEntity.ok().build(); } } <file_sep>package com.example.springredisdood.bill; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.experimental.SuperBuilder; /** * @author aroussi * @version %I% %G% */ @Getter @SuperBuilder @NoArgsConstructor class Bill { private String ref; private String clientRef; private Double amount; } <file_sep>package com.example.springredisdood; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.testcontainers.containers.GenericContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @Testcontainers public class SpringRedisDoodApplicationTests { @Container public static GenericContainer redis = new GenericContainer("redis:6.0.10"); @DynamicPropertySource static void configure(DynamicPropertyRegistry registry) { registry.add("spring.redis.host", redis::getHost); registry.add("spring.redis.port", redis::getFirstMappedPort); } } <file_sep>rootProject.name = 'spring-redis-dood' <file_sep>package com.example.springredisdood.bill.infrastructure; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * @author aroussi * @version %I% %G% */ @Configuration class RedisConfig { @Bean RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } }
0450fc4a477d2f5418018a043deb4b28c2aa9b00
[ "Markdown", "INI", "Gradle", "Java", "Shell" ]
9
Shell
roussi/spring-redis-zipkin
bc8e7dc6bdbb5c88fccfcc5909fbf53a66953c86
6f25df1f352e078cc8d8697354f8bb87ec50d514
refs/heads/master
<file_sep>$(document).ready(function () { var source = $("#movie-info-template").html(); //richiamo del template di handlebars var template = Handlebars.compile(source); var urlBase = 'https://api.themoviedb.org/3'; $('button').click(function() { // al click del bottone salvo nella variabile chiaveRicerca l'input acquisito dall'HTML var chiaveRicerca = $('#ricerca').val(); $('.informazioni-film').empty(); // console.log(chiaveRicerca); cercaShow(chiaveRicerca, 'movie'); cercaShow(chiaveRicerca, 'tv'); }); $('#ricerca').keydown(function(event) { var chiaveRicerca = $('#ricerca').val(); if(event.keyCode == '13') { $('.informazioni-film').empty(); cercaShow(chiaveRicerca, 'movie'); cercaShow(chiaveRicerca, 'tv'); } }); function cercaShow (input, tipo) { $.ajax({ //chiamata ajax al database di themoviedb per cercare film e serie tv url: urlBase + '/search/' + tipo, data: { api_key: '<KEY>', query: input, language: 'it-IT' }, method: 'GET', success: function (data) { var dataShow = data.results; createCard(dataShow); }, error: function (err) { alert('ERRORISSIMO!!!!!'); } }); }; function createCard (dataInput) { //ciclo for per passare i valori a handlebars for (var i = 0; i < dataInput.length; i++) { var infoShow = dataInput[i]; var info = { titoloSerie: infoShow.name, titolo: infoShow.title, titoloOriginaleSerie: infoShow.original_name, titoloOriginale: infoShow.original_title, linguaOriginale: bandierine(infoShow.original_language), voto: stelleVoto(infoShow.vote_average), plot: infoShow.overview, copertina: posterCopertina(infoShow.poster_path) }; var specificheShow = template(info); //collegamento handlebars $('.informazioni-film').append(specificheShow); }; }; function posterCopertina (valoreApiCover) { //funzione per aggiungere l'immagine di copertina if (valoreApiCover !== null) { var urlBaseCover = 'https://image.tmdb.org/t/p/'; var dimensione = 'w342/'; return '<img class="cover" src="' + urlBaseCover + dimensione + valoreApiCover + '">'; } else { return '<img class="cover" src="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Flascrucesfilmfest.com%2Fwp-content%2Fuploads%2F2018%2F01%2Fno-poster-available.jpg&f=1&nofb=1">'; }; }; function bandierine (siglaNazione) { //funzione per trasformare la lingua in bandierine console.log(siglaNazione); var flag = ''; if (siglaNazione == 'en') { flag = 'gb'; } else if (siglaNazione == 'ja') { flag = 'jp'; } else if (siglaNazione == 'zh') { flag = 'cn'; } else if (siglaNazione == 'ko') { flag = 'kr'; } else { flag = siglaNazione; } return '<img src="https://www.countryflags.io/' + flag + '/flat/16.png">' } function stelleVoto (valutazione) { //funzione per trasformare la valutazione in stelline var recensione = Math.ceil(valutazione / 2); var arrayStelleVoto = []; var a = 0; for (var i = 0; i < 5; i++) { if (a < recensione) { arrayStelleVoto.push('<i class="fas fa-star"></i>'); a = a + 1; } else { arrayStelleVoto.push('<i class="far fa-star"></i>'); } } return arrayStelleVoto.join(''); }; });
08858964c79c872cd3e69536e0114117171b3260
[ "JavaScript" ]
1
JavaScript
Davide-Roberti/ajax-ex-boolflix
900af0d96ff2a51fd5a472dd0572932d039ecc5d
f9eb3a93fbad6cf65e30cd958ff304049c6c2972
refs/heads/master
<repo_name>lauragmz/proyecto-intro-ciencia-de-datos<file_sep>/clean_data.py # Definición de la función limpiar_columna que realiza las siguientes transformaciones al nombre de una columna: # 1. Convertir a minúsculas # 2. Reemplazar espacios por guiones bajo # 3. Eliminar puntos # 4. Eliminar acentos # 5. Eliminar comas def limpiar_columna(nombre_columna): return nombre_columna.lower()\ .replace(' ','_')\ .replace('.','')\ .replace('á','a').replace('é','e').replace('í','i').replace('ó','o').replace('ú','u')\ .replace(',','') # Definición de la función limpiar_encabezado que aplica la función anterior para "limpiar" los nombres de todas las columnas que conforman al dataframe y devuelve un arreglo con los nombres limpios de las columnas def limpiar_encabezado (df): columnas_limpias = [] for i in range(0,len(df.columns)): nombre_columna_limpia = limpiar_columna(df.columns[i]) columnas_limpias.append(nombre_columna_limpia) return columnas_limpias # Definición de la función reemplazar_columnas que reemplaza los nombres originales de las de una dataframe, por los nombres en formato limpio o estandar y devuelve el dataframe con los nombres de columnas en formato estandar def reemplazar_columnas(df,columnas_limpias): for i in range(0,len(df.columns)): df.rename(columns = {df.columns[i]: columnas_limpias[i]}, inplace = True) return df # Definición de la función estandarizar_columnas que utiliza las funciones anteriores para estandarizar (tranformar a minúsculas, eliminar acentos, reemplazar espacios y eliminar ciertos caracteres) los nombres de las columnas de un dataframe y devolver un dataframe con los nombres de columna ya transformados def estandarizar_columnas(df): columnas_limpias = limpiar_encabezado(df) df_columnas_limpias = reemplazar_columnas(df,columnas_limpias) return df_columnas_limpias<file_sep>/transform_data.py # Definición de la función tranformar_minusculas que recibe como argumento un dataframe, convierte a minúsculas la información contenida en cada una de las columnas y devuelve el dataframe con esta modificación. def transformar_minusculas(df,columnas): return df.apply(lambda x: x.astype(str).str.lower() if x.name in columnas else x) # Definición de la función eliminar_signos que recibe como argumento un dataframe con información en minúsculas y aplica las siguientes transformaciones: # 1. Eliminación de acentos # 2. Reemplazo de espacios por guiones bajo # 3. Eliminación de comas, puntos, punto y coma, signos de mas # 4. Transformación de los "nan" a "NaN" # y devuelve un dataframe con todas estas modificaciones. def eliminar_signos(df,columnas): return df.apply(lambda x: x.astype(str).str.replace('á','a'). str.replace('é','e'). str.replace('í','i'). str.replace('ó','o'). str.replace('ú','u'). str.replace(' ','_'). str.replace(',',''). str.replace('.',''). str.replace(';',''). str.replace('+',''). str.replace('nan','NaN') if x.name in columnas else x) # Definición de la función estandarizar_datos que recibe como argumento un dataframe, utiliza las dos funciones anteriores para estandarizar (convertir a minúsculas, reemplazar espacios por guiones bajo y eliminar ciertos caracteres) la información de dicho dataframe y deveuelve un nuevo dataframe en formato estandar. def estandarizar_datos(df): df_minusculas = transformar_minusculas(df,df.columns) df_estandar = eliminar_signos(df_minusculas,df_minusculas.columns) return df_estandar # Definición de la función eliminar_variables que recibe como argumento una dataframe y una lista con el nombre de las columnas a eliminar; y devuelve el dataframe con las columnas reducidas def eliminar_variables(df,lista_columnas): df_reducido =df.drop(lista_columnas, axis =1) return df_reducido # Definición de la función convertir_variable que recibe como argumento un dataframe, la columna que quiere transfomarse y el tipo de variable al que desea transformarse; y devuelve un nuevo dataframe con las variables ya transformadas def convertir_variable(df,columna,tipo_variable): df_convertido = df.astype({columna:tipo_variable}) return df_convertido<file_sep>/README.md # Proyecto-intro-ciencia-de-datos Código utilizado para el Proyecto Final de la materia Introducción a Ciencia de Datos, de la maestría en Ciencia de Datos del ITAM. Los modulos *load_data.py*, *clean_data.py* y *transform_data.py* fueron creados específicamente para este proyecto. El archivo *proyecto_parte1.ipynb* incluye código y argumentos del proyecto. Debido al tamaño del archivo, es necesario descargar o clonar el repositorio para su lectura. El archivo *proyecto_parte1_nodataprof.ipynb* no incluye el data profiling y permite la visualización directa (sin necesidad de descargar o cloner el repositorio). <file_sep>/load_data.py # Definición de la función cargar_datos que permite: # 1. Leer un archivo csv, separado por punto y coma # 2. Guardarlo en un objeto de tipo dataframe (df) # 3. Imprimir el número de observaciones y variables import pandas as pd def cargar_datos(archivo_csv): datos_df = pd.read_csv(archivo_csv, sep = ';') print('Número de observaciones: ',datos_df.shape[0]) print('Número de variables: ',datos_df.shape[1]) return datos_df
63a6794517962d0ab0bb1b6f4074c45b8171e011
[ "Markdown", "Python" ]
4
Python
lauragmz/proyecto-intro-ciencia-de-datos
949e8e782e9ed406a86d5e319477e961e6826ad9
85d3cbf927f7c74739a89caea92432a751015d65
refs/heads/master
<repo_name>Cappibara/spreadsheet-to-pdf<file_sep>/test.py import os import re import win32com.client as win32 from tkinter import * TEMPLATE_PATH = os.getcwd() + '/templates/' RANGE = range(3, 8) ADD_REGEX = re.compile('.*(add).*', re.IGNORECASE) MULTIPLY_REGEX = re.compile('.*(multiply).*', re.IGNORECASE) excel = 0 ss = 0 word = 0 doc = 0 # This will contain all enums/module constants from coms bound with EnsureDispatch COM_CONSTANTS = win32.constants #---------------------------------------------------------------------- def excelToWord(invoiceNum): setup() spreadsheet = openExcel() openWordTemplate(spreadsheet, 'Tribals.docx', invoiceNum) cleanup() def setup(): global word, excel word = win32.gencache.EnsureDispatch('Word.Application') excel = win32.gencache.EnsureDispatch('Excel.Application') def cleanup(): ss.Close(False) excel.Application.Quit() doc.SaveAs( os.getcwd() + '/test.docx' ) doc.ExportAsFixedFormat(os.getcwd() + '/test.pdf', COM_CONSTANTS.wdExportFormatPDF) doc.Close(False) word.Application.Quit() def openExcel(): global excel, ss ss = excel.Workbooks.Open( os.getcwd() + '/test_sheet') sh = ss.ActiveSheet excel.Visible = False return sh def openWordTemplate(spreadsheet, templateName, invoiceNum): global word, doc doc = word.Documents.Open(TEMPLATE_PATH + templateName) selection = word.Selection word.Visible = False rng = doc.Range(0,0) index = 2 val = spreadsheet.Cells(index,1).Value sum = 0 product = 1 while val: numVal = spreadsheet.Cells(index,2).Value if( ADD_REGEX.match(val) != None ): sum += numVal elif( MULTIPLY_REGEX.match(val) != None ): product = product * numVal index += 1 val = spreadsheet.Cells(index,1).Value selection.Find.Execute('_invoice_num_')#, ReplaceWith = invoiceNum, Replace = True) selection.Text = invoiceNum selection.WholeStory() selection.Find.Execute('_amount_') selection.Text = fillWithWhitespace(str(sum), len(selection.Text)) def fillWithWhitespace(str, expectedSize): #TODO This will need to use the largest amount (num of digits) as expected difference = expectedSize - len(str) if(difference <= 0): return str else: return (' ' * difference) + str def getInputs(): def submit(): excelToWord( invoiceEntry.get() ) window.quit() window = Tk() invoiceLabel = Label(window, text = 'Invoice #:') invoiceLabel.pack() invoiceEntry = Entry(window, width = 20) invoiceEntry.pack() submitButton = Button(window, text = "Submit", command = submit) submitButton.pack() exitButtonWidget = Button(window, text = "Exit", command = window.quit, bg = "red") exitButtonWidget.pack() window.mainloop() if __name__ == "__main__": getInputs()<file_sep>/README.md # spreadsheet-to-pdf Script for translating spreadsheets from Sage 50 (excel) -> Word -> Pdf
7e440388a846af759dc1c7bfe5d47e003f1fb86c
[ "Markdown", "Python" ]
2
Python
Cappibara/spreadsheet-to-pdf
f5d503c4e062d08c37ea0e4e94bf42c62e35cc72
03ddde5f632d3349470a573a704dcc7e4765d02a
refs/heads/master
<repo_name>create-account/my-react-elec<file_sep>/src/components/SideBox.js import React, { Component } from 'react'; import { Box } from 'grommet'; export default class SideBox extends Component { render() { const { children, show } = this.props; const display = show ? ( <Box width='small' background='light-2' elevation='small' align='center' justify='center' > {children} </Box> ) : null; return display; } }<file_sep>/src/App.js import React, { Component } from 'react'; import { Grommet, Box } from 'grommet'; import { Sidebar } from 'grommet-icons'; import { connect } from 'react-redux'; import AppBar from './components/AppBar'; import SideBox from './components/SideBox'; const theme = { global: { // colors: { // brand: '#0096D6' // }, font: { family: 'Roboto', size: '14px', height: '20px', }, }, }; class App extends Component { render() { return ( <Grommet theme={theme}> <Box fill> <AppBar name='Easy Art Maker' icon={<Sidebar />} /> <SideBox show={this.props.sidebar} > Sidebar is gere </SideBox> </Box> </Grommet> ); } } const mapStateToProps = state => { console.log(state); return state; } export default connect(mapStateToProps)(App); <file_sep>/src/components/AppBar.js import React from 'react'; import { Box, Button, Heading } from 'grommet'; import { connect } from 'react-redux'; import { toggleSideBox } from '../actions'; const AppBar = (props) => { const { name, icon } = props; return ( <Box tag='header' direction='row' align='center' background='brand' pad={{ left: 'small', right: 'small', vertical: 'small' }} elevation='medium' style={{ zIndex: '100' }} {...props} > <Button icon={icon} onClick={() => {props.toggleSideBox()}} /> <Heading level='4' margin='none'>{name}</Heading> </Box> ); } const mapStateToProps = (state) => { console.log(state); return state; } export default connect(mapStateToProps, { toggleSideBox })(AppBar);
8354d559f98f68b372e6439fae0f21491d55ec5d
[ "JavaScript" ]
3
JavaScript
create-account/my-react-elec
cf43ee0c1048b6e45b836f6579edd8e7252ce2dd
362f838fa45ae4192427b43b3cc556feac505bcf
refs/heads/main
<repo_name>fayeed/holochain-test-action<file_sep>/README.md # holochain-test-action <file_sep>/scripts/add-osx-cert.sh ## Taken from https://github.com/Zettlr/Zettlr/blob/develop/scripts/add-osx-cert.sh #!/usr/bin/env sh # This script takes the macOS code sign certificate from the secret env # variable, saves it on the runner, and finally adds it to the keychain # so that electron-forge can access it to sign the built app. # Original source of this script: # https://dev.to/rwwagner90/signing-electron-apps-with-github-actions-4cof KEY_CHAIN=build.keychain CERT_FILE=certificate.p12 # Recreate the certificate from the secure environment variable echo "$COMMUNITIES_APPLE_CERT" | base64 --decode > $CERT_FILE # Create a new keychain using the password "actions" security create-keychain -p actions $KEY_CHAIN # Make the keychain the default so that electron-forge finds it security default-keychain -s $KEY_CHAIN # Unlock the keychain using the previously chosen, very secure password security unlock-keychain -p actions $KEY_CHAIN # Set keychain locking timeout to 3600 seconds security set-keychain-settings -t 3600 -u $KEY_CHAIN # Import our certificate into the (now default) created keychain and also allow # the codesign binary to access said certificate. security import $CERT_FILE -k $KEY_CHAIN -P "$COMMUNITIES_APPLE_CERT_PASSWORD" -T /usr/bin/codesign; security list-keychains -s build.keychain # Since macOS Sierra, the following command is necessary. # Further information: https://stackoverflow.com/a/40039594 security set-key-partition-list -S apple-tool:,apple: -s -k actions $KEY_CHAIN # Remove the certificate file again rm -f $CERT_FILE<file_sep>/scripts/get-holochain.sh #!/usr/bin/env sh [ ! -d "./resources" ] && mkdir "./resources" [ ! -d "./resources/temp" ] && mkdir "./resources/temp" HOLOCHAIN_VER="f3d17d993ad8d988402cc01d73a0095484efbabb" echo "Getting holochain from GitHub" [ ! -d "./resources/temp/lair" ] && git clone https://github.com/holochain/lair ./resources/temp/lair [ ! -d "./resources/temp/holochain" ] && git clone https://github.com/holochain/holochain ./resources/temp/holochain cd ./resources/temp/holochain && git checkout $HOLOCHAIN_VER<file_sep>/scripts/copy-hc.sh #!/bin/bash [ ! -d "./resources" ] && mkdir "./resources" if [[ "$OSTYPE" == "linux-gnu"* ]]; then [ ! -d "./resources/linux" ] && mkdir "./resources/linux" [ -f "./resources/linux/holochain" ] && rm ./resources/linux/holochain cp `which holochain` ./resources/linux/ && echo "Copied Holochain to resources" [ -f "./resources/linux/lair-keystore" ] && rm ./resources/linux/lair-keystore cp `which lair-keystore` ./resources/linux/ && echo "Copied lair to resources" [ -f "./resources/linux/hc" ] && rm ./resources/linux/hc cp `which hc` ./resources/linux/ && echo "Copied hc to resources" elif [[ "$OSTYPE" == "darwin"* ]]; then [ ! -d "./resources/darwin" ] && mkdir "./resources/darwin" [ -f "./resources/darwin/holochain" ] && rm ./resources/darwin/holochain cp `which holochain` ./resources/darwin && echo "Copied Holochain to resources" [ -f "./resources/darwin/lair-keystore" ] && rm ./resources/darwin/lair-keystore cp `which lair-keystore` ./resources/darwin && echo "Copied lair to resources" [ -f "./resources/darwin/hc" ] && rm ./resources/darwin/hc cp `which hc` ./resources/darwin/ && echo "Copied hc to resources" else echo "Sorry your OS type is not supported" fi<file_sep>/scripts/clean-state.command #!/bin/bash if [[ "$OSTYPE" == "linux-gnu"* ]]; then path="$HOME/.config/junto" elif [[ "$OSTYPE" == "darwin"* ]]; then path="$HOME/Library/Application Support/junto" fi echo "Will delete path: $path" # read -p "IS THIS CORRECT? (y/n) " answer # if [[ $answer =~ ^[Yy]$ ]] ; # then # echo "Accepted, deleting directory" rm -rf $path # else # echo "Not deleting" # fi <file_sep>/scripts/get-languages.js const fs = require("fs-extra"); const wget = require("node-wget-js"); const unzipper = require("unzipper"); const path = require("path"); const languages = { profiles: { targetDnaName: "agent-profiles", dna: "https://github.com/jdeepee/profiles/releases/download/0.0.4/agent-profiles.dna", bundle: "https://github.com/jdeepee/profiles/releases/download/0.0.4/bundle.js", }, "agent-expression-store": { targetDnaName: "agent-store", dna: "https://github.com/perspect3vism/agent-language/releases/download/0.0.4/agent-store.dna", bundle: "https://github.com/perspect3vism/agent-language/releases/download/0.0.4/bundle.js", }, "neighbourhood-store": { targetDnaName: "neighbourhood-store", //dna: "https://github.com/perspect3vism/neighbourhood-language/releases/download/0.0.2/neighbourhood-store.dna", bundle: "https://github.com/perspect3vism/neighbourhood-language/releases/download/0.0.3/bundle.js", }, languages: { targetDnaName: "languages", dna: "https://github.com/perspect3vism/language-persistence/releases/download/0.0.3/languages.dna", bundle: "https://github.com/perspect3vism/language-persistence/releases/download/0.0.3/bundle.js", }, "group-expression": { targetDnaName: "group-expression", dna: "https://github.com/juntofoundation/Group-Expression/releases/download/0.0.3/group-expression.dna", bundle: "https://github.com/juntofoundation/Group-Expression/releases/download/0.0.3/bundle.js", }, "shortform-expression": { targetDnaName: "shortform-expression", dna: "https://github.com/juntofoundation/Short-Form-Expression/releases/download/0.0.2/shortform-expression.dna", bundle: "https://github.com/juntofoundation/Short-Form-Expression/releases/download/0.0.2/bundle.js", }, "social-context": { zipped: true, targetDnaName: "social-context", resource: "https://github.com/juntofoundation/Social-Context/releases/download/0.0.12/full_index.zip", }, "social-context-channel": { zipped: true, targetDnaName: "social-context", resource: "https://github.com/juntofoundation/Social-Context/releases/download/0.0.12/signal.zip", }, }; async function main() { await fs.ensureDir("./ad4m"); await fs.ensureDir("./ad4m/languages"); for (const lang in languages) { const dir = `./ad4m/languages/${lang}`; await fs.ensureDir(dir + "/build"); // bundle if (languages[lang].bundle) { let url = languages[lang].bundle; let dest = dir + "/build/bundle.js"; wget({ url, dest }); } // dna if (languages[lang].dna) { url = languages[lang].dna; dest = dir + `/${languages[lang].targetDnaName}.dna`; wget({ url, dest }); } if (languages[lang].zipped) { await wget( { url: languages[lang].resource, dest: `${dir}/lang.zip`, }, async () => { //Read the zip file into a temp directory await fs .createReadStream(`${dir}/lang.zip`) .pipe(unzipper.Extract({ path: `${dir}` })) .promise(); // if (!fs.pathExistsSync(`${dir}/bundle.js`)) { // throw Error("Did not find bundle file in unzipped path"); // } fs.copyFileSync( path.join(__dirname, `../${dir}/bundle.js`), path.join(__dirname, `../${dir}/build/bundle.js`) ); fs.rmSync(`${dir}/lang.zip`); fs.rmSync(`${dir}/bundle.js`); } ); } } } main();
175d8b2d37b9cd7f2878c628ec3f52a673eb267f
[ "Markdown", "JavaScript", "Shell" ]
6
Markdown
fayeed/holochain-test-action
bc3f5821a047a0a837c166cc1e4f3ef8228a190f
6390d4ca1f16800427565656b403470e92b997dd
refs/heads/master
<repo_name>Degnath/Profile-Page<file_sep>/script.js function changeProfile(element){ var element = document.getElementById("switchName"); element.innerText ="Deg"; } function connectionChange(element){ var element= document.getElementById("connectionChange"); element.innerText -=1; } function hide(id) { var e = document.getElementById(id); e.remove(); } <file_sep>/ja/js.js function reverse(arr){ for(var i = 0; i < arr.length/2; i++) { var temp = arr[i] arr[i] = arr[arr.length-1-i] arr[arr.length-1-i] = temp; } return arr; } console.log(reverse(["a", "b", "c", "d", "e"])); function fizzBuzz() { var result = ""; for(var i = 1; i <= 100; i++) { result = result + (i % 15 == 0 ? "FizzBuzz\n": (i % 5 ==0)? "Buzz\n": (i%3==0) ? "Fizz\n": ""+i +"\n"); } console.log(result); } fizzBuzz(1,100);
4f6b86d20d07ad6304606bbd394445007f378eda
[ "JavaScript" ]
2
JavaScript
Degnath/Profile-Page
35e2681ab3d4d3f1ef10d2539723c00e932542cc
422d52cb8193b3082e5c442730f84d7c5449e7e4
refs/heads/master
<file_sep>''' Created on 30-Jul-2017 @author: Suresh ''' from builtins import input print("Hello World!\n") while True: print("Enter 'x' for Exit. ") print("Enter any number: ") value = input() if (value=='x') : print("Value of expression is x") print(value) print("Exit\n") break print("if-else Condition") print("--------------------") if(int(value)==1): print("Value of expression is 1") print(value) elif(int(value)==2): print("Value of expression is 2") print(value) elif(int(value)==3): print("Value of expression is 3") print(value) print("Thank you\n") print("Nested if-else Condition") print("---------------------------") if(int(value)<=3): if(int(value)==1): print("Value of expression is 1") print(value) elif(int(value)==2): print("Value of expression is 2") print(value) elif(int(value)==3): print("Value of expression is 3") print(value) else: print("Value of expression is not less than 3") print(value) print("Thank you\n") <file_sep>''' Created on 03-Jun-2017 @author: Suresh ''' from Tkinter import * root = Tk() # Create the root (base) window where all widgets go w = Label(root, text="Hello, world!") # Create a label with words w.pack() # Put the label into the window root.mainloop() # Start the event loop
e7ed15e898600a981059c1cde9984c88be2c3f3d
[ "Python" ]
2
Python
msuresh168/Python
9b4aedf106680095f51490a9c459028854541d71
98e0528d0ba271e89e519b494860b7da05127ff8
refs/heads/master
<repo_name>kcookva/Imgupload<file_sep>/models/users.js var mongoose = require("mongoose"); var Schema = mongoose.Schema; var path = require("path"); mongoose.connection.on('open', function() { console.log("Mongoose connected!"); }); var userSchema = new Schema({ username: { type: String }, password: { type: String }, admin: {type: Boolean}, }); var User = mongoose.model('User', userSchema); var users = new User(); module.exports = { users:users, User:User }<file_sep>/models/images.js var mongoose = require("mongoose"); var Schema = mongoose.Schema; var path = require("path"); mongoose.connection.on('open', function() { console.log("Mongoose connected!"); }); var imageSchema = new Schema({ title: { type: String }, filename: { type: String }, folder: {type: String}, mimetype: {type: String}, size: {type: Number} }); var Image = mongoose.model('Image', imageSchema); var images = new Image(); module.exports = { images:images, Image:Image }<file_sep>/controllers/folders.js module.exports = { uploads: function(req,res){ if(req.session.user){ var Image = require("../models/images").Image; Image.find({'folder':"uploads"}, function(err,docs){ var displayedimages = docs; res.render("showimages", {displayedimages:displayedimages, session:req.session.user, sessionstatus:req.session.status}); }); }else{ res.redirect("/"); }; }, good: function(req,res){ if(req.session.user){ var Image = require("../models/images").Image; Image.find({'folder':"good"}, function(err,docs){ var displayedimages = docs; res.render("showimages", {displayedimages:displayedimages, session:req.session.user, sessionstatus:req.session.status}); }); }else{ res.redirect("/"); }; }, better: function(req,res){ if(req.session.user){ var Image = require("../models/images").Image; Image.find({'folder':"better"}, function(err,docs){ var displayedimages = docs; res.render("showimages", {displayedimages:displayedimages, session:req.session.user, sessionstatus:req.session.status}); }); }else{ res.redirect("/"); }; }, best: function(req,res){ if(req.session.user){ var Image = require("../models/images").Image; Image.find({'folder':"best"}, function(err,docs){ var displayedimages = docs; res.render("showimages", {displayedimages:displayedimages,session:req.session.user, sessionstatus:req.session.status}); }); }else{ res.redirect("/"); }; } }<file_sep>/controllers/home.js module.exports = { index: function(req, res){ res.render("home"); // res.render("test") }, login: function(req, res){ var User = require("../models/users").User; req.checkBody('username', 'Username is required').notEmpty(); req.checkBody('password', '<PASSWORD>').notEmpty(); var errors = req.validationErrors(); if(errors){ res.render("home", { errors:errors }); }else{ var founduser = User.findOne({username:req.body.username, password:<PASSWORD>}, function(err,docs){ if(docs){ var dbusername = docs.username; var dbpassword = <PASSWORD>; var dbstatus = docs.admin; var dbid = docs.objectId; if(err){ incorrecterrors = "There was an error logging you in." res.render("home", {incorrecterrors:incorrecterrors}); }else{ console.log("Username/Password has been entered"); req.session.user = dbusername; req.session.status = dbstatus; console.log("correct"); res.redirect("client"); } }else{ res.render("home"); } }); } }, logout: function(req,res){ req.session.destroy(); console.log("logged out!"); res.redirect('/'); } }<file_sep>/README.md "# Imgupload" <file_sep>/server/routes.js var express = require("express"); var home = require('../controllers/home'); var client = require('../controllers/client'); var path= require("path"); var multer = require("multer"); var upload = multer().single('fileToUpload'); var images = require("../controllers/image"); var folders = require("../controllers/folders"); var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'public/img/' + req.body.folder); }, filename: function (req, file, cb) { cb(null, req.body.title + '-' + Date.now() + path.extname(file.originalname)); } }); var upload = multer({ storage: storage }); module.exports = function(app) { var router = express.Router(); app.use('/', router); router.get('/', home.index); router.post("/", home.login); router.get('/client', client.home); router.post('/upload', upload.single('fileToUpload'), images.upload); router.get("/view", images.view); router.get('/uploads', folders.uploads); router.get('/good', folders.good); router.get('/better', folders.better); router.get('/best', folders.best); router.post('/delete', images.delete); router.post("/out", home.logout); }
d79eb3f584d48ca5334d0008617cec593fd5f75f
[ "JavaScript", "Markdown" ]
6
JavaScript
kcookva/Imgupload
cd6c19f98f73006c61d42cda6ed24805a7ab1ce9
88a1ed93a65647acd6121823b082febf97710ea3
refs/heads/master
<file_sep><?php use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::get('/user', function (Request $request) { return $request->user(); })->middleware('auth:api'); Route::get('/reports', 'Api\Report\ReportController@index'); Route::post('/report', 'Api\Report\ReportController@store'); Route::post('/report/meta', 'Api\Report\ReportController@storeMeta'); Route::post('/report/disease', 'Api\Report\ReportController@storeDisease'); Route::post('/report/patho', 'Api\Report\ReportController@storePatho'); Route::post('/report/genus', 'Api\Report\ReportController@storeGenus'); Route::post('/report/other', 'Api\Report\ReportController@storeOther'); Route::post('/report', 'Api\Report\ReportController@store'); Route::post('/report', 'Api\Report\ReportController@store'); Route::get('/report/{sample_id}', 'Api\Report\ReportController@find');<file_sep><?php namespace App\Repos\Batches; interface SampleRepoInterface { public function all($batch); }<file_sep><?php namespace App\Repos\Batches; use App\Models\Batch; use App\Models\Sample; use Carbon\Carbon; class BatchRepo implements BatchRepoInterface { public function all() { return Batch::all(); } public function paginate($pages) { return Batch::paginate($pages); } public function create($data) { $batch = new Batch(); $batch->fill(array_except($data, ['arrive_time', 'send_time'])); $batch['arrive_time'] = Carbon::parse($data['arrive_time']); $batch['send_time'] = Carbon::parse($data['send_time']); return $batch->save(); } }<file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateReportsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('reports', function (Blueprint $table) { $table->increments('id'); $table->string('sample_id')->index(); $table->json('gut'); $table->json('metabolism'); $table->json('disease'); $table->json('papa'); $table->json('papa_disease'); $table->tinyInteger('papa_disease_color'); $table->json('food'); $table->json('functional_food'); $table->json('life'); $table->text('common_bacteria_s'); $table->tinyInteger('common_bacteria_s_color'); $table->json('common_bacteria'); $table->text('harm_bacteria_s'); $table->tinyInteger('harm_bacteria_s_color'); $table->json('harm_bacteria'); $table->text('carbohydrate_s'); $table->tinyInteger('carbohydrate_s_color'); $table->json('carbohydrate'); $table->text('lipid_s'); $table->tinyInteger('lipid_s_color'); $table->json('lipid'); $table->text('protein_s'); $table->tinyInteger('protein_s_color'); $table->json('protein'); $table->text('immune_s'); $table->tinyInteger('immune_s_color'); $table->json('immune'); $table->text('benefit_s'); $table->tinyInteger('benefit_s_color'); $table->json('benefit'); $table->text('harm_s'); $table->tinyInteger('harm_s_color'); $table->json('harm'); $table->text('diabetes2_s'); $table->tinyInteger('diabetes2_s_color'); $table->json('diabetes2'); $table->text('ibd_s'); $table->tinyInteger('ibd_s_color'); $table->json('ibd'); $table->text('coloncancer_s'); $table->tinyInteger('coloncancer_s_color'); $table->json('coloncancer'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('reports'); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Report extends Model { protected $table = 'reports'; protected $guarded = []; protected $fillable = ['sample_id','gut','metabolism','disease','papa','papa_disease','papa_disease_color','food','functional_food','life','common_bacteria_s','common_bacteria_s_color','common_bacteria','harm_bacteria_s','harm_bacteria_s_color','harm_bacteria','carbohydrate_s','carbohydrate_s_color','carbohydrate','lipid_s','lipid_s_color','lipid','protein_s','protein_s_color','protein','immune_s','immune_s_color','immune','benefit_s','benefit_s_color','benefit','harm_s','harm_s_color','harm','diabetes2_s','diabetes2_s_color','diabetes2','ibd_s','ibd_s_color','ibd','coloncancer_s','coloncancer_s_color','coloncancer']; } <file_sep><?php namespace App\Http\Controllers\Api\Batch; use App\Repos\Batches\BatchRepoInterface; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class BatchController extends Controller { protected $repo; public function __construct(BatchRepoInterface $repo) { $this->repo = $repo; } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Batch extends Model { protected $guarded = ['_token']; // public function setSendTimeAttribute() // { // return strtotime($this->send_time); // } // // public function setArriveTimeAttribute() // { // return strtotime($this->arrive_time); // } public function samples() { return $this->hasMany('App\Models\Sample'); } } <file_sep><?php namespace App\Repos\Batches; use App\Models\Sample; class SampleRepo implements SampleRepoInterface { public function all($batch) { return Sample::where('batch_id', $batch)->paginate(10); } }<file_sep><?php namespace App\Repos\Batches; interface BatchRepoInterface { public function all(); public function create($data); public function paginate($pages); }<file_sep><?php namespace App\Repos\Reports; interface ReportRepoInterface { public function all(); public function find($id); public function create($data); public function attributes(); public function save($data); public function insertDb($table, $data); }<file_sep><?php namespace App\Repos\Reports; use App\Models\Report; use Illuminate\Support\Facades\DB; class ReportRepo implements ReportRepoInterface { public function all() { return Report::all(); } public function find($sample_id) { return Report::where('sample_id', $sample_id)->first(); } public function create($data) { Report::create($data); } public function attributes() { $report = new Report(); return $report->getFillable(); } public function save($data) { return Report::create($data); } public function insertDb($table, $data) { return Db::table($table)->insert($data); } }<file_sep><?php namespace App\Http\Controllers; use App\Repos\Batches\BatchRepoInterface; use Illuminate\Http\Request; use App\Http\Requests; use App\Models\Batch; class BatchController extends Controller { protected $repo; public function __construct(BatchRepoInterface $repo) { $this->repo = $repo; } public function index () { $batches = $this->repo->paginate(8); return view('batches.index', compact('batches')); } public function create(Batch $batch) { // $batch = []; return view('batches.create', compact('batch')); } public function store(Request $request) { // dd($request->all()); $this->repo->create($request->all()); return redirect()->route('batches.index'); } public function update() { } public function destroy($id) { } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Sample extends Model { public function batch() { return $this->belongsTo('App\Models\Batch'); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | This file is where you may define all of the routes that are handled | by your application. Just tell Laravel the URIs it should respond | to using a Closure or controller method. Build something great! | */ Route::get('/', function () { return view('welcome'); }); Auth::routes(); Route::get('/home', 'HomeController@index'); // Route::get('/batches/{id}/samples', ['uses' => 'BatchController@samples', 'as' => 'batches.samples']); Route::resource('batches', 'BatchController'); // Route::resource('/batches/{id}/samples', 'SampleController'); Route::group(['prefix' => 'batches/{batch}', 'name' => 'batches'], function() { Route::resource('samples', 'SampleController'); }); Route::resource('clients', 'ClientController'); Route::resource('projects', 'ProjectController'); Route::resource('tasks', 'TaskController'); <file_sep><?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class RepoServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // parent::boot(); } /** * Register the application services. * * @return void */ public function register() { $this->app->bind('App\Repos\Reports\ReportRepoInterface', 'App\Repos\Reports\ReportRepo'); $this->app->bind('App\Repos\Batches\BatchRepoInterface', 'App\Repos\Batches\BatchRepo'); $this->app->bind('App\Repos\Batches\SampleRepoInterface', 'App\Repos\Batches\SampleRepo'); } } <file_sep><?php namespace App\Http\Controllers\Api\Report; use App\Repos\Reports\ReportRepoInterface; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class ReportController extends Controller { protected $report; public function __construct(ReportRepoInterface $report) { $this->report = $report; } public function index() { return $this->report->all(); } public function store(Request $request) { $data = $request->all(); $keys = $this->report->attributes(); $fill = []; foreach ($keys as $key => $attr) { if (is_array($data[$attr])) { $fill[$attr] = json_encode($data[$attr]); } else { $fill[$attr] = $data[$attr]; } } $this->report->save($fill); return response()->json([ "message" => "success" ]); } public function find($sample_id) { return $this->report->find($sample_id); } public function storeMeta(Request $request) { return $this->storeData($request, 'report_metabolism'); } public function storeDisease(Request $request) { return $this->storeData($request, 'report_disease'); } public function storePatho(Request $request) { return $this->storeData($request, 'report_pathogen'); } public function storeGenus(Request $request) { return $this->storeData($request, 'report_genus'); } public function storeOther(Request $request) { return $this->storeData($request, 'report_other'); } /** * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function storeData(Request $request, $table) { $fills = $request->all(); for ($i = 1; $i <= count($fills); ++$i) { $fill = []; foreach ($fills[$i] as $key => $value) { $fill[$key] = $value; } $this->report->insertDb($table, $fill); } // dd($request->all()); return response()->json([ 'success' => 'data saved' ]); } }
0f7d83a5820adbc357501e276f2a950083bf4b05
[ "PHP" ]
16
PHP
kegeer/pp
1414e6513346e205b1790e5586551069d37fe010
f022c95f3b68d2598755d34cb7cdf75ec5551047
refs/heads/master
<file_sep>const foregroundColor = '#c7c7c7'; const backgroundColor = '#000'; const borderColor = '#333'; const colors = { black: '#626262', red: '#ff8373', green: '#b4fb73', yellow: '#fffdc3', blue: '#a5d5fe', magenta: '#ff90fe', cyan: '#d1d1fe', white: '#f1f1f1', lightBlack: '#8f8f8f', lightRed: '#ffc4be', lightGreen: '#d6fcba', lightYellow: '#fffed5', lightBlue: '#c2e3ff', lightMagenta: '#ffb2fe', lightCyan: '#e6e7fe', lightWhite: '#ffffff' }; exports.decorateConfig = config => { return Object.assign({}, config, { foregroundColor, backgroundColor, borderColor, colors }); }; <file_sep># Pastel theme for Hyper Pastel colors ported from [iTerm's](https://www.iterm2.com/) color presets to [Hyper](https://hyper.is). ![Screenshot](screenshot.png) ## Install Add `hyper-pastel` to the plugins list in your `~/.hyper.js` config file. ```js plugins: [ 'hyper-pastel' ] ``` ## License MIT
8eb8098251d2ba1859627bed382b708b92b15cdd
[ "JavaScript", "Markdown" ]
2
JavaScript
jerep/hyper-pastel
3e3b51f803cc5827ebce88a16abb8d80ce1b4795
defed604496ef658b884715ffd283a4a8b74a4f8
refs/heads/master
<repo_name>edsource/smarter-balanced-results<file_sep>/README.md # smarter-balanced-results EdSource interactive database showing results of CA Smarter Balanced tests ## To build locally: `git clone https://github.com/edsource/smarter-balanced-results.git` `cd smarter-balanced-results` Initialize virtual environment: `virtualenv venv` Activate virtual environment: `source venv/bin/activate` Install dependencies: `pip install -r requirements.txt` ## To run app on local server: `python app.py` ## To build static site: `python freeze.py` <file_sep>/static/stacked-column-percent-jinja.js var stackedColumnChart = { vars:{ label:[], w:null, h:null, m:{}, contain:null, xaxisLabel:null, yaxisLabel:null, tickFormat:null, ticks:null, path:null, color:null, padding:null, sort:false, items:null, title:null, subhed:null, source:null, data:null, chart:null, legend:null }, getAttr: function(p, path, contain, w, h, m, color, items, sort, xlabel, ylabel, tF, tick, pad, title, subhed, source, data, chart, legend){ p.w = parseInt(w)// - m[1] - m[3]; p.h = parseInt(h)// - m[0] - m[2]; p.m = { top:m[0], right:m[1], bottom:m[2], left:m[3] }; p.path = path; p.contain = '#' + contain; p.xaxisLabel = xlabel; p.yaxisLabel = ylabel; p.tickFormat = tF; p.ticks = tick; p.color = color[items]; p.padding = pad; p.sort = sort; p.title = title; p.subhed = subhed; p.source = source; p.data = data; p.chart = chart; p.legend = legend; stackedColumnChart.drawChart(stackedColumnChart.vars, p.data); }, processData: function(d, c){ var tempData = new Array(); var loc = 0; switch(c){ case 0: //OVERALL ALL STUDENTS tempData[0] = new Object(); tempData[0]['xlabel'] = 'English'; tempData[0]['Standard Not Met'] = parseFloat(d.pct_standard_not_met_eng); tempData[0]['Standard Nearly Met'] = parseFloat(d.pct_standard_nearly_met_eng); tempData[0]['Standard Met'] = parseFloat(d.pct_standard_met_eng); tempData[0]['Standard Exceeded'] = parseFloat(d.pct_standard_exceeded_eng); tempData[1] = new Object(); tempData[1]['xlabel'] = 'Math'; tempData[1]['Standard Not Met'] = parseFloat(d.pct_standard_not_met_math); tempData[1]['Standard Nearly Met'] = parseFloat(d.pct_standard_nearly_met_math); tempData[1]['Standard Met'] = parseFloat(d.pct_standard_met_math); tempData[1]['Standard Exceeded'] = parseFloat(d.pct_standard_exceeded_math); break; case 1: //OVERALL GRADES ENGLISH if (d.check_3rd_eng === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Grade 3'; tempData[loc]['Standard Not Met'] = parseFloat(d.grade3_eng_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.grade3_eng_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.grade3_eng_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.grade3_eng_lvl_4); loc ++; } if (d.check_4th_eng === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Grade 4'; tempData[loc]['Standard Not Met'] = parseFloat(d.grade4_eng_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.grade4_eng_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.grade4_eng_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.grade4_eng_lvl_4); loc ++; } if (d.check_5th_eng === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Grade 5'; tempData[loc]['Standard Not Met'] = parseFloat(d.grade5_eng_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.grade5_eng_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.grade5_eng_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.grade5_eng_lvl_4); loc ++; } if (d.check_6th_eng === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Grade 6'; tempData[loc]['Standard Not Met'] = parseFloat(d.grade6_eng_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.grade6_eng_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.grade6_eng_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.grade6_eng_lvl_4); loc ++; } if (d.check_7th_eng === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Grade 7'; tempData[loc]['Standard Not Met'] = parseFloat(d.grade7_eng_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.grade7_eng_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.grade7_eng_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.grade7_eng_lvl_4); loc ++; } if (d.check_8th_eng === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Grade 8'; tempData[loc]['Standard Not Met'] = parseFloat(d.grade8_eng_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.grade8_eng_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.grade8_eng_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.grade8_eng_lvl_4); loc ++; } if (d.check_11th_eng === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Grade 11'; tempData[loc]['Standard Not Met'] = parseFloat(d.grade11_eng_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.grade11_eng_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.grade11_eng_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.grade11_eng_lvl_4); loc ++; } break; case 2: //OVERALL GRADES MATH if (d.check_3rd_math === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Grade 3'; tempData[loc]['Standard Not Met'] = parseFloat(d.grade3_math_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.grade3_math_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.grade3_math_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.grade3_math_lvl_4); loc ++; } if (d.check_4th_math=== 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Grade 4'; tempData[loc]['Standard Not Met'] = parseFloat(d.grade4_math_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.grade4_math_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.grade4_math_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.grade4_math_lvl_4); loc ++; } if (d.check_5th_math === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Grade 5'; tempData[loc]['Standard Not Met'] = parseFloat(d.grade5_math_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.grade5_math_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.grade5_math_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.grade5_math_lvl_4); loc ++; } if (d.check_6th_math === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Grade 6'; tempData[loc]['Standard Not Met'] = parseFloat(d.grade6_math_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.grade6_math_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.grade6_math_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.grade6_math_lvl_4); loc ++; } if (d.check_7th_math === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Grade 7'; tempData[loc]['Standard Not Met'] = parseFloat(d.grade7_math_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.grade7_math_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.grade7_math_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.grade7_math_lvl_4); loc ++; } if (d.check_8th_math === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Grade 8'; tempData[loc]['Standard Not Met'] = parseFloat(d.grade8_math_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.grade8_math_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.grade8_math_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.grade8_math_lvl_4); loc ++; } if (d.check_11th_math === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Grade 11'; tempData[loc]['Standard Not Met'] = parseFloat(d.grade11_math_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.grade11_math_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.grade11_math_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.grade11_math_lvl_4); loc ++; } break; case 3: // RACE AND ETHNICITY ENGLISH if (d.check_white === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'White'; tempData[loc]['Standard Not Met'] = parseFloat(d.white_eng_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.white_eng_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.white_eng_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.white_eng_lvl_4); loc ++; } if (d.check_black === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'African American'; tempData[loc]['Standard Not Met'] = parseFloat(d.black_eng_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.black_eng_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.black_eng_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.black_eng_lvl_4); loc ++; } if (d.check_aian === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Amer Ind Alk Native'; tempData[loc]['Standard Not Met'] = parseFloat(d.aian_eng_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.aian_eng_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.aian_eng_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.aian_eng_lvl_4); loc ++; } if (d.check_asian === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Asian'; tempData[loc]['Standard Not Met'] = parseFloat(d.asian_eng_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.asian_eng_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.asian_eng_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.asian_eng_lvl_4); loc ++; } if (d.check_filipino === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Filipino'; tempData[loc]['Standard Not Met'] = parseFloat(d.filipino_eng_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.filipino_eng_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.filipino_eng_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.filipino_eng_lvl_4); loc ++; } if (d.check_pi === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Pacific Islander'; tempData[loc]['Standard Not Met'] = parseFloat(d.pi_eng_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.pi_eng_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.pi_eng_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.pi_eng_lvl_4); loc ++; } if (d.check_hisp === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Hispanic'; tempData[loc]['Standard Not Met'] = parseFloat(d.hisp_eng_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.hisp_eng_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.hisp_eng_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.hisp_eng_lvl_4); loc ++; } break; case 4: // RACE AND ETHNICITY MATH if (d.check_white === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'White'; tempData[loc]['Standard Not Met'] = parseFloat(d.white_math_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.white_math_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.white_math_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.white_math_lvl_4); loc ++; } if (d.check_black === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'African American'; tempData[loc]['Standard Not Met'] = parseFloat(d.black_math_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.black_math_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.black_math_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.black_math_lvl_4); loc ++; } if (d.check_aian === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Amer Ind Alk Native'; tempData[loc]['Standard Not Met'] = parseFloat(d.aian_math_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.aian_math_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.aian_math_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.aian_math_lvl_4); loc ++; } if (d.check_asian === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Asian'; tempData[loc]['Standard Not Met'] = parseFloat(d.asian_math_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.asian_math_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.asian_math_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.asian_math_lvl_4); loc ++; } if (d.check_filipino === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Filipino'; tempData[loc]['Standard Not Met'] = parseFloat(d.filipino_math_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.filipino_math_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.filipino_math_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.filipino_math_lvl_4); loc ++; } if (d.check_pi === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Pacific Islander'; tempData[loc]['Standard Not Met'] = parseFloat(d.pi_math_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.pi_math_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.pi_math_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.pi_math_lvl_4); loc ++; } if (d.check_hisp === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Hispanic'; tempData[loc]['Standard Not Met'] = parseFloat(d.hisp_math_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.hisp_math_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.hisp_math_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.hisp_math_lvl_4); loc ++; } break; case 5: // GENDER ENGLISH tempData[0] = new Object(); tempData[0]['xlabel'] = 'Male'; tempData[0]['Standard Not Met'] = parseFloat(d.male_eng_lvl_1); tempData[0]['Standard Nearly Met'] = parseFloat(d.male_eng_lvl_2); tempData[0]['Standard Met'] = parseFloat(d.male_eng_lvl_3); tempData[0]['Standard Exceeded'] = parseFloat(d.male_eng_lvl_4); tempData[1] = new Object(); tempData[1]['xlabel'] = 'Female'; tempData[1]['Standard Not Met'] = parseFloat(d.female_eng_lvl_1); tempData[1]['Standard Nearly Met'] = parseFloat(d.female_eng_lvl_2); tempData[1]['Standard Met'] = parseFloat(d.female_eng_lvl_3); tempData[1]['Standard Exceeded'] = parseFloat(d.female_eng_lvl_4); break; case 6: // GENDER MATH tempData[0] = new Object(); tempData[0]['xlabel'] = 'Male'; tempData[0]['Standard Not Met'] = parseFloat(d.male_math_lvl_1); tempData[0]['Standard Nearly Met'] = parseFloat(d.male_math_lvl_2); tempData[0]['Standard Met'] = parseFloat(d.male_math_lvl_3); tempData[0]['Standard Exceeded'] = parseFloat(d.male_math_lvl_4); tempData[1] = new Object(); tempData[1]['xlabel'] = 'Female'; tempData[1]['Standard Not Met'] = parseFloat(d.female_math_lvl_1); tempData[1]['Standard Nearly Met'] = parseFloat(d.female_math_lvl_2); tempData[1]['Standard Met'] = parseFloat(d.female_math_lvl_3); tempData[1]['Standard Exceeded'] = parseFloat(d.female_math_lvl_4); break; case 7: if (d.check_ed === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Economically Disadvantaged'; tempData[loc]['Standard Not Met'] = parseFloat(d.ed_eng_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.ed_eng_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.ed_eng_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.ed_eng_lvl_4); loc ++; } if (d.check_el === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'English Learner'; tempData[loc]['Standard Not Met'] = parseFloat(d.el_eng_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.el_eng_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.el_eng_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.el_eng_lvl_4); loc ++; } break; case 8: if (d.check_ed === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'Economically Disadvantaged'; tempData[loc]['Standard Not Met'] = parseFloat(d.ed_math_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.ed_math_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.ed_math_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.ed_math_lvl_4); loc ++; } if (d.check_el === 'TRUE'){ tempData[loc] = new Object(); tempData[loc]['xlabel'] = 'English Learner'; tempData[loc]['Standard Not Met'] = parseFloat(d.el_math_lvl_1); tempData[loc]['Standard Nearly Met'] = parseFloat(d.el_math_lvl_2); tempData[loc]['Standard Met'] = parseFloat(d.el_math_lvl_3); tempData[loc]['Standard Exceeded'] = parseFloat(d.el_math_lvl_4); loc ++; } break; case 11: // STATE GRADE 3 ENGLISH for (var i = 0; i < d.length ; i++){ tempData[i] = new Object(); tempData[i]['xlabel'] = d[i].stateAbbr; tempData[i]['Level 2 or Lower'] = 1 - parseFloat(d[i].english_3rd); tempData[i]['Level 3 or Higher'] = parseFloat(d[i].english_3rd); } break; case 12: // STATE GRADE 4 ENGLISH for (var i = 0; i < d.length ; i++){ tempData[i] = new Object(); tempData[i]['xlabel'] = d[i].stateAbbr; tempData[i]['Level 2 or Lower'] = 1 - parseFloat(d[i].english_4th); tempData[i]['Level 3 or Higher'] = parseFloat(d[i].english_4th); } break; case 13: // STATE GRADE 5 ENGLISH for (var i = 0; i < d.length ; i++){ tempData[i] = new Object(); tempData[i]['xlabel'] = d[i].stateAbbr; tempData[i]['Level 2 or Lower'] = 1 - parseFloat(d[i].english_5th); tempData[i]['Level 3 or Higher'] = parseFloat(d[i].english_5th); } break; case 14: // STATE GRADE 6 ENGLISH for (var i = 0; i < d.length ; i++){ tempData[i] = new Object(); tempData[i]['xlabel'] = d[i].stateAbbr; tempData[i]['Level 2 or Lower'] = 1 - parseFloat(d[i].english_6th); tempData[i]['Level 3 or Higher'] = parseFloat(d[i].english_6th); } break; case 15: // STATE GRADE 7 ENGLISH for (var i = 0; i < d.length ; i++){ tempData[i] = new Object(); tempData[i]['xlabel'] = d[i].stateAbbr; tempData[i]['Level 2 or Lower'] = 1 - parseFloat(d[i].english_7th); tempData[i]['Level 3 or Higher'] = parseFloat(d[i].english_7th); } break; case 16: // STATE GRADE 8 ENGLISH for (var i = 0; i < d.length ; i++){ tempData[i] = new Object(); tempData[i]['xlabel'] = d[i].stateAbbr; tempData[i]['Level 2 or Lower'] = 1 - parseFloat(d[i].english_8th); tempData[i]['Level 3 or Higher'] = parseFloat(d[i].english_8th); } break; case 17: // STATE GRADE 11 ENGLISH var index; for (var i = 0; i < d.length ; i++){ tempData[i] = new Object(); tempData[i]['xlabel'] = d[i].stateAbbr; tempData[i]['Level 2 or Lower'] = 1 - parseFloat(d[i].english_11th); tempData[i]['Level 3 or Higher'] = parseFloat(d[i].english_11th); if (d[i].stateAbbr === 'Missouri'){ index = i; } } if (index > -1){tempData.splice(index, 1);} break; case 21: // STATE GRADE 3 MATH for (var i = 0; i < d.length ; i++){ tempData[i] = new Object(); tempData[i]['xlabel'] = d[i].stateAbbr; tempData[i]['Level 2 or Lower'] = 1 - parseFloat(d[i].math_3rd); tempData[i]['Level 3 or Higher'] = parseFloat(d[i].math_3rd); } break; case 22: // STATE GRADE 4 MATH for (var i = 0; i < d.length ; i++){ tempData[i] = new Object(); tempData[i]['xlabel'] = d[i].stateAbbr; tempData[i]['Level 2 or Lower'] = 1 - parseFloat(d[i].math_4th); tempData[i]['Level 3 or Higher'] = parseFloat(d[i].math_4th); } break; case 23: // STATE GRADE 5 MATH for (var i = 0; i < d.length ; i++){ tempData[i] = new Object(); tempData[i]['xlabel'] = d[i].stateAbbr; tempData[i]['Level 2 or Lower'] = 1 - parseFloat(d[i].math_5th); tempData[i]['Level 3 or Higher'] = parseFloat(d[i].math_5th); } break; case 24: // STATE GRADE 6 MATH for (var i = 0; i < d.length ; i++){ tempData[i] = new Object(); tempData[i]['xlabel'] = d[i].stateAbbr; tempData[i]['Level 2 or Lower'] = 1 - parseFloat(d[i].math_6th); tempData[i]['Level 3 or Higher'] = parseFloat(d[i].math_6th); } break; case 25: // STATE GRADE 7 MATH for (var i = 0; i < d.length ; i++){ tempData[i] = new Object(); tempData[i]['xlabel'] = d[i].stateAbbr; tempData[i]['Level 2 or Lower'] = 1 - parseFloat(d[i].math_7th); tempData[i]['Level 3 or Higher'] = parseFloat(d[i].math_7th); } break; case 26: // STATE GRADE 8 MATH for (var i = 0; i < d.length ; i++){ tempData[i] = new Object(); tempData[i]['xlabel'] = d[i].stateAbbr; tempData[i]['Level 2 or Lower'] = 1 - parseFloat(d[i].math_8th); tempData[i]['Level 3 or Higher'] = parseFloat(d[i].math_8th); } break; case 27: // STATE GRADE 11 MATH var index; for (var i = 0; i < d.length ; i++){ tempData[i] = new Object(); tempData[i]['xlabel'] = d[i].stateAbbr; tempData[i]['Level 2 or Lower'] = 1 - parseFloat(d[i].math_11th); tempData[i]['Level 3 or Higher'] = parseFloat(d[i].math_11th); if (d[i].stateAbbr === 'Missouri'){ index = i; } } if (index > -1){tempData.splice(index, 1);} break; case 100: //TOP 100 ENG DISTRICTS for (var i = 0; i < d.length ; i++){ tempData[i] = new Object(); tempData[i]['xlabel'] = d[i].entity_name; tempData[i]['Standard Not Met'] = parseFloat(d[i].pct_standard_not_met_eng); tempData[i]['Standard Nealry Met'] = parseFloat(d[i].pct_standard_nearly_met_eng); tempData[i]['Standard Met or Exceeded'] = parseFloat(d[i].pct_standard_met_or_exceeded_eng); } break; } return tempData; }, drawChart: function(p, data){ /* PROCESS DATA FOR CHART OF CHOICE ==========================================*/ data = stackedColumnChart.processData(data, p.chart) /* SCALE ==========================*/ var xScale = d3.scale.ordinal().rangeRoundBands([0, p.w - 30], p.padding); var yScale = d3.scale.linear().rangeRound([p.h, 0]); /* COLOR ==========================*/ var color = d3.scale.ordinal().range(p.color); /* AXES ==========================*/ var xAxis = d3.svg.axis().scale(xScale).orient('bottom'); var yAxis = d3.svg.axis().scale(yScale).orient('left').ticks(p.tick).tickFormat(d3.format(p.tickFormat)); /* CHART ==========================*/ var chart = d3.select(p.contain).append('svg').classed('s_c_p', true).attr('width', p.w).attr('height', p.h) .append('g').attr('transform', 'translate('+ p.m.left +','+ p.m.top + ')'); /* DATA AND DRAW ===============================================================================*/ color.domain(d3.keys(data[0]).filter(function(key){ return key !== 'xlabel'})); /* MAPS Y POS FOR SEGMENTS ====================================*/ data.forEach(function(d){ var y0 = 0; d.seg = color.domain().map(function(name){return {name:name, y0:y0, y1: y0 += +d[name]}; }) d.seg.forEach(function(d) {d.y0 /= y0; d.y1 /= y0;}); }) /* SORT ====================================*/ if (p.sort == true){data.sort(function(a,b) {return b.seg[0].y1 - a.seg[0].y1;})} /* MAP X COLUMNS ====================================*/ xScale.domain(data.map(function(d){ return d.xlabel;})); /* DRAW AXES ====================================*/ chart.append('g').attr('class', 'xaxis').attr('transform', 'translate(0,' + p.h + ')').call(xAxis) .selectAll(".tick text").call(stackedColumnChart.wrapLabels, xScale.rangeBand()); chart.append('g').attr('class', 'yaxis').call(yAxis); /* TOOLTIP ====================================*/ var tip = d3.tip().html(function(d) { jQuery('.n').addClass('d3-tip'); if (p.tickFormat == '.0%'){ return (d.name + '<br>' + Math.round((d.y1 - d.y0)*100) + '%'); } }); chart.call(tip); /* DRAW COLUMNS ====================================*/ var items = chart.selectAll('.xitem').data(data).enter() .append('g').attr('class','xitem').attr('transform', function(d){return 'translate(' + xScale(d.xlabel) + ',0)';}); items.selectAll('rect').data(function(d) {return d.seg;}).enter().append('rect') .attr('width', xScale.rangeBand()).attr('y', function(d) {return yScale(d.y1);}).attr('height', function(d) {return yScale(d.y0) - yScale(d.y1); }).style('fill', function(d){return color(d.name);}) .on('mouseover', tip.show).on('mouseout', tip.hide); /* ADJUST SVG ====================================*/ jQuery(p.contain + ' svg').attr('height', p.h+(p.m.top * 2)); var svgg = jQuery(p.contain + ' svg').attr('height'); stackedColumnChart.addMeta(p, data); }, addMeta:function(p, data){ if (p.legend == true){ /* ADD LEGEND DETAILS =================================*/ jQuery(p.contain).prepend('<div id="legend"></div>'); for (var i = 0 ; i < data[0].seg.length ; i++){ jQuery(p.contain + ' #legend').append('<div class="legend-item"><div></div><p>'+ data[0].seg[i].name+'</p></div>'); jQuery(p.contain + ' .legend-item>div:eq('+i+')').css({'background-color':p.color[i]}) } /* STYLES =================================*/ jQuery(p.contain + ' #legend').css({'overflow':'hidden', 'margin':'20px 0'}); jQuery(p.contain + ' .legend-item').css({'float':'left','overflow':'hidden', 'margin':'0 15px 20px 0'}); jQuery(p.contain + ' .legend-item>div').css({'width':'30px','height':'30px','float':'left'}); jQuery(p.contain + ' .legend-item p').css({'font-size':'.9em','color':'#333','float': 'right', 'margin': '0 0 0 10px'}); } if (p.subhed != null){ /* ADD META DETAILS =================================*/ jQuery(p.contain).prepend('<div id="meta"></div>'); if (p.legend == true) {jQuery(p.contain + ' #meta').detach().insertAfter(p.contain + ' #legend');} jQuery(p.contain + ' #meta').append('<h2>'+p.subhed+'</h2>'); if (p.source !== null){jQuery(p.contain + ' #meta').append('<p>'+p.source+'</p>');} jQuery(p.contain + ' #meta h2').css({'margin':0,'font-size':'1em','color':'#aaa'}); jQuery(p.contain + ' #meta p').css({'text-align': 'center','font-style': 'italic','font-size': '1em'}); } }, wrapLabels: function(text, width){ text.each(function() { var text = d3.select(this), words = text.text().split(/\s+/).reverse(), word, line = [], lineNumber = 0, lineHeight = 1.1, // ems y = text.attr("y"), dy = parseFloat(text.attr("dy")), tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em"); while (word = words.pop()) { line.push(word); tspan.text(line.join(" ")); if (tspan.node().getComputedTextLength() > width) { line.pop(); tspan.text(line.join(" ")); line = [word]; tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word); } } }); } }<file_sep>/freeze.py from flask_frozen import Freezer from app import app, get_csv freezer = Freezer(app) @freezer.register_generator def detail(): for row in get_csv('./static/districtdata.csv'): yield {'entity_slug': row['entity_slug']} @freezer.register_generator def schools_detail(): for row in get_csv('./static/schooldata.csv'): yield {'entity_slug': row['entity_slug']} # @freezer.register_generator # def charter(): # for row in get_csv('./static/charter.csv'): # yield {'slug': row['slug']} if __name__ == '__main__': freezer.freeze()
d08a7c898986fc797cc2fe63158da3b619a2e77d
[ "Markdown", "Python", "JavaScript" ]
3
Markdown
edsource/smarter-balanced-results
7670cca7d153fdc9154b6414e4959e8505da8332
7db1a2db349c395ca21580dbb692866482e3397f
refs/heads/master
<repo_name>TalPat/push_swap<file_sep>/check_srcs/commands2.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* commands2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/13 14:54:02 by tpatter #+# #+# */ /* Updated: 2018/07/24 14:15:37 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "checker.h" void ft_ra(t_check *check) { t_list *tmp; t_list *conveyer; if (check->cola && check->cola->next) { tmp = check->cola; conveyer = check->cola; check->cola = check->cola->next; while (conveyer->next) conveyer = conveyer->next; conveyer->next = tmp; tmp->next = NULL; } } void ft_rb(t_check *check) { t_list *tmp; t_list *conveyer; if (check->colb && check->colb->next) { tmp = check->colb; conveyer = check->colb; check->colb = check->colb->next; while (conveyer->next) conveyer = conveyer->next; conveyer->next = tmp; tmp->next = NULL; } } void ft_rr(t_check *check) { ft_ra(check); ft_rb(check); } void ft_rra(t_check *check) { t_list *conveyer; t_list *tmp; if (check->cola && check->cola->next) { conveyer = check->cola; while (conveyer->next->next) conveyer = conveyer->next; tmp = conveyer->next; conveyer->next = NULL; tmp->next = check->cola; check->cola = tmp; } } void ft_rrb(t_check *check) { t_list *conveyer; t_list *tmp; if (check->colb && check->colb->next) { conveyer = check->colb; while (conveyer->next->next) conveyer = conveyer->next; tmp = conveyer->next; conveyer->next = NULL; tmp->next = check->colb; check->colb = tmp; } } <file_sep>/Makefile # **************************************************************************** # # # # ::: :::::::: # # Makefile :+: :+: :+: # # +:+ +:+ +:+ # # By: tpatter <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2018/07/24 17:28:22 by tpatter #+# #+# # # Updated: 2018/07/25 17:51:32 by tpatter ### ########.fr # # # # **************************************************************************** # NAMECH = checker CHSRCDIR = check_srcs/ CHSRC = checker.c\ commands1.c\ commands2.c\ commands3.c\ ft_check.c\ ft_checkerror.c\ ft_extract.c CHOBJDIR = chobj/ CHOBJ = $(CHSRC:%.c=%.o) CHOBJPATH := $(addprefix $(CHOBJDIR), $(CHOBJ)) NAMEPS = push_swap PSSRCDIR = ps_srcs/ PSSRC = commands1.c\ ft_bubble.c\ ft_orderfactor.c\ commands2.c\ ft_checkerror.c\ ft_pulla.c\ commands3.c\ ft_checkorder.c\ ft_push_swap.c\ ft_altquick.c\ ft_checkrevorder.c\ ft_quick.c\ ft_basic.c\ ft_combine.c\ ft_split.c\ ft_basicinv.c\ ft_dualsove.c\ ft_tinysort.c\ ft_basicn.c\ ft_extract.c\ push_swap.c\ ft_basicninv.c\ ft_merge.c PSOBJDIR = psobj/ PSOBJ = $(PSSRC:%.c=%.o) PSOBJPATH := $(addprefix $(PSOBJDIR), $(PSOBJ)) HEADER = includes/ CFLAGS = -Wall -Werror -Wextra CC = gcc LIBDIR = libft/ LIB = $(LIBDIR)libft.a LIBHEAD = $(LIBDIR)includes/ LIBLINK = -L $(LIBDIR) -l ft INCLUDES = -I $(HEADER) -I $(LIBHEAD) all: $(NAMECH) $(NAMEPS) $(NAMECH): $(CHOBJPATH) $(LIB) $(CC) -o $(NAMECH) $(CHOBJPATH) $(LIBLINK) $(INCLUDES) $(CFLAGS) $(CHOBJDIR)%.o: $(CHSRCDIR)%.c mkdir -p $(CHOBJDIR) $(CC) $(CFLAGS) -c -o $@ $< $(INCLUDES) $(LIB): make -C $(LIBDIR) $(NAMEPS): $(PSOBJPATH) $(LIB) $(CC) -o $(NAMEPS) $(PSOBJPATH) $(LIBLINK) $(INCLUDES) $(CFLAGS) $(PSOBJDIR)%.o: $(PSSRCDIR)%.c mkdir -p $(PSOBJDIR) $(CC) $(CFLAGS) -c -o $@ $< $(INCLUDES) clean: rm -rf $(PSOBJPATH) $(CHOBJPATH) make -C $(LIBDIR) clean fclean: clean rm -rf $(NAMECH) $(NAMEPS) make -C $(LIBDIR) fclean re: fclean all <file_sep>/ps_srcs/commands3.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* commands3.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/13 14:55:44 by tpatter #+# #+# */ /* Updated: 2018/07/24 16:17:58 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "push_swap.h" void ft_rrr(t_ps *ps) { t_list *conveyer; t_list *tmp; ft_putendl("rrr"); if (ps->cola && ps->cola->next) { conveyer = ps->cola; while (conveyer->next->next) conveyer = conveyer->next; tmp = conveyer->next; conveyer->next = NULL; tmp->next = ps->cola; ps->cola = tmp; } if (ps->colb && ps->colb->next) { conveyer = ps->colb; while (conveyer->next->next) conveyer = conveyer->next; tmp = conveyer->next; conveyer->next = NULL; tmp->next = ps->colb; ps->colb = tmp; } } void ft_printvis(int n, char col) { if (col == 'G') ft_putstr_fd("\x1B[32m", 0); else if (col == 'R') ft_putstr_fd("\x1B[31m", 0); ft_putstr_fd("\t", 0); while (n-- > 0) ft_putchar_fd('|', 0); ft_putstr_fd("\x1B[0m", 0); } void ft_visualise(t_ps *ps) { t_list *tmp; if (!ps->vis) return ; tmp = ps->cola; while (tmp) { ft_putstr_fd(tmp->content, 0); ft_printvis(ft_atoi(tmp->content), 'G'); ft_putstr_fd("\n", 0); tmp = tmp->next; } tmp = ps->colb; while (tmp) { ft_putstr_fd(tmp->content, 0); ft_printvis(ft_atoi(tmp->content), 'R'); ft_putstr_fd("\n", 0); tmp = tmp->next; } } void ft_docom(char *str, t_ps *ps) { if (!ft_strcmp(str, "sa")) ft_sa(ps); else if (!ft_strcmp(str, "sb")) ft_sb(ps); else if (!ft_strcmp(str, "ss")) ft_ss(ps); else if (!ft_strcmp(str, "pa")) ft_pa(ps); else if (!ft_strcmp(str, "pb")) ft_pb(ps); else if (!ft_strcmp(str, "ra")) ft_ra(ps); else if (!ft_strcmp(str, "rb")) ft_rb(ps); else if (!ft_strcmp(str, "rr")) ft_rr(ps); else if (!ft_strcmp(str, "rra")) ft_rra(ps); else if (!ft_strcmp(str, "rrb")) ft_rrb(ps); else if (!ft_strcmp(str, "rrr")) ft_rrr(ps); else ps->err = 1; ft_visualise(ps); } <file_sep>/includes/push_swap.h /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* push_swap.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/15 12:50:57 by tpatter #+# #+# */ /* Updated: 2018/07/25 12:49:06 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef PUSH_SWAP_H # define PUSH_SWAP_H # include "libft.h" typedef struct s_ps { t_list *cola; t_list *colb; int nuint; int err; char *line; int ofactor; int pushed; int vis; } t_ps; int main(int ac, char **av); int ft_checkerror(int ac, char **av); void ft_extract(char **av, t_ps *ps); void ft_check(t_ps *ps); void ft_push_swap(t_ps *ps); int ft_checkorder(t_ps *ps); int ft_checkrevorder(t_ps *ps); int ft_findmax(t_list *list); int ft_findmin(t_list *list); void ft_orderfactor(t_ps *ps); void ft_sa(t_ps *ps); void ft_sb(t_ps *ps); void ft_ss(t_ps *ps); void ft_pa(t_ps *ps); void ft_pb(t_ps *ps); void ft_ra(t_ps *ps); void ft_rb(t_ps *ps); void ft_rr(t_ps *ps); void ft_rra(t_ps *ps); void ft_rrb(t_ps *ps); void ft_rrr(t_ps *ps); void ft_docom(char *str, t_ps *ps); void ft_basic(t_ps *ps); void ft_basicinv(t_ps *ps); void ft_three(t_ps *ps); void ft_dualsolve(t_ps *ps); void ft_split(t_ps *ps); void ft_combine(t_ps *ps); void ft_tinysort(int inc, t_ps *ps); void ft_quicksort(t_ps *ps); void ft_quickinv(t_ps *ps); void ft_pulla(t_ps *ps); void ft_basicn(int n, t_ps *ps); void ft_basicninv(int n, t_ps *ps); void ft_merge(t_ps *ps); void ft_altquicksort(t_ps *ps); void ft_altquickinv(t_ps *ps); #endif <file_sep>/ps_srcs/ft_combine.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_combine.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/18 12:06:51 by tpatter #+# #+# */ /* Updated: 2018/07/23 14:30:31 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "push_swap.h" #include <stdlib.h> int ft_last(t_list *list) { t_list *tmp; tmp = list; while (tmp->next) tmp = tmp->next; return (ft_atoi(tmp->content)); } void ft_combine(t_ps *ps) { while (!ft_checkorder(ps) || ps->colb) { if (!ps->colb) ft_docom("rra", ps); else if ((ft_checkorder(ps) && ft_atoi(ps->colb->content) < ft_atoi(ps->cola->content)) || (ft_atoi(ps->colb->content) > ft_last(ps->cola))) { ft_docom("pa", ps); } else { ft_docom("rra", ps); } } } <file_sep>/ps_srcs/ft_basicinv.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_basicinv.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/18 10:45:04 by tpatter #+# #+# */ /* Updated: 2018/07/25 13:32:40 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "push_swap.h" #include <stdlib.h> int ft_findmax(t_list *list) { t_list *tmp; int max; int count; tmp = list->next; max = ft_atoi(list->content); while (tmp) { if (ft_atoi(tmp->content) > max) max = ft_atoi(tmp->content); tmp = tmp->next; } count = 0; tmp = list; while (ft_atoi(tmp->content) != max) { count++; tmp = tmp->next; } return (count); } void ft_basicinv(t_ps *ps) { unsigned int ronu; unsigned int i; ps->pushed = 0; while (!ft_checkrevorder(ps)) { i = 0; ronu = ft_findmax(ps->colb); if (ronu > ft_lstlen(ps->colb) / 2) { while (i++ < ft_lstlen(ps->colb) - ronu) ft_docom("rrb", ps); } else while (i++ < ronu) ft_docom("rb", ps); if (!ft_checkrevorder(ps)) { ps->pushed++; ft_docom("pa", ps); } } while (ps->pushed--) ft_docom("pb", ps); } <file_sep>/ps_srcs/push_swap.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* push_swap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/15 12:59:49 by tpatter #+# #+# */ /* Updated: 2018/07/25 18:43:28 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" #include "libft.h" #include <stdlib.h> void ft_cleanps(t_ps *ps) { t_list *tmp; tmp = ps->cola; while (tmp) { free(tmp->content); tmp = tmp->next; free(ps->cola); ps->cola = tmp; } tmp = ps->colb; while (tmp) { free(tmp->content); tmp = tmp->next; free(ps->colb); ps->cola = tmp; } free(ps); } void ft_initialise(t_ps *ps) { ps->cola = NULL; ps->colb = NULL; ps->err = 0; ps->vis = 0; } int main(int ac, char **av) { t_ps *ps; ps = (t_ps*)malloc(sizeof(t_ps)); ft_initialise(ps); if (!ft_strcmp(av[ac - 1], "-v")) { ps->vis = 1; av[ac - 1] = NULL; ac--; } if (ac == 1) ft_putstr("\n"); else if (ft_checkerror(ac, av)) ft_putstr_fd("Error\n", 2); else { ft_extract(av, ps); if (ft_lststrduplicates(ps->cola)) ft_putstr_fd("Error\n", 2); else ft_push_swap(ps); } ft_cleanps(ps); return (0); } <file_sep>/ps_srcs/ft_altquick.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_altquick.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/23 10:15:51 by tpatter #+# #+# */ /* Updated: 2018/07/23 14:25:12 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "push_swap.h" #include <stdlib.h> int ft_altfindpiv(t_ps *ps) { int a; int b; int c; int count; t_list *tmp; a = ft_atoi(ps->cola->content); tmp = ps->cola; count = ft_lstlen(ps->cola) / 2; while (--count) tmp = tmp->next; b = ft_atoi(tmp->content); while (tmp->next) tmp = tmp->next; c = ft_atoi(tmp->content); if (a < b && a < c) return (a); else if (b < a && b < c) return (b); return (c); } int ft_altfindpivinv(t_ps *ps) { int a; int b; int c; int count; t_list *tmp; a = ft_atoi(ps->colb->content); tmp = ps->colb; count = ft_lstlen(ps->colb) / 2; while (--count) tmp = tmp->next; b = ft_atoi(tmp->content); while (tmp->next) tmp = tmp->next; c = ft_atoi(tmp->content); if (a < b && a < c) return (a); else if (b < a && b < c) return (b); return (c); } void ft_altquickinv(t_ps *ps) { int piv; int i; while (ps->colb) { if (ft_lstlen(ps->colb) < 4) { ft_basicinv(ps); break ; } else { i = ft_lstlen(ps->colb); piv = ft_altfindpivinv(ps); while (i--) { if (ft_atoi(ps->colb->content) >= piv) ft_docom("pa", ps); else ft_docom("rb", ps); } } } while (ps->colb) ft_docom("pa", ps); } void ft_altquicksort(t_ps *ps) { int piv; int i; while (ps->cola) { if (ft_lstlen(ps->cola) < 4) { ft_three(ps); break ; } else { piv = ft_altfindpiv(ps); i = ft_lstlen(ps->cola); while (i--) { if (ft_atoi(ps->cola->content) <= piv) ft_docom("pb", ps); else ft_docom("ra", ps); } } } while (ps->cola) ft_docom("pb", ps); } <file_sep>/includes/checker.h /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* checker.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/13 11:16:17 by tpatter #+# #+# */ /* Updated: 2018/07/25 12:47:47 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef CHECKER_H # define CHECKER_H # include "libft.h" typedef struct s_check { t_list *cola; t_list *colb; int nuint; int err; char *line; } t_check; int main(int ac, char **av); int ft_checkerror(int ac, char **av); void ft_extract(char **av, t_check *check); void ft_check(t_check *check); void ft_sa(t_check *check); void ft_sb(t_check *check); void ft_ss(t_check *check); void ft_pa(t_check *check); void ft_pb(t_check *check); void ft_ra(t_check *check); void ft_rb(t_check *check); void ft_rr(t_check *check); void ft_rra(t_check *check); void ft_rrb(t_check *check); void ft_rrr(t_check *check); void ft_docom(char *str, t_check *check); int ft_ordered(t_check *check); #endif <file_sep>/ps_srcs/ft_dualsove.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_dualsove.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/17 14:32:21 by tpatter #+# #+# */ /* Updated: 2018/07/17 15:12:14 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "push_swap.h" #include <stdlib.h> int ft_aborder(t_ps *ps) { t_list *tmp; int ab; ab = 0; tmp = ps->colb; if (!ps->colb || ft_lstlen(ps->colb) == 1) ab++; else { while (tmp->next) { if (ft_atoi(tmp->content) > ft_atoi(tmp->next->content)) return (0); tmp = tmp->next; } ab++; } ab += ft_checkorder(ps); if (ab == 2) return (1); return (0); } int ft_firstbiggest(t_list *lst) { t_list *tmp; int first; first = ft_atoi(lst->content); tmp = lst->next; while (tmp) { if (ft_atoi(tmp->content) > first) return (0); tmp = tmp->next; } return (1); } void ft_dualsolve(t_ps *ps) { while (!ft_checkorder(ps)) { while (!ft_aborder(ps)) { if (ft_atoi(ps->cola->content) > ft_atoi(ps->cola->next->content) && !ft_firstbiggest(ps->cola)) { ft_sa(ps); ft_putendl("sa"); } if (!ft_checkorder(ps)) { ft_ra(ps); ft_putendl("ra"); } } } } <file_sep>/ps_srcs/ft_basic.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_basic.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/16 15:37:57 by tpatter #+# #+# */ /* Updated: 2018/07/25 13:32:19 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "push_swap.h" #include <stdlib.h> int ft_findmin(t_list *list) { t_list *tmp; int min; int count; tmp = list->next; min = ft_atoi(list->content); while (tmp) { if (ft_atoi(tmp->content) < min) min = ft_atoi(tmp->content); tmp = tmp->next; } count = 0; tmp = list; while (ft_atoi(tmp->content) != min) { count++; tmp = tmp->next; } return (count); } void ft_basic(t_ps *ps) { unsigned int ronu; unsigned int i; ps->pushed = 0; while (!ft_checkorder(ps)) { i = 0; ronu = ft_findmin(ps->cola); if (ronu > ft_lstlen(ps->cola) / 2) { while (i++ < ft_lstlen(ps->cola) - ronu) ft_docom("rra", ps); } else while (i++ < ronu) ft_docom("ra", ps); if (!ft_checkorder(ps)) { ps->pushed++; ft_docom("pb", ps); } } while (ps->pushed--) ft_docom("pa", ps); } <file_sep>/check_srcs/commands3.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* commands3.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/13 14:55:44 by tpatter #+# #+# */ /* Updated: 2018/07/24 14:15:50 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "checker.h" void ft_rrr(t_check *check) { ft_rra(check); ft_rrb(check); } void ft_docom(char *str, t_check *check) { if (!ft_strcmp(str, "sa")) ft_sa(check); else if (!ft_strcmp(str, "sb")) ft_sb(check); else if (!ft_strcmp(str, "ss")) ft_ss(check); else if (!ft_strcmp(str, "pa")) ft_pa(check); else if (!ft_strcmp(str, "pb")) ft_pb(check); else if (!ft_strcmp(str, "ra")) ft_ra(check); else if (!ft_strcmp(str, "rb")) ft_rb(check); else if (!ft_strcmp(str, "rr")) ft_rr(check); else if (!ft_strcmp(str, "rra")) ft_rra(check); else if (!ft_strcmp(str, "rrb")) ft_rrb(check); else if (!ft_strcmp(str, "rrr")) ft_rrr(check); else check->err = 1; } <file_sep>/ps_srcs/commands2.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* commands2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/13 14:54:02 by tpatter #+# #+# */ /* Updated: 2018/07/23 09:24:50 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "push_swap.h" void ft_ra(t_ps *ps) { t_list *tmp; t_list *conveyer; if (ps->cola && ps->cola->next) { ft_putendl("ra"); tmp = ps->cola; conveyer = ps->cola; ps->cola = conveyer->next; while (conveyer->next) conveyer = conveyer->next; conveyer->next = tmp; conveyer->next->next = NULL; } } void ft_rb(t_ps *ps) { t_list *tmp; t_list *conveyer; if (ps->colb && ps->colb->next) { ft_putendl("rb"); tmp = ps->colb; conveyer = ps->colb; ps->colb = ps->colb->next; while (conveyer->next) conveyer = conveyer->next; conveyer->next = tmp; conveyer->next->next = NULL; } } void ft_rr(t_ps *ps) { t_list *tmp; t_list *conveyer; ft_putendl("rr"); if (ps->cola && ps->cola->next) { tmp = ps->cola; conveyer = ps->cola; ps->cola = conveyer->next; while (conveyer->next) conveyer = conveyer->next; conveyer->next = tmp; conveyer->next->next = NULL; } if (ps->colb && ps->colb->next) { tmp = ps->colb; conveyer = ps->colb; ps->colb = ps->colb->next; while (conveyer->next) conveyer = conveyer->next; conveyer->next = tmp; conveyer->next->next = NULL; } } void ft_rra(t_ps *ps) { t_list *conveyer; t_list *tmp; if (ps->cola && ps->cola->next) { ft_putendl("rra"); conveyer = ps->cola; while (conveyer->next->next) conveyer = conveyer->next; tmp = conveyer->next; conveyer->next = NULL; tmp->next = ps->cola; ps->cola = tmp; } } void ft_rrb(t_ps *ps) { t_list *conveyer; t_list *tmp; if (ps->colb && ps->colb->next) { ft_putendl("rrb"); conveyer = ps->colb; while (conveyer->next->next) conveyer = conveyer->next; tmp = conveyer->next; conveyer->next = NULL; tmp->next = ps->colb; ps->colb = tmp; } } <file_sep>/check_srcs/commands1.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* commands1.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/13 14:50:14 by tpatter #+# #+# */ /* Updated: 2018/07/24 14:07:42 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "checker.h" void ft_sa(t_check *check) { t_list *tmp; if (check->cola && check->cola->next) { tmp = check->cola; check->cola = check->cola->next; tmp->next = check->cola->next; check->cola->next = tmp; } } void ft_sb(t_check *check) { t_list *tmp; if (check->colb && check->colb->next) { tmp = check->colb; check->colb = check->colb->next; tmp->next = check->colb->next; check->colb->next = tmp; } } void ft_ss(t_check *check) { ft_sa(check); ft_sb(check); } void ft_pa(t_check *check) { t_list *tmp; if (check->colb) { tmp = check->colb; check->colb = check->colb->next; tmp->next = check->cola; check->cola = tmp; } } void ft_pb(t_check *check) { t_list *tmp; if (check->cola) { tmp = check->cola; check->cola = check->cola->next; tmp->next = check->colb; check->colb = tmp; } } <file_sep>/ps_srcs/ft_extract.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_extract.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/13 13:53:18 by tpatter #+# #+# */ /* Updated: 2018/07/25 17:16:36 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "push_swap.h" #include <stdlib.h> void ft_endarr(char **arr) { int i; i = 0; while (arr[i]) { free(arr[i]); i++; } free(arr); } void ft_extract(char **av, t_ps *ps) { int i; int j; char **mynus; i = 1; ps->cola = NULL; ps->colb = NULL; while (av[i]) { mynus = ft_strsplit(av[i], ' '); j = 0; while (mynus[j]) { if (!ps->cola) ps->cola = ft_lstnew(mynus[j], ft_strlen(mynus[j])); else ft_lstaddend(ps->cola, mynus[j], ft_strlen(mynus[j])); j++; } ft_endarr(mynus); i++; } ps->nuint = ft_lstlen(ps->cola); } <file_sep>/check_srcs/ft_check.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_check.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/13 15:09:44 by tpatter #+# #+# */ /* Updated: 2018/07/25 13:07:26 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "checker.h" #include <stdlib.h> int ft_ordered(t_check *check) { t_list *tmp; tmp = check->cola; while (tmp->next) { if (ft_atoi(tmp->content) > ft_atoi(tmp->next->content)) return (0); tmp = tmp->next; } if (check->colb) return (0); return (1); } void ft_check(t_check *check) { while (ft_grabline(0, &check->line)) { ft_docom(check->line, check); free(check->line); } if (check->err) ft_putstr_fd("Error\n", 2); else if (ft_ordered(check)) ft_putstr("OK\n"); else ft_putstr("KO\n"); } <file_sep>/ps_srcs/ft_basicninv.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_basicninv.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/22 16:45:31 by tpatter #+# #+# */ /* Updated: 2018/07/23 09:29:30 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "push_swap.h" #include <stdlib.h> int ft_findnmax(int n, t_list *list) { t_list *tmp; int max; int count; tmp = list->next; max = ft_atoi(list->content); while (n - 1 && tmp) { if (ft_atoi(tmp->content) > max) max = ft_atoi(tmp->content); tmp = tmp->next; n--; } count = 0; tmp = list; while (ft_atoi(tmp->content) != max) { count++; tmp = tmp->next; } return (count); } void ft_basicninv(int n, t_ps *ps) { int ronu; int count; if (n && ps->colb) { ronu = ft_findnmax(n, ps->colb); count = ronu; while (ronu) { ft_rb(ps); ronu--; } ft_pa(ps); while (count && ps->colb) { ft_rrb(ps); count--; } ft_basicninv(n - 1, ps); } } <file_sep>/check_srcs/checker.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* checker.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/13 10:52:54 by tpatter #+# #+# */ /* Updated: 2018/08/01 10:46:41 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "checker.h" #include "libft.h" #include <stdlib.h> void ft_cleancheck(t_check *check) { t_list *tmp; tmp = check->cola; while (tmp) { free(tmp->content); tmp = tmp->next; free(check->cola); check->cola = tmp; } tmp = check->colb; while (tmp) { free(tmp->content); tmp = tmp->next; free(check->colb); check->colb = tmp; } free(check); } int main(int ac, char **av) { t_check *check; check = (t_check*)malloc(sizeof(t_check)); check->cola = NULL; check->colb = NULL; check->err = 0; if (ac == 1) ft_putstr("\n"); else if (ft_checkerror(ac, av)) ft_putstr_fd("Error\n", 2); else { ft_extract(av, check); if (ft_lststrduplicates(check->cola)) ft_putstr_fd("Error\n", 2); else ft_check(check); } ft_cleancheck(check); return (0); } <file_sep>/ps_srcs/ft_basicn.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_basicn.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/22 16:25:52 by tpatter #+# #+# */ /* Updated: 2018/07/23 09:29:41 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "push_swap.h" #include <stdlib.h> int ft_findnmin(int n, t_list *list) { t_list *tmp; int min; int count; tmp = list->next; min = ft_atoi(list->content); while (n - 1 && tmp) { if (ft_atoi(tmp->content) < min) min = ft_atoi(tmp->content); tmp = tmp->next; n--; } count = 0; tmp = list; while (ft_atoi(tmp->content) != min) { count++; tmp = tmp->next; } return (count); } void ft_basicn(int n, t_ps *ps) { int ronu; int count; if (n && ps->cola) { ronu = ft_findnmin(n, ps->cola); count = ronu; while (ronu) { ft_ra(ps); ronu--; } ft_pb(ps); while (count && ps->cola) { ft_rra(ps); count--; } ft_basicn(n - 1, ps); } } <file_sep>/check_srcs/ft_extract.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_extract.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/13 13:53:18 by tpatter #+# #+# */ /* Updated: 2018/07/25 17:23:03 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "checker.h" #include <stdlib.h> void ft_endarr(char **arr) { int i; i = 0; while (arr[i]) { free(arr[i]); i++; } free(arr); } void ft_extract(char **av, t_check *check) { int i; int j; char **mynus; i = 1; check->cola = NULL; check->colb = NULL; while (av[i]) { mynus = ft_strsplit(av[i], ' '); j = 0; while (mynus[j]) { if (!check->cola) check->cola = ft_lstnew(mynus[j], ft_strlen(mynus[j])); else ft_lstaddend(check->cola, mynus[j], ft_strlen(mynus[j])); j++; } ft_endarr(mynus); i++; } check->nuint = ft_lstlen(check->cola); } <file_sep>/ps_srcs/commands1.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* commands1.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpatter <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/13 14:50:14 by tpatter #+# #+# */ /* Updated: 2018/07/23 09:02:20 by tpatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "push_swap.h" void ft_sa(t_ps *ps) { t_list *tmp; if (ps->cola && ps->cola->next) { ft_putendl("sa"); tmp = ps->cola; ps->cola = ps->cola->next; tmp->next = ps->cola->next; ps->cola->next = tmp; } } void ft_sb(t_ps *ps) { t_list *tmp; if (ps->colb && ps->colb->next) { ft_putendl("sb"); tmp = ps->colb; ps->colb = ps->colb->next; tmp->next = ps->colb->next; ps->colb->next = tmp; } } void ft_ss(t_ps *ps) { t_list *tmp; ft_putendl("ss"); if (ps->cola && ps->cola->next) { tmp = ps->cola; ps->cola = ps->cola->next; tmp->next = ps->cola->next; ps->cola->next = tmp; } if (ps->colb && ps->colb->next) { tmp = ps->colb; ps->colb = ps->colb->next; tmp->next = ps->colb->next; ps->colb->next = tmp; } } void ft_pa(t_ps *ps) { t_list *tmp; if (ps->colb) { ft_putendl("pa"); tmp = ps->colb; ps->colb = ps->colb->next; tmp->next = ps->cola; ps->cola = tmp; } } void ft_pb(t_ps *ps) { t_list *tmp; if (ps->cola) { ft_putendl("pb"); tmp = ps->cola; ps->cola = ps->cola->next; tmp->next = ps->colb; ps->colb = tmp; } }
686f77a5c359e681854cf8645265a5ed9e8dfc7a
[ "C", "Makefile" ]
21
C
TalPat/push_swap
b9094f201fb61b40bea82b683605ff231dcc9f37
cdcf61e57b0093aa9d1bf2c8da1e0d5179d91fb6
refs/heads/master
<file_sep>import { LOAD_EVENTS_SUCCESS, CREATE_EVENT_SUCCESS, UPDATE_EVENT_SUCCESS } from '../constants/actionTypes'; import EventApi from '../api/mockEventApi'; export function loadEventsSuccess(events) { return {type: LOAD_EVENTS_SUCCESS, events}; } export function createEventSuccess(event) { return {type: CREATE_EVENT_SUCCESS, event} } export function updateEventSuccess(event) { return {type: UPDATE_EVENT_SUCCESS, event}; } export function loadEvents() { return function(dispatch) { EventApi.loadEvents() .then(events => { dispatch(loadEventsSuccess(events)); }) .catch(error => { throw(error); }); } } export function saveEvent(event) { return function(dispatch) { return EventApi.saveEvent(event) .then(savedEvent => { event.id ? dispatch(updateEventSuccess(savedEvent)) : dispatch(createEventSuccess(savedEvent)); }) .catch(error => { throw(error); }); } } <file_sep>const events = [ { id: 'default-name', name: 'default name', notes: 'default note' }, { id: 'default-name2', name: 'default name2', notes: 'default note2' } ]; export default class EventApi { static loadEvents() { return new Promise((resolve) => { resolve([...events]); }); } static saveEvent(event) { event = Object.assign({}, event); return new Promise((resolve, reject) => { if (event.name.length < 1) { reject('Missing course name'); } if (event.id) { let modifiedEvent = events.findIndex(arrayEvent => arrayEvent.id === event.id); events.slice(modifiedEvent, 1, event); } else { event.id = event.name.replace(/\s/g, '-'); events.push(event); } resolve(event); }); } } <file_sep>export const LOAD_EVENTS_SUCCESS = 'LOAD_EVENTS_SUCCESS'; export const CREATE_EVENT_SUCCESS = 'CREATE_EVENT_SUCCESS'; export const UPDATE_EVENT_SUCCESS = 'UPDATE_EVENT_SUCCESS'; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import * as eventActions from '../../actions/eventActions' import EventTable from './EventTable'; class HomePage extends React.Component { constructor(props, context) { super(props, context); } render() { return ( <div> <h1>Daily Log</h1> <EventTable events={this.props.events} /> <Link to="/event" className="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">Add Event</Link> </div> ); } } HomePage.propTypes = { events: PropTypes.array.isRequired, actions: PropTypes.object.isRequired }; function mapStateToProps(state) { return { events: state.events }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(eventActions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(HomePage); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; const TR = ({children, selectable}) => { const selectableRowChildren = React.Children.map(children, child => { return React.cloneElement(child, { selectable: selectable && child === children[0] }); }); return ( <tr>{selectableRowChildren}</tr> ); } TR.propTypes = { children: PropTypes.node.isRequired, selectable: PropTypes.bool } export default TR; <file_sep># Daily Log Simple React/Redux app to log various events during the day. Scaffolded using [react-slingshot](https://github.com/coryhouse/react-slingshot). <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import Table from '../common/table/Table'; import TR from '../common/table/TR'; import TH from '../common/table/TH'; import EventTableRow from './EventTableRow'; const EventTable = ({events}) => { return ( <Table selectable={false} headerRow={ <TR> <TH>Event</TH> <TH>Time</TH> <TH>Notes</TH> </TR> } // TODO Refactor?: Create <TBODY> component instead of passing as prop to make // this look more like regular html? bodyRows={events.map(event => <EventTableRow key={event.id} event={event} />)} /> ); }; EventTable.propTypes = { events: PropTypes.array.isRequired } export default EventTable; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; const TH = ({children, selectable}) => { return ( <th className={selectable ? 'mdl-data-table__cell--non-numeric' : ''}>{children}</th> ); } TH.propTypes = { children: PropTypes.node.isRequired, selectable: PropTypes.bool }; export default TH; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import TR from '../common/table/TR'; import TD from '../common/table/TD'; const EventTableRow = ({event, selectable}) => { return ( <TR selectable={selectable}> <TD><Link to={`event/${event.id}`}>{event.name}</Link></TD> <TD>{event.time}</TD> <TD>{event.notes}</TD> </TR> ); }; EventTableRow.propTypes = { event: PropTypes.object.isRequired, selectable: PropTypes.bool }; export default EventTableRow;
29adcd7b040fc0fa39f16b8bc7e7c250abc1ff02
[ "JavaScript", "Markdown" ]
9
JavaScript
nateloberger/daily-log
c560c934ad81e2b7435cd939c1046ea7cd90df28
062140ee9823a7b0f4eb7dedab05841910204224
refs/heads/master
<repo_name>woosanguk-git/express_project<file_sep>/routes/auth.js var express = require("express"); var router = express.Router(); const dbConfig = require("../config/database"); const mysql = require("mysql"); const connection = mysql.createConnection(dbConfig); // router.post("/login_process", function(req, res, next) { // let post = req.body; // let id = post.id; // let pwd = <PASSWORD>; // if (id === testAuthData.id && pwd === testAuthData.password) { // req.session.is_logined = true; // req.session.userId = id; // authLoginCheck(req, res); // // session.save는 세션정보를 저장하는 작업을 바로 실행한다. // req.session.save(function(err) { // res.render("test", {userId : req.session.userId}); // console.log(req.session); // }); // } else { // res.send("fail"); // } // }); router.get("/logout", function(req, res, next) { req.logout(); // passport 에서 넣어둔 기능. // 콜백함수 시간차에 의한 여러가지 오류를 이코드를 통해서 임시적으로 고침. req.session.save(function() { res.redirect("/"); }); }); router.get("/register", function(req, res, next) { res.render("register"); }); router.post("/register_process", function(req, res, next) { let userData = req.body; // body-parser moudle 사용 console.log("유저데이터", userData); console.log("리퀘바디", req.body); const userInsertQuery = `insert into user values('${userData.id}','${userData.pwd}','${userData.displayName}','${userData.name}')`; // console.log(userData.id); connection.query(userInsertQuery, function(error, result) { if (error) { console.error("Register data insert error in mysql"); console.error(error); } const resData = {result : true} res.json(resData); }); }); router.post("/register", function(req, res, next) { const registerData = req.body.data; const type = req.body.type; let checkQuery = ""; // console.log("123123123", registerData); // console.log("123123123", type); if (type == "id") { checkQuery= `SELECT count(id) as num FROM user WHERE id = '${registerData}'`; } else if(type =="displayname"){ checkQuery = `SELECT count(id) as num FROM user WHERE displayname = '${registerData}'`; } connection.query(checkQuery, function(error, data) { const count = data[0].num; console.log(count); // console.log(typeof count); const resData = { count: count }; res.json(resData); }); }); module.exports = router; <file_sep>/routes/board.js var express = require("express"); var router = express.Router(); var sanitizeHtml = require("sanitize-html"); const dbConfig = require("../config/database"); const mysql = require("mysql"); const connection = mysql.createConnection(dbConfig); // 노트북리스트 // 노트리스트 let nbList; let nList; router.get("/main", function(req, res, next) { console.log("/board/main", req.user); const userid = req.user.id; const notebookListQuery = `SELECT id, title FROM notebook where creuser = '${userid}'`; connection.query(notebookListQuery, function(error, data) { if (error) { console.error("노트북 리스트 로드 오류!"); console.error(error); } console.log(data); nbList = data; res.render("main", { userDisplayname: req.user.displayname, notebookList: data }); }); }); router.post("/createnotebook-process", function(req, res, next) { const post = req.body; let bookname = post.notebookName; const userid = req.user.id; bookname = sanitizeHtml(bookname); const createNotebookQuery = `INSERT INTO notebook(title, modidate,creuser) VALUES('${bookname}', NOW(), '${userid}')`; connection.query(createNotebookQuery, function(error, result) { if (error) { console.error("노트북 생성 오류 발생!"); throw error; } res.redirect("/board/main"); }); // console.log("usertest", req.user.id); }); router.get("/:notebookid", function(req, res, next) { // console.log("clean url ~") // params에는 노트북 네임이 들어온다. console.log("노트북 ID : ", req.params.notebookid); const notebookId = req.params.notebookid; // res.redirect("/board/main"); // todo const noteListQuery = `select id, title from note where notebookid = '${notebookId}'`; connection.query(noteListQuery, function(error, data) { if (error) { console.log("노트 리스트 불러오기 오류."); console.error(error); } console.log(data); nList = data; res.render("note", { userDisplayname: req.user.displayname, notebookList: nbList, noteList: data, nowNoteBookId: notebookId }); }); }); // Notebook delete router.get("/:notebookid/delete-process", function(req, res, next) { const notebookId = req.params.notebookid; const notebookDeleteQuery = `DELETE FROM notebook WHERE id = ${notebookId}`; connection.query(notebookDeleteQuery, function(error, result) { if (error) { console.log("노트북 삭제 오류."); console.error(error); } res.redirect("/board/main"); }); }); // note create router.get("/:notebookid/createnote", function(req, res, next) { const notebookId = req.params.notebookid; // console.log(notebookname); res.render("create", { nowNoteBookId: notebookId, userDisplayname: req.user.displayname }); }); router.post("/:notebookid/createnote-process", function(req, res, next) { const post = req.body; let notename = post.title; let content = post.content; const notebookId = req.params.notebookid; notename = sanitizeHtml(notename); content = sanitizeHtml(content); const createNoteQuery = `insert into note(title, content, modidate, notebookid) values('${notename}', '${content}', NOW(), ${notebookId})`; connection.query(createNoteQuery, function(error, result) { if (error) { console.error("노트 생성 오류 발생!"); console.error(error); } console.log(notebookId); res.redirect(`/board/${notebookId}`); }); // console.log("usertest", req.user.id); }); //notebook name modify router.post("/:notebookid/modify-process", function(req, res, next) { const notebookId = req.params.notebookid; const post = req.body; const toChangeNotebookName = sanitizeHtml(post.notebookName); const changeNotebookNameQuery = `UPDATE notebook SET title ='${toChangeNotebookName}',modidate = NOW() WHERE id = ${notebookId}`; connection.query(changeNotebookNameQuery, function(error, result) { if (error) { console.error("노트북 이름 수정 오류 발생!"); console.error(error); } res.redirect(`/board/main`); }); }); router.get("/:notebookid/:noteid", function(req, res, next) { console.log("노트 아이디", req.params.noteid); const notebookId = req.params.notebookid; const noteId = req.params.noteid; const noteContentQuery = `SELECT id, title, content FROM note WHERE id = '${noteId}' and notebookid = '${notebookId}'`; connection.query(noteContentQuery, function(error, data) { if (error) { console.log("노트 내용 불러오기 오류."); console.error(error); } // console.log("노트내용 데이터 : ",data) res.render("content", { userDisplayname: req.user.displayname, notebookList: nbList, noteList: nList, noteData: data, nowNoteBookId: notebookId }); }); }); router.get("/:notebookid/:noteid/notemodify", function(req, res, next) { const notebookId = req.params.notebookid; const noteId = req.params.noteid; const noteContentQuery = `SELECT id, title, content FROM note WHERE id = '${noteId}' and notebookid = '${notebookId}'`; connection.query(noteContentQuery, function(error, data) { if (error) { console.log("노트 내용 불러오기 오류."); console.error(error); } console.log("노트내용 데이터 : ", data); res.render("note_modify", { userDisplayname: req.user.displayname, notebookList: nbList, noteList: nList, noteData: data, nowNoteBookId: notebookId, nowNoteId: noteId }); }); }); router.post("/:notebookid/:noteid/notemodify-process", function( req, res, next ) { const notebookId = req.params.notebookid; const noteId = req.params.noteid; const post = req.body; const notename = sanitizeHtml(post.title); const content = sanitizeHtml(post.content); const noteUpdateQuery = `UPDATE note SET title = '${notename}', content = '${content}', modidate = NOW() WHERE id = ${noteId} AND notebookid = ${notebookId}`; connection.query(noteUpdateQuery, function(error, result) { if (error) { console.log("노트 내용 수정 오류."); console.error(error); } // console.log("결과 : ", result); res.redirect(`/board/${notebookId}/${noteId}`); }); }); router.get("/:notebookid/:noteid/notedelete-process", function(req, res, next) { const notebookId = req.params.notebookid; const noteId = req.params.noteid; const noteDeleteQuery = `DELETE FROM note WHERE id = ${noteId} AND notebookid = ${notebookId}`; connection.query(noteDeleteQuery, function(error, result) { if (error) { console.log("노트 삭제 오류."); console.error(error); } // console.log("결과 : ", result); // TO DO result 이용해서 결과알리기 res.redirect(`/board/${notebookId}/`); }); }); module.exports = router; <file_sep>/README.md # express_project note board porject used express <file_sep>/public/javascripts/register.js const registerForm = document.getElementById("js-user-register"); const idForm = registerForm.querySelector("#js-user-register__form"); const idInput = idForm.querySelector(".js-user-register__idForm-id"); const idAjaxSend = idForm.querySelector(".id-ajaxsend"); const checkMessageDiv = idForm.querySelector(".check-message"); //pwd check const pwd = idForm.querySelector(".js-user-register__idForm-pwd"); const pwdConfirm = idForm.querySelector( ".js-user-register__idForm-pwd-confirm" ); const pwdConfirmMessage = idForm.querySelector(".pwdconfirm-message"); // displayname check const displaynameInput = idForm.querySelector( ".js-user-register__idForm-displayname" ); const displaynameAjaxSend = idForm.querySelector(".displayname-ajaxsend"); const checkDisplaynameMessageDiv = idForm.querySelector( ".check-displayname-message" ); // sign up const signupButton = idForm.querySelector(".js-signup-button"); const overlapHiddenInput = idForm.querySelector(".js-signup-overlap"); let ID_FLAG = false; let PWD_FLAG = false; let DN_FLAG = false; // console.log(registerForm); // console.log(idForm); // console.log(idInput); // console.log(idAjaxSend); function reviseIDFlage(count) { if (count == 0) { ID_FLAG = true; } else { ID_FLAG = false; } overlapCheck(ID_FLAG, PWD_FLAG, DN_FLAG); } function reviseDISPLAYNAMEFlage(count) { if (count == 0) { DN_FLAG = true; } else { DN_FLAG = false; } overlapCheck(ID_FLAG, PWD_FLAG, DN_FLAG); } // id 재입력시 중복체크 메세지 삭제 function handleIdInput() { checkMessageDiv.innerHTML = ""; } // displayname 재입력시 중복체크 메세지 삭제 function handleDisplaynameInput() { checkDisplaynameMessageDiv.innerHTML = ""; } function createMessage(count, type) { const message = document.createElement("p"); if (count != 0) { message.innerText = `이미 존재하는 ${type} 입니다.`; } else { message.innerText = `사용가능한 ${type} 입니다.`; } return message; } // id ajax로 보내기 function sendIDAjax(url, idData) { let data = { data: idData, type: "id" }; data = JSON.stringify(data); let oReq = new XMLHttpRequest(); oReq.open("POST", url); oReq.setRequestHeader("Content-Type", "application/json"); oReq.send(data); oReq.addEventListener("load", function() { let result = JSON.parse(oReq.responseText); // alert(result); let count = result.count; let msg = createMessage(count, JSON.parse(data).type); checkMessageDiv.appendChild(msg); reviseIDFlage(count); }); } // id중복체크 function handleIdAjaxSend() { let idData = idInput.value; // console.log(idData); checkMessageDiv.innerHTML = ""; sendIDAjax("http://localhost:3000/auth/register", idData); } //pwd function createPWDMessage(flag) { const message = document.createElement("p"); if (flag == true) { message.innerText = "패스워드가 일치합니다."; } else { message.innerText = "패스워드가 일치하지않습니다."; } return message; } // pwd 일치 체크 function handlePwdConfirmInput() { pwdConfirmMessage.innerHTML = ""; const pwdData = pwd.value; const pwdConfirmData = pwdConfirm.value; let flag = false; if (pwdData == pwdConfirmData) { flag = true; PWD_FLAG = true; } else { flag = false; PWD_FLAG = false; } let msg = createPWDMessage(flag); pwdConfirmMessage.appendChild(msg); overlapCheck(ID_FLAG, PWD_FLAG, DN_FLAG); } // 닉네임(displayname) 중복체크 ajax function sendDisplaynameAjax(url, displaynameData) { let data = { data: displaynameData, type: "displayname" }; data = JSON.stringify(data); let oReq = new XMLHttpRequest(); oReq.open("POST", url); oReq.setRequestHeader("Content-Type", "application/json"); oReq.send(data); oReq.addEventListener("load", function() { let result = JSON.parse(oReq.responseText); let count = result.count; // alert(result.count); let msg = createMessage(count, JSON.parse(data).type); checkDisplaynameMessageDiv.appendChild(msg); reviseDISPLAYNAMEFlage(count); }); } // 닉네임(displayname) 중복체크 function handleDisplaynameAjaxSend() { let displaynameData = displaynameInput.value; checkDisplaynameMessageDiv.innerHTML = ""; sendDisplaynameAjax("http://localhost:3000/auth/register", displaynameData); } // overlapcheck function overlapCheck(ID_FLAG, PWD_FLAG, DN_FLAG) { if (ID_FLAG == true && PWD_FLAG == true && DN_FLAG == true) { overlapHiddenInput.value = 1; } else{ overlapHiddenInput.value = ""; } } // ajax 로 회원가입할 데이터를 보낸다. function sendRegisterDataAjax(url, registerData) { let data = registerData; data = JSON.stringify(data); let oReq = new XMLHttpRequest(); oReq.open("POST", url); oReq.setRequestHeader("Content-Type", "application/json"); // console.log(data); oReq.send(data); oReq.addEventListener("load", function() { // alert("회원가입이 완료되었습니다."); let result = JSON.parse(oReq.responseText); let flag = result.result; if(flag == true){ alert("회원가입 완료.") location.href = "http://localhost:3000/"; } }); } // 회원가입 function signup() { const registerData = idForm.getElementsByTagName("input"); let overlapCheck = registerData.overlapcheck.value; // console.log(overlapCheck); console.log(ID_FLAG, PWD_FLAG, DN_FLAG); let data = { id: registerData.id.value, pwd: <PASSWORD>, displayName: registerData.displayName.value, name: registerData.name.value }; console.log(overlapCheck); // console.log(data); if (overlapCheck != 1) { alert("회원 데이터를 확인해주십시오."); } else { sendRegisterDataAjax("http://localhost:3000/auth/register_process", data); } } // init function init() { // const tt = idForm.getElementsByTagName("input"); // console.log(tt); // id idAjaxSend.addEventListener("click", handleIdAjaxSend); idInput.addEventListener("input", handleIdInput); // pwd pwdConfirm.addEventListener("input", handlePwdConfirmInput); // displayname displaynameAjaxSend.addEventListener("click", handleDisplaynameAjaxSend); displaynameInput.addEventListener("input", handleDisplaynameInput); // sign up signupButton.addEventListener("click", signup); } init(); <file_sep>/routes/test.js var express = require("express"); var router = express.Router(); router.get("/", function(req, res, next) { // passport 가 req에 user 이라는 객체를 만들어주는것이다. // 로그인 되어있다면 req.user가 들어있어서 True일 거싱고 // 로그인이 되어있지 않다면 false 일 것이다. // req.user 를 이용하여 로그인 상태를 확인하여 뷰를 적용시킨다. console.log('/test', req.user); if(req.user){ res.render('test', {userId : req.user.id}); }else{ res.render('test',{text : 'login fail'}); } }); module.exports = router; <file_sep>/public/javascripts/notebook.js // const notebook = document.getElementById("js-control-buttons"); const notebook = document.getElementById("js-notebooks__control-buttons"); const newNoteButton = document.getElementById("js-control-buttons__new"); const editNotebookButton = document.getElementById("js-control-buttons__edit"); const notebooks = document.querySelectorAll(".js-notebook-column"); // console.log(newNoteButton.textContent); // 노트북 생성폼 추가 function addForm() { const form = document.createElement("form"); form.setAttribute("charset", "UTF-8"); form.setAttribute("method", "Post"); //Post 방식 form.setAttribute("action", "/board/createnotebook-process"); form.setAttribute("id", "js-notebook__form"); // html 엘리먼트 생성 const input = document.createElement("input"); input.setAttribute("type", "text"); input.setAttribute("name", "notebookName"); input.setAttribute("placeholder", "New book name."); const submit = document.createElement("input"); submit.setAttribute("type", "submit"); submit.setAttribute("value", "추가"); const deleteButton = document.createElement("button"); deleteButton.innerText = "X"; // x 버튼 이벤트리스너 추가 deleteButton.addEventListener("click", handleClickDeleteButton); // X 버튼에 id 추가 deleteButton.setAttribute("id", "js-deleteButton"); form.appendChild(input); form.appendChild(submit); form.appendChild(deleteButton); notebook.appendChild(form); } // 추가 버턴 누르면 폼 생성 function handleNewNotebookButton(event) { // 이벤트 리스너 제거 newNoteButton.removeEventListener("click", handleNewNotebookButton); addForm(); } // x버튼 눌렀을 때 function handleClickDeleteButton(event) { if (event) { const form = notebook.querySelector("#js-notebook__form"); this.removeEventListener("click", handleClickDeleteButton); notebook.removeChild(form); } init(); } // Edit function handleEditNotebookButton() { notebookEditForm(); addCancelButton(); } // 노트북 이름 수정에서 x버튼이 눌렸을 때 function handleBooknameModifyCancelButton(event) { // console.log(event); let tobeDeleteElement = event.toElement.parentElement; let parentElement = event.path[2]; // console.log(parentElement); // 얘를 부모 태그에서부터 지우면된다. this.removeEventListener("click", handleBooknameModifyCancelButton); parentElement.removeChild(tobeDeleteElement); } // x버튼이 눌렸을 때 function handleEditCancelButton() { for (let index = 0; index < notebooks.length; index++) { let deleteLink = notebooks[index].querySelector( ".notebook-column__delete-link" ); let modifyButton = notebooks[index].querySelector("button"); // 노트북이름 수정 폼 let notebookModifyForm = notebooks[index].querySelector(".js-notebook-modify__form") notebooks[index].removeChild(deleteLink); notebooks[index].removeChild(modifyButton); if(notebookModifyForm){ notebooks[index].removeChild(notebookModifyForm); } } let editCancelButton = document.getElementById( "js-control-buttons__edit-cancel" ); editCancelButton.removeEventListener("click", handleEditCancelButton); notebook.removeChild(editCancelButton); } // Edit 버튼을 누르면 취소할 수 있는 x버튼 추가. function addCancelButton() { let editCancelButton = document.createElement("button"); editCancelButton.innerText = "X"; editCancelButton.setAttribute("id", "js-control-buttons__edit-cancel"); notebook.appendChild(editCancelButton); editCancelButton.addEventListener("click", handleEditCancelButton); } // 수정버튼이 눌렸을 때 function handleNotebookModifyButton(event) { let parentElement = event.toElement.parentElement; let previousElement = event.toElement.previousElementSibling; let bookName = previousElement.textContent; let notebookURL = previousElement.getAttribute("href"); const div = document.createElement("div"); div.setAttribute("class", "js-notebook-modify__form"); const form = document.createElement("form"); form.setAttribute("charset", "UTF-8"); form.setAttribute("method", "Post"); //Post 방식 form.setAttribute("action", `${notebookURL}/modify-process`); const input = document.createElement("input"); input.setAttribute("type", "text"); input.setAttribute("name", "notebookName"); input.setAttribute("placeholder", bookName); const submit = document.createElement("input"); submit.setAttribute("type", "submit"); submit.setAttribute("value", "Rename"); const cancelButton = document.createElement("button"); cancelButton.setAttribute("type", "button"); cancelButton.innerText = "X"; // cancelButton 이벤트 리스터 추가. cancelButton.addEventListener("click", handleBooknameModifyCancelButton); form.appendChild(input); form.appendChild(submit); div.appendChild(form); div.appendChild(cancelButton); parentElement.appendChild(div); // console.log(notebookURL); // console.log(bookName); // console.log(event.toElement.previousElementSibling); // console.log(event); } // Edit 버튼 눌렀을 때 function notebookEditForm() { for (let index = 0; index < notebooks.length; index++) { let deleteLink = document.createElement("a"); let modifyButton = document.createElement("button"); let deleteButton = document.createElement("button"); let bookName = notebooks[index].querySelector( ".js-notebook-column__bookname" ).textContent; let bookNameURL = notebooks[index] .querySelector(".js-notebook-column__bookname") .getAttribute("href"); // 엘리먼트 속성 설정. deleteLink.setAttribute("href", `${bookNameURL}/delete-process`); deleteLink.setAttribute("class", "notebook-column__delete-link"); modifyButton.setAttribute("type", "button"); modifyButton.addEventListener("click", handleNotebookModifyButton); modifyButton.innerText = "수정"; deleteButton.innerText = "삭제"; deleteLink.appendChild(deleteButton); notebooks[index].appendChild(modifyButton); notebooks[index].appendChild(deleteLink); // console.log(index, notebooks[index]); // console.log("값 가져오기 테스트", notebooks[index].textContent); // console.log(notebooks[index].getElementsByClassName("js-notebook-column__bookname")); // console.log(notebooks[index].querySelector(".js-notebook-column__bookname").textContent); // 값 가져오는거 까지 성공 } } function init() { newNoteButton.addEventListener("click", handleNewNotebookButton); editNotebookButton.addEventListener("click", handleEditNotebookButton); } init(); <file_sep>/app.js // app.js 는 미들웨어를 관리하는 부분이다. var createError = require("http-errors"); var express = require("express"); var path = require("path"); var cookieParser = require("cookie-parser"); var bodyParser = require("body-parser"); var logger = require("morgan"); const session = require("express-session"); // const FileStore = require("session-file-store")(session); //mysql session store const mysql = require("mysql"); var MySQLStore = require("express-mysql-session")(session); var options = { host: "localhost", port: 3306, user: "test_user", password: "<PASSWORD>!", database: "test_DB" }; const connection = mysql.createConnection(options); var sessionStore = new MySQLStore({}, connection); var indexRouter = require("./routes/index"); var usersRouter = require("./routes/users"); var authRouter = require("./routes/auth"); var boardRouter = require("./routes/board"); var testRouter = require("./routes/test"); // app이 http.createServer에서 원하는 요청 핸들러 함수이다. var app = express(); // view engine setup // ejs파일을 저장할때 view폴더에 저장하면 // app.js 에서 알아서 views 폴더 안에 ejs파일을 사용 app.set("views", path.join(__dirname, "views")); // view engine으로 ejs를 사용한다. app.set("view engine", "ejs"); app.use(logger("dev")); app.use(express.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, "public"))); // app.use( // session({ // secret: "keyboard cat", // 암호화 // resave: false, // fasle 면 데이터가 변경될 때만 세션을 저장 // saveUninitialized: true, // 세션이 필요할때만 세션을 구동 (true) // store: new FileStore() // }) // ); app.use( session({ key: "session_cookie_name", secret: "session_cookie_secret", store: sessionStore, resave: false, saveUninitialized: false, cookie: { secure: false } }) ); //passport 모듈 가져오기 const passport = require("./lib/passport")(app, connection); // deserializeUser 가 호출되지 않는 문제 => // const passport = require("./lib/passport")(app, connection);를 // 세션 미들웨어 등록부분 이후에 호출하니 해결되었음 60~69번 줄 소스코드 // 그 전에 호출하니 deserializeUser 가 호출 되지 않앗음 하 ㅅㅂ app.post( "/auth/login_process", passport.authenticate("local", { successRedirect: "/board/main", failureRedirect: "/" }) ); app.use("/", indexRouter); app.use("/users", usersRouter); app.use("/auth", authRouter); app.use("/board", boardRouter); app.use("/test", testRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get("env") === "development" ? err : {}; // render the error page res.status(err.status || 500); res.render("error"); }); module.exports = app; <file_sep>/lib/passport.js //passport.js 모듈은 아래 함수 자체가 되는것이다. module.exports = function(app, connection) { // passport 는 세션을 내부적으로 사용하기 때문에 세션을 활성와 시키는 코드 다음에 등장해야한다. var passport = require("passport"); var LocalStrategy = require("passport-local").Strategy; app.use(passport.initialize()); //passport를 express 에 설치. app.use(passport.session()); // passport가 내부적으로 session을 사용함. passport.serializeUser(function(user, done) { console.log("serializeUser", user); done(null, user.id); // user.id 는 식별자를 사용하면된다. // serializeUser는 로그인 성공하는 순간 딱 한번 호출되는데 // 세션스토어에 정보를 저장하는 역활을 한다. }); passport.deserializeUser(function(id, done) { // deserializeUser는 로그인이 성공하면 페이지를 방문할때 마다 // deserializeUser의 콜백함수가 실행되도록 약속되어있음. // 사용자의 실제 데이터를 조회해서 가져오는 것이다. // 로그인 성공후 serializeUser 실행 후 // 각각의 페이지를 방문할 때마다 로그인한 사용자인지 아닌지를 체크하는 역활. // 그래서 새로고침할 때마다 호출되는 것이다. // done 함수에 사용자 실제 정보를 넣어준 것이다, console.log("deserializeUser", id); const lookUpQuery = `select id, displayname from user where id = '${id}'`; connection.query(lookUpQuery, function(error, data) { // console.log("data check : ", data[0]); done(null, data[0]); }); // User.findById(id, function(err, user) { // done(err, user); // }); }); passport.use( new LocalStrategy( { usernameField: "id", passwordField: "pwd" }, function(username, password, done) { // done이라는 함수를 어떻게 사용하느냐 따라 실패 성공여부를 알릴 수 있다. console.log("LocalStrategy", username, password); const userSelectQuery = `select id, password from user where id = '${username}'`; connection.query(userSelectQuery, function(error, data) { console.log(data[0].id); if (username === data[0].id) { console.log("아이디 일치."); if (password === data[0].password) { console.log("패스워드 일치."); //사용자의 정보를 passport 한테 알려준다. return done(null, data[0]); // 성공하면 done(null, data[0]); 는 // 위에 passport.serializeUser(function(user, done)에 // user 파라미터에 data[0]를 전달한다. } else { console.log("PASSWORD가 일치하지 않습니다."); return done(null, false, { message: "Incorrect password." }); } } else { console.log("ID가 존재하지 않거나 일치하지 않습니다."); return done(null, false, { message: "Incorrect username." }); } }); } ) ); return passport; }; <file_sep>/lib/sanitize-data.js var sanitizeHtml = require("sanitize-html"); function sanitizeHtmlData(data){ let sanitizedData = sanitizeHtml(data); return sanitizedData; } module.exports = sanitizeHtmlData;
169dfc73f2f9fbdfc26fa7324d0b8fe7fd9e09e0
[ "JavaScript", "Markdown" ]
9
JavaScript
woosanguk-git/express_project
cdfc507e2ea564c57583985d400e9eadc7e50f38
989efe432c1a0739a0667af372cabb4816a984a2
refs/heads/master
<file_sep>#py-amber_alert Web Amber Alert framework for use in countries lacking alert infrastructure written in Python3 using Flask, Flask-SQLAlchemy and associated abstraction layers. Please feel free to fork and contribute to the project. Currently, the project is a web app POSTGRES wrapper and has CRUD(Create, Read, Update and Delete) features and a public database view; with administrator only access to the CRUD and base database functions. py-amber_alert was created with the intention of its usage by both the authoritative body in charge in a country without a formal amber alert system as well as any involved Non-Governmental Organizations (NGOs) to track and aid in search and rescue of missing persons. The Amber Alert system operates on the principle of widening the search net by involving and using the public to ensure a faster response. It was originally designed to be implemented in India, but can be easily extended to any relevant situation or place. It is my hope that what I've hacked together will help the rising and rampant rates of kidnapping and missing persons cases in the aforementioned places. ##Quickstart To get started working on the project, you'll need to have a POSTGRES db setup; the details of which you add to config.py under `SQLALCHEMY_DATABASE_URI`. Setting up the db is relatively straightforward, refer to the following that do a much better job than I could. - [Arch Wiki](https://wiki.archlinux.org/index.php/PostgreSQL) - [<NAME>'s Blog](http://clarkdave.net/2012/08/postgres-quick-start-for-people-who-know-mysql/) - [Official PostgreSQL Documentation](https://www.postgresql.org/docs/9.4/static/tutorial-start.html) Install dependencies with `pip install -r requirements.txt` (it is also advisable to be in a virtualenv while running pip). To setup the db, run `python3 run.py init_db`; which initializes the db and writes the necessary trigger functions to the db. You can access the functions by heading over to `localhost:5000`. Set up an admin account through `localhost:5000/register`, after which you can access the CRUD features through `localhost:5000/admin`. Of course, you can always access the functions through the navbar. ##Future modifications and implementations - Geotracking - Beautification (have to learn how to make it look decently pretty.) - Notification system ##Contributors <NAME>, @nravic. Again, please feel free to fork it, pull it, push it and bop it and add to the project. If you have any questions, you can send over an email or track me down on IRC, where I go by @nravic and usually trawl around #archlinux, #python, #emacs or #anime on freenode. ##LICENSE Protected under the MIT license. In short, do what you will with my code; just don't be an ass about it. <file_sep>from flask import request, flash, render_template, url_for, redirect, abort, Blueprint, g from aalert import app, db from flask_login import login_required, logout_user, login_user, current_user from aalert.forms import * from aalert.models import * from sqlalchemy_searchable import search from flask_admin import Admin from flask_admin.contrib.sqla import ModelView @app.before_request def before_request(): g.search_form = SearchForm() @app.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, password=form.password.data) db.session.add(user) db.session.commit() return redirect(url_for('index')) return render_template('register.html', form=form) @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first_or_404() if user.is_correct_password(form.password.data): login_user(user) flash(u'Logged in Successfully.', 'success') return redirect(url_for('index')) else: flash(u'Incorrect username/password combination.', 'error') return redirect(url_for('index')) return render_template('login.html', form=form) @app.route('/', methods=['GET']) def index(): entries = db.session.query(Info.id, Info.firstname, Info.lastname, Info.age, Info.height,Info.last_loc, Info.missing_since) return render_template('disp.html', entries=entries) @app.route('/search', methods=['GET', 'POST']) def search(): if not g.search_form.validate_on_submit(): flash(u'Incorrect format for search string.', 'error') return redirect(url_for('index')) return redirect(url_for('search_results', query=g.search_form.query.data)) @app.route('/search_results/<query>') def search_results(query): results = Info.query.search(query).limit(20).all() if results == None: flash('No hits. Try a different search string.') return render_template('search_results.html', query=query, results=results) @app.route('/logout') def logout(): logout_user() flash(u'Logged out successfully.', 'success') return redirect(url_for('index')) #admin views admin = Admin(app, name='Amber Alert Database', template_mode='bootstrap') class ProtectedView(ModelView): def is_accessible(self): return current_user.is_authenticated def inaccessible_callback(self, name, **kwargs): return redirect(url_for('index')) admin.add_view(ProtectedView(Info, db.session)) <file_sep>DEBUG = True SQLALCHEMY_DATABASE_URI = 'postgresql://scire@localhost/testing_environ' SECRET_KEY = 'something_secret' BCRYPT_LOG_ROUNDS = 12 SQLALCHEMY_TRACK_MODIFICATIONS = True <file_sep>from flask import Flask from flask_bcrypt import Bcrypt from flask_sqlalchemy import SQLAlchemy from flask_admin import Admin from flask_wtf.csrf import CsrfProtect from flask_admin import Admin from sqlalchemy_searchable import make_searchable app = Flask(__name__, static_url_path='/static') app.config.from_pyfile('config.py') db = SQLAlchemy(app) make_searchable() CsrfProtect(app) bcrypt = Bcrypt(app) import aalert.manage import aalert.views from aalert.models import User #login configuration from flask_login import LoginManager login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = "login" @login_manager.user_loader def load_user(userid): return User.query.filter(User.id==userid).first() <file_sep>from random import SystemRandom from datetime import datetime from flask import Flask from sqlalchemy.ext.hybrid import hybrid_property from flask_login import UserMixin from flask_sqlalchemy import BaseQuery from sqlalchemy_searchable import SearchQueryMixin from sqlalchemy_utils.types import TSVectorType from sqlalchemy_searchable import make_searchable from aalert import db, bcrypt #public information table class InfoQuery(BaseQuery, SearchQueryMixin): pass class Info(db.Model): query_class = InfoQuery __tablename__ = 'info' id = db.Column(db.Integer, primary_key=True, unique=True, nullable=False, autoincrement=True) firstname = db.Column(db.Unicode(50)) lastname = db.Column(db.Unicode(50)) age = db.Column(db.Unicode(3)) height = db.Column(db.Unicode(3)) last_loc = db.Column(db.Unicode(180)) missing_since = db.Column(db.Unicode(10)) contact_info = db.Column(db.Unicode(15)) home_address = db.Column(db.Unicode(80)) search_vector = db.Column(TSVectorType('firstname', 'lastname', 'age', 'height', 'last_loc', 'missing_since', 'contact_info', 'home_address')) def __init__(self, firstname=firstname, lastname=lastname, age=age, height=height, last_loc=last_loc, missing_since=missing_since, contact_info=contact_info, home_address=home_address): self.firstname = firstname self.lastname = lastname self.age = age self.height = height self.last_loc = last_loc self.missing_since = missing_since self.contact_info = contact_info self.home_address = home_address def __repr__(self): return '<Info %r>' % self.firstname class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True) _password = db.Column(db.Binary(128)) @hybrid_property def password(self): return self._password @password.setter def _set_password(self, plaintext): self._password = bcrypt.generate_password_hash(plaintext) def is_correct_password(self, plaintext): return bcrypt.check_password_hash(self._password, plaintext) <file_sep>from flask_wtf import Form from wtforms import BooleanField, StringField, PasswordField, DateField, IntegerField, TextAreaField, TextField from wtforms.validators import DataRequired, Length #signin class LoginForm(Form): username = StringField('Username', validators=[DataRequired()]) password = PasswordField('<PASSWORD>', validators=[DataRequired()]) #adding entries class AddEntry(Form): firstname = StringField('First Name', validators = [DataRequired()]) lastname = StringField('Last Name', validators = [Length(min=0, max=50), DataRequired()]) age = IntegerField('Age', validators = [DataRequired()]) height = IntegerField('Height', validators = [DataRequired()]) last_loc = TextAreaField('Last Known Location', validators = [DataRequired()]) missing_since = DateField('Missing Since', validators = [DataRequired()]) contact_info = TextField('Number') home_address = TextAreaField('Home Address', validators = [DataRequired()]) #entry query (search bar type) class SearchForm(Form): query = StringField('Search Query', validators = [DataRequired()]) #register class RegistrationForm(Form): username = StringField('Username', validators=[DataRequired()]) password = PasswordField('<PASSWORD>', validators=[DataRequired()]) <file_sep>alembic==0.8.6 backports.pbkdf2==0.1 bcrypt==2.0.0 blinker==1.4 cffi==1.6.0 click==6.6 decorator==4.0.9 dominate==2.2.0 Flask==0.11.1 Flask-Admin==1.4.2 Flask-Bcrypt==0.7.1 Flask-Login==0.3.2 Flask-Mail==0.9.1 Flask-Migrate==1.8.0 Flask-Principal==0.4.0 Flask-Script==2.0.5 Flask-SQLAlchemy==2.1 Flask-WTF==0.12 itsdangerous==0.24 Jinja2==2.8 Mako==1.0.4 MarkupSafe==0.23 passlib==1.6.5 pbr==1.10.0 psycopg2==2.6.1 pycparser==2.14 pyparsing==2.1.5 python-editor==1.0 six==1.10.0 SQLAlchemy==1.0.13 sqlalchemy-migrate==0.10.0 SQLAlchemy-Searchable==0.10.1 SQLAlchemy-Utils==0.32.7 sqlparse==0.1.19 Tempita==0.5.2 validators==0.10.3 visitor==0.1.3 Werkzeug==0.11.10 WTForms==2.1 <file_sep>from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from aalert import app, db migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.command def init_db(): """ DROPS AND RECREATES SQL SCHEMA """ db.drop_all() db.configure_mappers() db.Model.metadata.create_all(db.session.connection()) db.create_all() db.session.commit() <file_sep>from aalert import app from aalert.manage import manager app.run(debug=True) manager.run()
02817c588b097f64e8c32794979d7724206d9cf0
[ "Markdown", "Python", "Text" ]
9
Markdown
nravic/py-amber_alert
cbe0446e6bbc5c1bd02d02383779e4daad600db5
f620122a51bbed3ae30556bdb7963b0c30b07813
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace CaseFlowManager { class Step : INotifyPropertyChanged { public string id { get; set; } public string name { get; set; } private string document = null; public string Document { get { return document; } set { document = value; NotifyPropertyChanged("Document"); } } private int order; public int Order { get { return order; } set { order = value; NotifyPropertyChanged("Order"); } } private DateTime startTime; public DateTime StartTime { get { return startTime; } set { startTime = value; NotifyPropertyChanged("StartTime"); } } private DateTime endTime; public DateTime EndTime { get { return endTime; } set { endTime = value; NotifyPropertyChanged("EndTime"); } } public int status; public List<Step> nextSteps = new List<Step>(); public List<Step> NextSteps { get { return nextSteps; } set { nextSteps = value; } } public Step(string id, string name) { this.id = id; this.name = name; this.startTime = DateTime.Today; } public Step(Step step) { this.id = step.id; this.name = step.name; this.startTime = DateTime.Today; this.Document = step.Document; } public Step NextStep() { Step nextStep = null; if (nextSteps.Count == 1) { nextStep = nextSteps[0]; } return nextStep; } public bool HasNextStep() { return NextStep() != null; } # region PropertyChanged public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } # endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; using System.ComponentModel; namespace CaseFlowManager { class Case : INotifyPropertyChanged { public string id { get; set; } public string name { get; set; } private int status; public int Status { get { return status; } set { status = value; NotifyPropertyChanged("Status"); } } private DateTime startTime; public DateTime StartTime { get { return startTime; } set { startTime = value; NotifyPropertyChanged("StartTime"); } } private DateTime endTime; public DateTime EndTime { get { return endTime; } set { endTime = value; NotifyPropertyChanged("EndTime"); } } public ObservableCollection<Step> workFlow = new ObservableCollection<Step>(); public ObservableCollection<Step> WorkFlow { get { return workFlow; } set { workFlow = value; } } public Step CurStep { get { return workFlow[workFlow.Count - 1]; } } public Case(string id, string name, bool newcase = true) { this.id = id; this.name = name; if (newcase) { this.Status = 1; // in processing this.StartTime = DateTime.Today; Step firstStep = new Step(CaseFlowManager.Instance.firstStep); firstStep.Order = 1; firstStep.StartTime = DateTime.Today; workFlow.Add(firstStep); } } public void StepDone() { CurStep.EndTime = DateTime.Today; CurStep.status = 2; if (CurStep.HasNextStep()) { Step nextStep = new Step(CurStep.NextStep()); workFlow.Add(nextStep); nextStep.Order = workFlow.Count; } else { endTime = DateTime.Today; Status = 2; // finish } } # region PropertyChanged public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } # endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace CaseFlowManager { /// <summary> /// NewCase.xaml 的交互逻辑 /// </summary> public partial class NewCaseView : Window { public NewCaseView() { InitializeComponent(); } private CaseFlowManager manager = CaseFlowManager.Instance; private void Ok_Click(object sender, RoutedEventArgs e) { string id = (++manager.idCount).ToString(); Case acase = new Case(id, this.textBox1.Text); manager.Cases.Add(acase); manager.curCase = acase; manager.DumpCase(acase); this.Close(); } private void Cancel_Click(object sender, RoutedEventArgs e) { this.Close(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace CaseFlowManager { /// <summary> /// StepSelectView.xaml 的交互逻辑 /// </summary> public partial class StepSelectView : Window { public StepSelectView() { InitializeComponent(); curCase = manager.curCase; curStep = curCase.CurStep; this.listBox1.ItemsSource = curStep.NextSteps; } private CaseFlowManager manager = CaseFlowManager.Instance; private Case curCase = null; private Step curStep = null; public void OkBtn_Click(object sender, RoutedEventArgs e) { if (this.listBox1.SelectedIndex < 0) { MessageBox.Show(@"请选择下一步"); return; } Step nextStep = curStep.NextSteps[this.listBox1.SelectedIndex]; curStep.NextSteps.Clear(); curStep.NextSteps.Add(nextStep); curCase.StepDone(); manager.DumpCase(curCase); this.Close(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Data; using System.Globalization; using System.Windows.Controls; namespace CaseFlowManager { public class ProcessConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Int32 status = (Int32)value; switch (status) { case 0: return @"Resource\Images\nostart.png"; case 1: return @"Resource\Images\run.png"; case 2: return @"Resource\Images\done.png"; default: return null; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class DocumentConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string doc = (string)value; if (doc != null) return @"Resource\Images\doc.png"; else return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class DateConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { DateTime date = (DateTime)value; if (date != null && date.Year != 1) return date.ToShortDateString(); else return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Diagnostics; using Excel = Microsoft.Office.Interop.Excel; namespace CaseFlowManager { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); manager.Initial(); this.remainderText.Text = manager.remainderDay.ToString(); this.caseSummaryView.ItemsSource = manager.Cases; this.Loaded += new RoutedEventHandler(MainWindow_Loaded); } private CaseFlowManager manager = CaseFlowManager.Instance; private void newBtn_Click(object sender, RoutedEventArgs e) { NewCaseView newCaseWin = new NewCaseView(); newCaseWin.Show(); } private void MainWindow_Loaded(object sender, EventArgs e) { manager.RemaindCases(); } private void caseSummaryView_SelectionChanged(object sender, SelectionChangedEventArgs e) { manager.curCase = this.caseSummaryView.SelectedItem as Case; this.caseDetailView.ItemsSource = (manager.curCase != null) ? manager.curCase.WorkFlow : null; this.caseDetailView.SelectedIndex = 0; } private void caseDetailView_SelectionChanged(object sender, SelectionChangedEventArgs e) { int curId = this.caseDetailView.SelectedIndex; int totalStep = this.caseDetailView.Items.Count; if (curId == totalStep - 1 && manager.curCase != null && manager.curCase.Status != 2) { this.finishBtn.IsEnabled = true; } else { this.finishBtn.IsEnabled = false; } } private void finishBtn_Click(object sender, RoutedEventArgs e) { Case curCase = manager.curCase; int curId = this.caseDetailView.SelectedIndex; int nextCnt = manager.FillNextSteps(); if (nextCnt > 1) { StepSelectView selectView = new StepSelectView(); selectView.Show(); } else { curCase.StepDone(); } this.finishBtn.IsEnabled = false; this.caseDetailView.SelectedIndex = curId + 1; manager.DumpCase(curCase); } private void deleteBtn_Click(object sender, RoutedEventArgs e) { int selectId = this.caseSummaryView.SelectedIndex; int lastId = this.caseSummaryView.Items.Count - 1; if (selectId != -1) { this.caseSummaryView.SelectedIndex = (selectId == lastId) ? -1 : selectId + 1; manager.RemoveCase(manager.Cases[selectId]); } } private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { DependencyObject img = (DependencyObject)sender; DependencyObject obj = VisualTreeHelper.GetParent(img); DependencyObject obj1 = VisualTreeHelper.GetParent(obj); Step docStep = ((GridViewRowPresenter)obj1).Content as Step; string doc = docStep.Document; string path = String.Format("Data\\{0}_{1}\\{2}", manager.curCase.id, manager.curCase.name, doc); try { Process.Start(path); } catch { string msg = String.Format("在文件夹( {0}_{1} )中找不到文件: {2}", manager.curCase.id, manager.curCase.name, doc); MessageBox.Show(msg); } } private void exportBtn_Click(object sender, RoutedEventArgs e) { Excel.Application excel = new Excel.Application(); excel.DisplayAlerts = false; excel.AlertBeforeOverwriting = false; object misValue = System.Reflection.Missing.Value; try { Excel.Workbook workbook = excel.Workbooks.Add(misValue); for (int i = 1; i <= manager.Cases.Count; i++) { Case acase = manager.Cases[i - 1]; Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets.get_Item(i); worksheet.Name = acase.name; for (int j = 1; j <= acase.WorkFlow.Count; j++) { Step astep = acase.WorkFlow[j - 1]; worksheet.Cells[j, 1] = astep.Order.ToString(); worksheet.Cells[j, 2] = astep.name; worksheet.Cells[j, 3] = astep.StartTime.ToShortDateString(); if (astep.status == 2) worksheet.Cells[j, 4] = astep.EndTime.ToShortDateString(); } } workbook.SaveAs(@"案件汇总.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); workbook.Close(true, misValue, misValue); MessageBox.Show("导出Excel成功,存放在“我的文档”文件夹下"); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { excel.Quit(); } } private void setdayBtn_Click(object sender, RoutedEventArgs e) { try { manager.remainderDay = Int32.Parse(this.remainderText.Text); manager.RemaindCases(); manager.parser.SaveRemainderDay(manager.remainderDay, @"Resource\Configs\SysConfig.xml"); } catch { MessageBox.Show("请输入正确的日期"); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Windows; namespace CaseFlowManager { class XmlParser { private XmlDocument doc; public void ParseSysConfig(string path) { try { doc = new XmlDocument(); doc.Load(path); // parse the remainder day XmlNode remainderNode = doc.GetElementsByTagName("reminder")[0]; CaseFlowManager.Instance.remainderDay = Int32.Parse(remainderNode.InnerText); // 1. create all step instances Dictionary<string, Step> stepMaps = new Dictionary<string, Step>(); XmlNodeList stepList = doc.GetElementsByTagName("step"); for (int i = 0; i < stepList.Count; ++i) { XmlNode node = stepList[i]; string id = node.Attributes["id"].Value; string name = node.Attributes["name"].Value; Step step = new Step(id, name); // add document information for (int j = 0; j < node.ChildNodes.Count; ++j) { XmlNode child = node.ChildNodes[j]; if (child.Name.Equals("document")) { step.Document = child.InnerText; } } stepMaps.Add(id, step); } // 2. chain the steps for (int i = 0; i < stepList.Count; ++i) { XmlNode node = stepList[i]; string id = node.Attributes["id"].Value; Step step = stepMaps[id]; for (int j = 0; j < node.ChildNodes.Count; ++j) { XmlNode child = node.ChildNodes[j]; if (child.Name.Equals("next") && !child.InnerText.Equals("null")) { step.nextSteps.Add(stepMaps[child.InnerText]); } } CaseFlowManager.Instance.workFlow.Add(step); } // 3. mark the first step XmlNode workFlow = doc.GetElementsByTagName("WorkFlow")[0]; string firstId = workFlow.FirstChild.Attributes["id"].Value; CaseFlowManager.Instance.firstStep = stepMaps[firstId]; } catch (Exception e) { MessageBox.Show(e.Message); } } public void SaveRemainderDay(int day, string path) { try { doc = new XmlDocument(); doc.Load(path); XmlNode remainderNode = doc.GetElementsByTagName("reminder")[0]; remainderNode.InnerText = CaseFlowManager.Instance.remainderDay.ToString(); doc.Save(path); } catch (Exception ex) { MessageBox.Show(ex.Message); } } public Case LoadCase(string file) { Case acase = null; try { doc = new XmlDocument(); doc.Load(file); // retrive <CaseInfo> XmlNode caseId = doc.GetElementsByTagName("CaseId")[0]; string id = caseId.InnerText; XmlNode caseName = doc.GetElementsByTagName("CaseName")[0]; string name = caseName.InnerText; acase = new Case(id, name, false); XmlNode caseStatus = doc.GetElementsByTagName("CaseStatus")[0]; acase.Status = Int32.Parse(caseStatus.InnerText); XmlNode caseStart = doc.GetElementsByTagName("CaseBegin")[0]; acase.StartTime = StringtoDateTime(caseStart.InnerText); if (acase.Status == 2) { XmlNode caseEnd = doc.GetElementsByTagName("CaseEnd")[0]; acase.EndTime = StringtoDateTime(caseEnd.InnerText); } // retrive <WorkFlow> XmlNodeList stepList = doc.GetElementsByTagName("step"); for (int i = 0; i < stepList.Count; ++i) { XmlNode stepNode = stepList[i]; string _id = stepNode.Attributes["id"].Value; string _name = stepNode.Attributes["name"].Value; Step step = new Step(_id, _name); for (int j = 0; j < stepNode.ChildNodes.Count; ++j) { string tag = stepNode.ChildNodes[j].Name; string text = stepNode.ChildNodes[j].InnerText; if (tag.Equals("status")) step.status = Int32.Parse(text); if (tag.Equals("begin")) step.StartTime = StringtoDateTime(text); if (tag.Equals("end")) step.EndTime = StringtoDateTime(text); if (tag.Equals("order")) step.Order = Int32.Parse(text); if (tag.Equals("document")) step.Document = text; } acase.workFlow.Add(step); } } catch (Exception e) { MessageBox.Show(e.Message); } return acase; } public void DumpCase(Case acase, string file) { doc = new XmlDocument(); doc.LoadXml("<Case></Case>"); XmlElement root = doc.DocumentElement; // assemble <CaseInfo> XmlElement caseInfo = doc.CreateElement("CaseInfo"); XmlElement id = doc.CreateElement("CaseId"); id.InnerText = acase.id; caseInfo.AppendChild(id); XmlElement name = doc.CreateElement("CaseName"); name.InnerText = acase.name; caseInfo.AppendChild(name); XmlElement status = doc.CreateElement("CaseStatus"); status.InnerText = acase.Status.ToString(); caseInfo.AppendChild(status); XmlElement begin = doc.CreateElement("CaseBegin"); begin.InnerText = DateTimeToString(acase.StartTime); caseInfo.AppendChild(begin); if (acase.Status == 2) { XmlElement end = doc.CreateElement("CaseEnd"); end.InnerText = DateTimeToString(acase.EndTime); caseInfo.AppendChild(end); } root.AppendChild(caseInfo); // assemble <WorkFlow> XmlElement workFlow = doc.CreateElement("WorkFlow"); for (int i = 0; i < acase.workFlow.Count; ++i) { Step step = acase.workFlow[i]; XmlElement _step = doc.CreateElement("step"); _step.SetAttribute("id", step.id); _step.SetAttribute("name", step.name); XmlElement _order = doc.CreateElement("order"); _order.InnerText = step.Order.ToString(); _step.AppendChild(_order); XmlElement _status = doc.CreateElement("status"); _status.InnerText = step.status.ToString(); _step.AppendChild(_status); XmlElement _begin = doc.CreateElement("begin"); _begin.InnerText = DateTimeToString(step.StartTime); _step.AppendChild(_begin); if (step.status == 2) { XmlElement _end = doc.CreateElement("end"); _end.InnerText = DateTimeToString(step.EndTime); _step.AppendChild(_end); } if (step.Document != null) { XmlElement _doc = doc.CreateElement("document"); _doc.InnerText = step.Document; _step.AppendChild(_doc); } workFlow.AppendChild(_step); } root.AppendChild(workFlow); doc.Save(file); } private DateTime StringtoDateTime(string str) { string[] arr = str.Split('/'); return new DateTime(Int32.Parse(arr[0]), Int32.Parse(arr[1]), Int32.Parse(arr[2])); } private string DateTimeToString(DateTime date) { return date.ToShortDateString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Collections.ObjectModel; using System.Windows; using System.IO; namespace CaseFlowManager { class CaseFlowManager : INotifyPropertyChanged { private static CaseFlowManager instance = null; public static CaseFlowManager Instance { get { if (instance == null) { instance = new CaseFlowManager(); } return instance; } } private CaseFlowManager() { parser = new XmlParser(); } public XmlParser parser; public int idCount = 0; // for generic work flow public List<Step> workFlow = new List<Step>(); public Step firstStep = null; // store all the case data private ObservableCollection<Case> cases = new ObservableCollection<Case>(); public ObservableCollection<Case> Cases { get { return cases; } set { cases = value; NotifyPropertyChanged("Cases"); } } public Case curCase = null; public int remainderDay = 1; public void Initial() { int maxCaseId = 0; char delim = '_'; try { parser.ParseSysConfig(@"Resource\Configs\SysConfig.xml"); DirectoryInfo DataDir = new DirectoryInfo(@"Data"); foreach (DirectoryInfo caseDir in DataDir.GetDirectories()) { FileInfo xmlFile = null; int id = Int32.Parse(caseDir.Name.Split(delim)[0]); maxCaseId = (id > maxCaseId) ? id : maxCaseId; foreach (FileInfo file in caseDir.GetFiles()) { if (file.Name.EndsWith(@".xml")) { xmlFile = file; break; } } Case acase = LoadCase(xmlFile.FullName); cases.Add(acase); } idCount = maxCaseId; } catch (Exception e) { MessageBox.Show(e.Message); } } public int FillNextSteps() { Step curStep = curCase.CurStep; curStep.NextSteps.Clear(); for (int i = 0; i < workFlow.Count; i++) { if (workFlow[i].id.Equals(curStep.id)) { foreach (Step s in workFlow[i].NextSteps) { curStep.NextSteps.Add(new Step(s)); } } } return curStep.NextSteps.Count; } public void RemoveCase(Case acase) { Cases.Remove(acase); string name = String.Format("{0}_{1}", acase.id, acase.name); string path = String.Format("Data\\{0}", name); DeleteFolder(path); } public void DeleteFolder(string dir) { if (Directory.Exists(dir)) { foreach (string d in Directory.GetFileSystemEntries(dir)) { if (File.Exists(d)) File.Delete(d); else DeleteFolder(d); } Directory.Delete(dir); } } public void CopyFiles(string srcDir, string tgtDir) { char delim = '\\'; if (Directory.Exists(srcDir) && Directory.Exists(tgtDir)) { foreach (string srcFile in Directory.GetFileSystemEntries(srcDir)) { string [] arr = srcFile.Split(delim); string tgtFile = String.Format("{0}\\{1}", tgtDir, arr[arr.Length-1]); File.Copy(srcFile, tgtFile); } } } public void DumpCase(Case acase) { string name = String.Format("{0}_{1}", acase.id, acase.name); string path = String.Format("Data\\{0}", name); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); CopyFiles(@"Resource\Doc", path); } parser.DumpCase(acase, String.Format("{0}\\{1}.xml", path, name)); } public Case LoadCase(string caseFile) { return parser.LoadCase(caseFile); } public void RemaindCases() { Dictionary<Case, int> remainderList = new Dictionary<Case, int>(); foreach (Case acase in Cases) { if (acase.Status == 1) { TimeSpan ts = DateTime.Today - acase.StartTime; if (ts.Days >= this.remainderDay) remainderList[acase] = ts.Days; } } if (remainderList.Count > 0) { string msg = "注意!以下案件已经过期:\n"; foreach (Case acase in remainderList.Keys) { msg += String.Format("{0} : {1} 天\n", acase.name, remainderList[acase]); } MessageBox.Show(msg); } } # region PropertyChanged public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } # endregion } }
c89a32d99290d1aeedb3af319ab9a80d31d22e14
[ "C#" ]
8
C#
zaviichen/CaseFlowManager
c1e0a81909e58fa6ae709661588dbf38d2b7945a
c4d14b9f6538653ff787bbfb371b9db43e0b0813
refs/heads/master
<repo_name>captainmattg/captainmattg.github.io<file_sep>/js/home.js var config = { apiKey: "<KEY>", authDomain: "jaunt-ddc86.firebaseapp.com", databaseURL: "https://jaunt-ddc86.firebaseio.com", projectId: "jaunt-ddc86", storageBucket: "jaunt-ddc86.appspot.com", messagingSenderId: "40972835460" }; firebase.initializeApp(config); /** * Handles the sign in button press. */ function toggleSignIn() { if (firebase.auth().currentUser) { // [START signout] firebase.auth().signOut(); // [END signout] } else { var email = document.getElementById('email').value; var password = document.getElementById('password').value; if (email.length < 4) { alert('Please enter an email address.'); return; } if (password.length < 4) { alert('Please enter a password.'); return; } // Sign in with email and pass. // [START authwithemail] firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // [START_EXCLUDE] if (errorCode === 'auth/wrong-password') { alert('Wrong password.'); } else { console.error(error); } // [END_EXCLUDE] }); // [END authwithemail] } document.getElementById('quickstart-sign-in').disabled = true; } /** * initApp handles setting up UI event listeners and registering Firebase auth listeners: * - firebase.auth().onAuthStateChanged: This listener is called when the user is signed in or * out, and that is where we update the UI. */ function initApp() { // Listening for auth state changes. // [START authstatelistener] firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. var displayName = user.displayName; var email = user.email; var emailVerified = user.emailVerified; var photoURL = user.photoURL; var isAnonymous = user.isAnonymous; var uid = user.uid; var refreshToken = user.refreshToken; var providerData = user.providerData; const imgRef = firebase.storage().ref(); //SET NAME + Email + ProfPic var mainRef = firebase.database().ref('Users/' + uid); mainRef.once("value") .then(function(snapshot) { var name = snapshot.child('/name').val(); var email = snapshot.child('/email').val(); var authorPic = snapshot.child('/profile_picture').val(); document.getElementById('name').textContent = name; document.getElementById('email').textContent = email; }); var mainRef1 = firebase.database().ref('Admin/xplore'); mainRef1.once("value") .then(function(snapshot) { var largeTitle1 = snapshot.child('/large/title1').val(); var largeTitle2 = snapshot.child('/large/title2').val(); var largeTitle3 = snapshot.child('/large/title3').val(); var largeTitle4 = snapshot.child('/large/body1').val(); var largeTitle5 = snapshot.child('/large/body2').val(); var largeTitle6 = snapshot.child('/large/lat').val(); var largeTitle7 = snapshot.child('/large/long').val(); var largeTitle8 = snapshot.child('/large/localName').val(); var largeTitle9 = snapshot.child('/large/localAbout').val(); var largeTitle10 = snapshot.child('/large/localUID').val(); document.getElementById('largeTitle1In').value = largeTitle1; document.getElementById('largeTitle2In').value = largeTitle2; document.getElementById('largeTitle3In').value = largeTitle3; document.getElementById('largeTitle4In').value = largeTitle4; document.getElementById('largeTitle5In').value = largeTitle5; document.getElementById('largeTitle6In').value = largeTitle6; document.getElementById('largeTitle7In').value = largeTitle7; document.getElementById('largeNameIn').value = largeTitle8; document.getElementById('largeAboutIn').value = largeTitle9; document.getElementById('largeUIDIn').value = largeTitle10; var small1Title1 = snapshot.child('/small1/title1').val(); var small1Title2 = snapshot.child('/small1/title2').val(); var small1Title3 = snapshot.child('/small1/title3').val(); var small1Title4 = snapshot.child('/small1/body1').val(); var small1Title5 = snapshot.child('/small1/body2').val(); var small1Title6 = snapshot.child('/small1/lat').val(); var small1Title7 = snapshot.child('/small1/long').val(); var small1Title8 = snapshot.child('/small1/localName').val(); var small1Title9 = snapshot.child('/small1/localAbout').val(); var small1Title10 = snapshot.child('/small1/localUID').val(); document.getElementById('small1Title1In').value = small1Title1; document.getElementById('small1Title2In').value = small1Title2; document.getElementById('small1Title3In').value = small1Title3; document.getElementById('small1Title4In').value = small1Title4; document.getElementById('small1Title5In').value = small1Title5; document.getElementById('small1Title6In').value = small1Title6; document.getElementById('small1Title7In').value = small1Title7; document.getElementById('small1NameIn').value = small1Title8; document.getElementById('small1AboutIn').value = small1Title9; document.getElementById('small1UIDIn').value = small1Title10; var small2Title1 = snapshot.child('/small2/title1').val(); var small2Title2 = snapshot.child('/small2/title2').val(); var small2Title3 = snapshot.child('/small2/title3').val(); var small2Title4 = snapshot.child('/small2/body1').val(); var small2Title5 = snapshot.child('/small2/body2').val(); var small2Title6 = snapshot.child('/small2/lat').val(); var small2Title7 = snapshot.child('/small2/long').val(); var small2Title8 = snapshot.child('/small2/localName').val(); var small2Title9 = snapshot.child('/small2/localAbout').val(); var small2Title10 = snapshot.child('/small2/localUID').val(); document.getElementById('small2Title1In').value = small2Title1; document.getElementById('small2Title2In').value = small2Title2; document.getElementById('small2Title3In').value = small2Title3; document.getElementById('small2Title4In').value = small2Title4; document.getElementById('small2Title5In').value = small2Title5; document.getElementById('small2Title6In').value = small2Title6; document.getElementById('small2Title7In').value = small2Title7; document.getElementById('small2NameIn').value = small2Title8; document.getElementById('small2AboutIn').value = small2Title9; document.getElementById('small2UIDIn').value = small2Title10; var small3Title1 = snapshot.child('/small3/title1').val(); var small3Title2 = snapshot.child('/small3/title2').val(); var small3Title3 = snapshot.child('/small3/title3').val(); var small3Title4 = snapshot.child('/small3/body1').val(); var small3Title5 = snapshot.child('/small3/body2').val(); var small3Title6 = snapshot.child('/small3/lat').val(); var small3Title7 = snapshot.child('/small3/long').val(); var small3Title8 = snapshot.child('/small3/localName').val(); var small3Title9 = snapshot.child('/small3/localAbout').val(); var small3Title10 = snapshot.child('/small3/localUID').val(); document.getElementById('small3Title1In').value = small3Title1; document.getElementById('small3Title2In').value = small3Title2; document.getElementById('small3Title3In').value = small3Title3; document.getElementById('small3Title4In').value = small3Title4; document.getElementById('small3Title5In').value = small3Title5; document.getElementById('small3Title6In').value = small3Title6; document.getElementById('small3Title7In').value = small3Title7; document.getElementById('small3NameIn').value = small3Title8; document.getElementById('small3AboutIn').value = small3Title9; document.getElementById('small3UIDIn').value = small3Title10; var small4Title1 = snapshot.child('/small4/title1').val(); var small4Title2 = snapshot.child('/small4/title2').val(); var small4Title3 = snapshot.child('/small4/title3').val(); var small4Title4 = snapshot.child('/small4/body1').val(); var small4Title5 = snapshot.child('/small4/body2').val(); var small4Title6 = snapshot.child('/small4/lat').val(); var small4Title7 = snapshot.child('/small4/long').val(); var small4Title8 = snapshot.child('/small4/localName').val(); var small4Title9 = snapshot.child('/small4/localAbout').val(); var small4Title10 = snapshot.child('/small4/localUID').val(); document.getElementById('small4Title1In').value = small4Title1; document.getElementById('small4Title2In').value = small4Title2; document.getElementById('small4Title3In').value = small4Title3; document.getElementById('small4Title4In').value = small4Title4; document.getElementById('small4Title5In').value = small4Title5; document.getElementById('small4Title6In').value = small4Title6; document.getElementById('small4Title7In').value = small4Title7; document.getElementById('small4NameIn').value = small4Title8; document.getElementById('small4AboutIn').value = small4Title9; document.getElementById('small4UIDIn').value = small4Title10; var small5Title1 = snapshot.child('/small5/title1').val(); var small5Title2 = snapshot.child('/small5/title2').val(); var small5Title3 = snapshot.child('/small5/title3').val(); var small5Title4 = snapshot.child('/small5/body1').val(); var small5Title5 = snapshot.child('/small5/body2').val(); var small5Title6 = snapshot.child('/small5/lat').val(); var small5Title7 = snapshot.child('/small5/long').val(); var small5Title8 = snapshot.child('/small5/localName').val(); var small5Title9 = snapshot.child('/small5/localAbout').val(); var small5Title10 = snapshot.child('/small5/localUID').val(); document.getElementById('small5Title1In').value = small5Title1; document.getElementById('small5Title2In').value = small5Title2; document.getElementById('small5Title3In').value = small5Title3; document.getElementById('small5Title4In').value = small5Title4; document.getElementById('small5Title5In').value = small5Title5; document.getElementById('small5Title6In').value = small5Title6; document.getElementById('small5Title7In').value = small5Title7; document.getElementById('small5NameIn').value = small5Title8; document.getElementById('small5AboutIn').value = small5Title9; document.getElementById('small5UIDIn').value = small5Title10; }); var lrgFileButton = document.getElementById("lrgFileButton"); var lrgFileButton2 = document.getElementById("lrgFileButton2"); var lrgFileButton3 = document.getElementById("lrgFileButton3"); var sml1FileButton = document.getElementById("sml1FileButton"); var sml1FileButton2 = document.getElementById("sml1FileButton2"); var sml2FileButton = document.getElementById("sml2FileButton"); var sml2FileButton2 = document.getElementById("sml2FileButton2"); var sml3FileButton = document.getElementById("sml3FileButton"); var sml3FileButton2 = document.getElementById("sml3FileButton2"); var sml4FileButton = document.getElementById("sml4FileButton"); var sml4FileButton2 = document.getElementById("sml4FileButton2"); var sml5FileButton = document.getElementById("sml5FileButton"); var sml5FileButton2 = document.getElementById("sml5FileButton2"); lrgFileButton.addEventListener('change', function(e){ var file = e.target.files[0]; var storageRef = firebase.storage().ref("large"); storageRef.put(file); }); lrgFileButton2.addEventListener('change', function(e){ var file = e.target.files[0]; var storageRef = firebase.storage().ref("large2"); storageRef.put(file); }); lrgFileButton3.addEventListener('change', function(e){ var file = e.target.files[0]; var storageRef = firebase.storage().ref("large3"); storageRef.put(file); }); sml1FileButton.addEventListener('change', function(e){ var file = e.target.files[0]; var storageRef = firebase.storage().ref("small1"); storageRef.put(file); }); sml1FileButton2.addEventListener('change', function(e){ var file = e.target.files[0]; var storageRef = firebase.storage().ref("small12"); storageRef.put(file); }); sml2FileButton.addEventListener('change', function(e){ var file = e.target.files[0]; var storageRef = firebase.storage().ref("small2"); storageRef.put(file); }); sml2FileButton2.addEventListener('change', function(e){ var file = e.target.files[0]; var storageRef = firebase.storage().ref("small22"); storageRef.put(file); }); sml3FileButton.addEventListener('change', function(e){ var file = e.target.files[0]; var storageRef = firebase.storage().ref("small3"); storageRef.put(file); }); sml3FileButton2.addEventListener('change', function(e){ var file = e.target.files[0]; var storageRef = firebase.storage().ref("small32"); storageRef.put(file); }); sml4FileButton.addEventListener('change', function(e){ var file = e.target.files[0]; var storageRef = firebase.storage().ref("small4"); storageRef.put(file); }); sml4FileButton2.addEventListener('change', function(e){ var file = e.target.files[0]; var storageRef = firebase.storage().ref("small42"); storageRef.put(file); }); sml5FileButton.addEventListener('change', function(e){ var file = e.target.files[0]; var storageRef = firebase.storage().ref("small5"); storageRef.put(file); }); sml5FileButton2.addEventListener('change', function(e){ var file = e.target.files[0]; var storageRef = firebase.storage().ref("small52"); storageRef.put(file); }); // [START_EXCLUDE silent] document.getElementById('signButton').textContent = 'sign out'; // [END_EXCLUDE] } else { // [END_EXCLUDE] window.location.replace("https://app.jaunt-app.co.uk/"); } }); // [END authstatelistener] document.getElementById('signButton').addEventListener('click', toggleSignIn, false); document.getElementById('saveButton').addEventListener('click', save, true); } function upload() { const file = $('#photo').get(0).files[0]; } function save() { var xploreLargeRef = firebase.database().ref('Admin/xplore/large'); var xploreSmall1Ref = firebase.database().ref('Admin/xplore/small1'); var xploreSmall2Ref = firebase.database().ref('Admin/xplore/small2'); var xploreSmall3Ref = firebase.database().ref('Admin/xplore/small3'); var xploreSmall4Ref = firebase.database().ref('Admin/xplore/small4'); var xploreSmall5Ref = firebase.database().ref('Admin/xplore/small5'); var pushRef = xploreLargeRef.push(); var lt1 = document.getElementById('largeTitle1In').value; var lt2 = document.getElementById('largeTitle2In').value; var lt3 = document.getElementById('largeTitle3In').value; var lt4 = document.getElementById('largeTitle4In').value; var lt5 = document.getElementById('largeTitle5In').value; var lt6 = document.getElementById('largeTitle6In').value; var lt7 = document.getElementById('largeTitle7In').value; var lt8 = document.getElementById('largeNameIn').value; var lt9 = document.getElementById('largeAboutIn').value; var lt10 = document.getElementById('largeUIDIn').value; var s1t1 = document.getElementById('small1Title1In').value; var s1t2 = document.getElementById('small1Title2In').value; var s1t3 = document.getElementById('small1Title3In').value; var s1t4 = document.getElementById('small1Title4In').value; var s1t5 = document.getElementById('small1Title5In').value; var s1t6 = document.getElementById('small1Title6In').value; var s1t7 = document.getElementById('small1Title7In').value; var s1t8 = document.getElementById('small1NameIn').value; var s1t9 = document.getElementById('small1AboutIn').value; var s1t10 = document.getElementById('small1UIDIn').value; var s2t1 = document.getElementById('small2Title1In').value; var s2t2 = document.getElementById('small2Title2In').value; var s2t3 = document.getElementById('small2Title3In').value; var s2t4 = document.getElementById('small2Title4In').value; var s2t5 = document.getElementById('small2Title5In').value; var s2t6 = document.getElementById('small2Title6In').value; var s2t7 = document.getElementById('small2Title7In').value; var s2t8 = document.getElementById('small2NameIn').value; var s2t9 = document.getElementById('small2AboutIn').value; var s2t10 = document.getElementById('small2UIDIn').value; var s3t1 = document.getElementById('small3Title1In').value; var s3t2 = document.getElementById('small3Title2In').value; var s3t3 = document.getElementById('small3Title3In').value; var s3t4 = document.getElementById('small3Title4In').value; var s3t5 = document.getElementById('small3Title5In').value; var s3t6 = document.getElementById('small3Title6In').value; var s3t7 = document.getElementById('small3Title7In').value; var s3t8 = document.getElementById('small3NameIn').value; var s3t9 = document.getElementById('small3AboutIn').value; var s3t10 = document.getElementById('small3UIDIn').value; var s4t1 = document.getElementById('small4Title1In').value; var s4t2 = document.getElementById('small4Title2In').value; var s4t3 = document.getElementById('small4Title3In').value; var s4t4 = document.getElementById('small4Title4In').value; var s4t5 = document.getElementById('small4Title5In').value; var s4t6 = document.getElementById('small4Title6In').value; var s4t7 = document.getElementById('small4Title7In').value; var s4t8 = document.getElementById('small4NameIn').value; var s4t9 = document.getElementById('small4AboutIn').value; var s4t10 = document.getElementById('small4UIDIn').value; var s5t1 = document.getElementById('small5Title1In').value; var s5t2 = document.getElementById('small5Title2In').value; var s5t3 = document.getElementById('small5Title3In').value; var s5t4 = document.getElementById('small5Title4In').value; var s5t5 = document.getElementById('small5Title5In').value; var s5t6 = document.getElementById('small5Title6In').value; var s5t7 = document.getElementById('small5Title7In').value; var s5t8 = document.getElementById('small5NameIn').value; var s5t9 = document.getElementById('small5AboutIn').value; var s5t10 = document.getElementById('small5UIDIn').value; xploreLargeRef.set({ title1 : lt1, title2 : lt2, title3 : lt3, body1 : lt4, body2 : lt5, lat : lt6, long : lt7, localName : lt8, localAbout : lt9, localUID : lt10 }); xploreSmall1Ref.set({ title1 : s1t1, title2 : s1t2, title3 : s1t3, body1 : s1t4, body2 : s1t5, lat : s1t6, long : s1t7, localName : s1t8, localAbout : s1t9, localUID : s1t10 }); xploreSmall2Ref.set({ title1 : s2t1, title2 : s2t2, title3 : s2t3, body1 : s2t4, body2 : s2t5, lat : s2t6, long : s2t7, localName : s2t8, localAbout : s2t9, localUID : s2t10 }); xploreSmall3Ref.set({ title1 : s3t1, title2 : s3t2, title3 : s3t3, body1 : s3t4, body2 : s3t5, lat : s3t6, long : s3t7, localName : s3t8, localAbout : s3t9, localUID : s3t10 }); xploreSmall4Ref.set({ title1 : s4t1, title2 : s4t2, title3 : s4t3, body1 : s4t4, body2 : s4t5, lat : s4t6, long : s4t7, localName : s4t8, localAbout : s4t9, localUID : s4t10 }); xploreSmall5Ref.set({ title1 : s5t1, title2 : s5t2, title3 : s5t3, body1 : s5t4, body2 : s5t5, lat : s5t6, long : s5t7, localName : s5t8, localAbout : s5t9, localUID : s5t10 }); } window.onload = function() { initApp(); }; <file_sep>/js/slider.js $(function () { $('.marquee').marquee({ duration: 14000, duplicated: true, gap: 00, direction: 'left', pauseOnHover: true }); });// JavaScript Document
366ec349f85260d936978a75a05500627d139179
[ "JavaScript" ]
2
JavaScript
captainmattg/captainmattg.github.io
9cb7398a2aa9e712a51dc534c43b4c626afb3acc
120a517abf2d0e50818760a9275ba6ff5cc5550a
refs/heads/master
<repo_name>BruceChanJianLe/CPP_SmartPointers<file_sep>/ExerciseFiles/deleter.cpp #include "my_strc.hpp" #include "my_func.hpp" using namespace std; // There are several ways to create a custom deleter // 1. function // 2. functor // 3. lambda void deleter(const myStrC * o) { cout << "func deleter: "; if(o) { cout << o->value() << endl; } else { cout << "[null]" << endl; } cout << flush; delete o; } class D { public: void operator () (const myStrC * o) { cout << "class deleter: "; if(o) { cout << o->value() << endl; } else { cout << "[null]" << endl; } cout << flush; delete o; } }; int main(int argc, char ** argv) { message("first method using a function"); message("create share pointer"); std::shared_ptr<myStrC> a(new myStrC("thing"), &deleter); message("display a"); disp(a); message("reset a"); a.reset(); disp(a); message("second method using class functor"); message("create second share pointer"); std::shared_ptr<myStrC> b(new myStrC("thing2"), D()); message("display b"); disp(b); message("reset b"); b.reset(); disp(b); message("third method using lambda"); message("create third share pointer"); std::shared_ptr<myStrC> c(new myStrC("thing3"), [=](const myStrC * o) { cout << "lambda deleter: "; if(o) { cout << o->value() << endl; } else { cout << "[null]" << endl; } cout << flush; delete o; } ); message("display c"); disp(c); message("reset c"); c.reset(); disp(c); message("end of scope"); return 0; }<file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.17) project(smartPointer) # SET(CMAKE_CXX_FLAGS "-std=c++17") SET(CMAKE_CXX_STANDARD 17) SET(CMAKE_CXX_STANDARD_REQUIRED ON) SET(CMAKE_CXX_COMPILE_FEATURES ON) add_executable(uniquePointer ExerciseFiles/unique.cpp ExerciseFiles/my_func.cpp ExerciseFiles/my_strc.cpp) add_executable(sharedPointer ExerciseFiles/share.cpp ExerciseFiles/my_func.cpp ExerciseFiles/my_strc.cpp) # add_executable(sharedPointer2 ExerciseFiles/shared_ptr.cpp ExerciseFiles/strc.cpp) add_executable(weakPointer ExerciseFiles/weak.cpp ExerciseFiles/my_func.cpp ExerciseFiles/my_strc.cpp) add_executable(customDeleter ExerciseFiles/deleter.cpp ExerciseFiles/my_func.cpp ExerciseFiles/my_strc.cpp)<file_sep>/README.md # Smart Pointers Smart pointer is basically a template class that uses operator overloads to provide the functionality of a pointer. While providing additional features to support improved memory management and safety. A smart pointer is essentially a wrapper around a standard bare C-langauge pointer. It is designed to provide these benefits while operating as closely as possible to a standard pointer. Smart pointers are in `#include <memory>` header. **Unique Pointer** - Only one copy of this pointer - Cannot be copied - Can be safely destroy its associated resources by calling reset on the pointer - Can transfer ownership by moving it **Shared Pointer** - Can make copies of this pointer - Can delete those copies as much as I want - The resources will automatically and safely be destroyed when all copies of pointers are deleted or when it goes out of scope **Weak Pointer** - Weak pointer is used to prevent circular references - Weak pointer goes out of scope when its share pointers gets deleted ## Summary C++ provides three different types of smart pointers, unique pointer, shared pointer and weak pointer. So, how do I choose which one to use in a given situation? My strategy is to start with a default choice and specialize from there. For most purposes, I'll choose a shared pointer by default. It's powerful and flexible, while still being safe. This is the pointer that works most like unmanaged pointer, but it still manages objects nicely. I'll choose a weak pointer for circumstances where I need an optional value, that is, I don't require a pointer to be valid. I just need to know if it is or it isn't valid. This is useful for breaking up circular references, but it's also useful for other cases where I need to link to a resource that's managed by another object. Finally, I'll choose a unique pointer in cases where I need to know that a resource is only available to one object at a time. This is a one to one relationship. A unique pointer cannot be copied. This is actually a bit deceptive because you can take an L reference of a unique pointer. Because of this, some developers like to use the unique pointer as their default choice and only use the shared pointer where it's necessary to actually share the pointer. You may certainly do that if you like. It's really a matter of style. For my part, I like the explicit nature of the shared pointer, rather the implicit of using a unique pointer with L references. This is my strategy and you're welcome to use it as a starting point. I strongly suggest that you spend some time working with the different types of smart pointers. Then, you'll develop a strategy that works for you. ## Reference - [Top 10 dumb mistakes to avoid with C++ 11 smart pointers](https://www.acodersjourney.com/top-10-dumb-mistakes-avoid-c-11-smart-pointers/) <file_sep>/ExerciseFiles/my_func.hpp #ifndef __MYFUNC_H_ #define __MYFUNC_H_ #include <iostream> #include <string> #include <memory> #include "my_strc.hpp" using namespace std; void message(const string s); void disp(std::unique_ptr<myStrC> & o); void disp(const std::shared_ptr<myStrC> & o); void disp(const std::weak_ptr<myStrC> & o); #endif<file_sep>/ExerciseFiles/weak.cpp #include "my_strc.hpp" #include "my_func.hpp" using namespace std; int main(int argc, char ** argv) { message("create shared pointer"); auto a = std::make_shared<myStrC>("thing"); message("make several copies"); auto c1 = a; auto c2 = a; auto c3 = a; auto c4 = a; auto c5 = a; message("reference count is now 6"); disp(a); message("create weak pointer"); auto w1 = std::weak_ptr<myStrC>(a); disp(w1); message("destory copies"); c1.reset(); c2.reset(); c3.reset(); c4.reset(); c5.reset(); message("reference count should be 1"); disp(a); message("check weak pointer"); disp(w1); message("destroy a"); a.reset(); message("check weak pointer"); disp(w1); message("end of scope"); return 0; }<file_sep>/ExerciseFiles/my_func.cpp #include "my_func.hpp" using namespace std; void message(const string s) { cout << endl << s << endl << flush; } // To display unique pointer void disp(std::unique_ptr<myStrC> & o) { if(o) { cout << o->value() << endl; } else { cout << "null" << endl; } cout << flush; } // To display shared pointer void disp(const std::shared_ptr<myStrC> & o) { if(o) { cout << o->value() << " (" << o.use_count() << ")" << endl; } else { cout << "null" << endl; } cout << flush; } // To display weak pointer alongside with shared pointer void disp(const std::weak_ptr<myStrC> & o) { // Must obtain a lock to use a weak pointer auto count = o.use_count(); auto sp = o.lock(); if(sp) { cout << sp->value() << " (w:" << count << " s:" << sp.use_count() << ")" << endl; } else { cout << "[null]" << endl; } cout << flush; }<file_sep>/ExerciseFiles/unique.cpp #include "my_strc.hpp" #include "my_func.hpp" using namespace std; // Function to demonstarte that you cannot pass a unique pointer // to a function without referencing it void f(unique_ptr<myStrC> & p) { message("f()"); disp(p); } int main(int argc, char ** argv) { message("create unique pointer one"); std::unique_ptr<myStrC> a(new myStrC("one")); disp(a); message("make_unique two"); auto b = std::make_unique<myStrC>("two"); disp(a); disp(b); message("reset a to three"); a.reset(new myStrC("three")); disp(a); disp(b); message("move b to c"); auto c = std::move(b); disp(a); disp(b); disp(c); message("reset a"); a.reset(); disp(a); disp(b); disp(c); // Unique pointer can only be pass by reference in function f(c); message("end of scope"); return 0; }<file_sep>/ExerciseFiles/my_strc.cpp #include "my_strc.hpp" #include <memory> using namespace std; void myStrC::msg(const string s) { if(!data.empty()) { cout << __mystrc_class << ": " << s << " (" << data << ")" << endl; } else { cout << __mystrc_class << ": " << s << endl; } cout << flush; } myStrC::myStrC() : data({}) { msg("default ctor"); } myStrC::myStrC(const string s) : data(s) { msg("cstring ctor"); } myStrC::myStrC(const myStrC & f) : data(f.data) { msg("copy ctor"); } myStrC::myStrC(myStrC && o) : data(std::move(o.data)) { o.data = {}; msg("move ctor"); } myStrC::~myStrC() { msg("dtor"); } myStrC & myStrC::operator = (myStrC o) { swap(o); msg("copy and swap ="); return * this; } const string myStrC::value () const { return data; } myStrC::operator const string () const { return value(); } void myStrC::swap(myStrC & o) { std::swap(this->data, o.data); } bool myStrC::operator == (const myStrC & o) const { // cout << "funciton overload " << flush; if(data == o.data) { return true; } else { return false; } }<file_sep>/ExerciseFiles/my_strc.hpp // My string wrapper class #ifndef __MYSTRC_H_ #define __MYSTRC_H_ #include <iostream> #include <string> using namespace std; static const string __mystrc_class = "my_strc"; static const string __mystrc_version = "1.0"; class myStrC { private: string data {}; void msg(const string); public: myStrC(); myStrC(const string s); myStrC(const myStrC &); myStrC(myStrC &&); ~myStrC(); myStrC & operator = (myStrC); const string value() const; operator const string () const; void swap(myStrC &); bool operator == (const myStrC &) const; }; #endif<file_sep>/ExerciseFiles/share.cpp #include "my_strc.hpp" #include "my_func.hpp" using namespace std; int main(int argc, char ** argv) { message("create share pointer with new"); std::shared_ptr<myStrC> a1(new myStrC("none")); auto a = std::make_shared<myStrC>("new"); message("reset a to one"); a.reset(new myStrC("one")); disp(a); message("b = a"); auto b = a; disp(a); disp(b); cout << "a == b " << (a == b ? "true" : "false") << endl; cout << "* a == * b " << (* a == * b ? "true" : "false") << endl; message("reset a to two"); a.reset(new myStrC("two")); disp(a); disp(b); cout << "a == b " << (a == b ? "true" : "false") << endl; cout << "* a == * b " << (* a == * b ? "true" : "false") << endl; message("b.swap(a)"); b.swap(a); disp(a); disp(b); message("std::swap using obj"); std::swap(a, b); disp(a); disp(b); message("std::swap using pointer"); std::swap(*a, *b); disp(a); disp(b); message("end of scope"); return 0; }
a1cc20bbe4d043dc42229b1cd53962969e297990
[ "Markdown", "CMake", "C++" ]
10
C++
BruceChanJianLe/CPP_SmartPointers
b40d2589038e0586f439cfa9a327e95c48b07323
4739c638d711bd924b21480a2c30ddaa299d6a97
refs/heads/master
<file_sep>Events are a model of stuff happening in games. How we manage these events is called even handling. Events are very variable so it would be cool if we could modify functions on the fly and pass them around. For our case, we have an application. That application creates a window object. The window generates events from user input, etc... As we don't want the window to contain any application functions, we can pass the window a callback function instead. For simplicity we are not going to implement a buffered event system (a queue for events to be done instead at every frame). We are just going to be letting the event execute and pause the rest of our program (blocking event). We need to create Application IEventListener, OnEvent class, Event types and debug data.<file_sep>#include "ptpch.h"<file_sep>#pragma once // For use by Praction applications #include "Praction/Application.h" #include "Praction/Layer.h" #include "Praction/Log.h" #include "Praction/ImGui/ImGuiLayer.h" // ---Entry Point------------------- #include "Praction/EntryPoint.h" //----------------------------------<file_sep>Modern OpenGL (Glad) Next steps, ImGUI running. ImGUI is a framework to get a UI fast. UI is important to not have to recompile code whenever we want to change a single variable. In the OpenGL series we used a extension called GLEW. We are going to be using GLAD. GLAD loads the libraries from the graphics card. 1. We are going to configure it on the website first 2. We are going to add it as a separate project 3. Then set it up in the premake file. <file_sep># Praction engine Praction engine is my attempt to make a game engine. I will be following the guidance TheChernoProject's Hazel engine and other internet related resources in this endeavor. ## Features * Windowing (windows only) * Debugging Tools (Logger) ## Features in development * Game Engine Framework * Windowing (desktop only for now) * Renderer using OpenGL (Windows only for now) * Debugging Tools * Level editor that operates at run time (ImGui) * Scripting language for content creators * Memory Management System * Entity-component System (game objects functions and family tree) * Physics * File management system (virtual support) * Build system ## Patch notes: * Patch 0.0.14 ImGui Events * Patch 0.0.13 ImGui Added in debug menu screen (non-functional yet) * Patch 0.0.12 OpenGL extension (Glad) Added Glad to modernize and extend OpenGL. * Patch 0.0.11 Layers Added in the Layer Class. * Patch 0.0.10 Window Event Added in the Window Event system. * Patch 0.0.9 Window Abstraction and GLFW Added in Window class using GLFW * Patch 0.0.8 Precompiled headers Added in precompiled headers file. * Patch 0.0.7 Events Created Event, mouse event, keyboard event, application classes. * Patch 0.0.6 Premake Created premake5.lua to assist in automating generation of project files * Patch 0.0.5 Logger Clients have now access to a error display logger. * Patch 0.0.4 Entry Point Clients can now create Praction engine's applications objects * Patch 0.0.1 Initial setup<file_sep>ImGui Previously we used Glad to import modern OpenGl functions from the graphics card. Today we are going to use ImGui to make a debug menu. Make it work. Make is correct. Make it fast. We going to make it work first just hacking in ImGui into the game engine.<file_sep># DESIGNING our GAME ENGINE ## Difficulty of making a game engine * Just using heuristics, it is hard to make a game engine: * Most game studios make games with pre-existing game engines * If game studio makes a game engine it usually takes a lot of resources * There are already free resources on the internet * No reason to reinvent the wheel * We are not a massive team so we have to limit the scope of project * Can't build Unreal or Unity * Must take it slowly to present instructions ## Game Engine Framework * Minimal frame work to get feature running * Iterate over to further develop feature ## Future Features * Level editor that operates at run time (ImGui) * Shader compilation ## Next Planning Lessons * API for renderer * naming ## Game Engine Framework Features * Entry point (i.e. at launch of the program) * what is executed in the main function * who is providing input to the program (user or game or engine) * engine macros * Application layer * life cycle of applications * run loop * what keeps game executing code * time keeping * events * windows resized * controls * Window layer (desktop support) * input * events * events manager * Renderer * Render API abstraction using OpenGL * OpenGL is the simplest API * OpenGL is cross platform (Mac, Linux) * Debugging support * Logging * Scripting language: allows artist/content creators to operate without thinking of low-level engine systems like memory * Memory Systems * Entity-component System * Physics * File I/O, Virtual File System * Build system<file_sep>#pragma once #include "Praction/Core.h" #include "Layer.h" #include <vector> namespace Praction { // LayerStack is a wrapper over a vector of layers (m_Layers) class PRACTION_API LayerStack { public: LayerStack(); ~LayerStack(); void PushLayer(Layer* layer); void PushOverlay(Layer* overlay); void PopLayer(Layer* layer); void PopOverlay(Layer* overlay); // begins, end allows us to iterate using a range based for loop, forwards and backwards. std::vector<Layer*>::iterator begin() { return m_Layers.begin(); } std::vector<Layer*>::iterator end() { return m_Layers.end(); } private: // m_Layer is a vector of layers std::vector<Layer*> m_Layers; // m_LayerInsert allows us to iterate over the layers and go reverse order for events std::vector<Layer*>::iterator m_LayerInsert; }; } <file_sep>#pragma once #include "Core.h" #include "Window.h" #include "Praction/LayerStack.h" #include "Praction/Events/Event.h" #include "Praction/Events/ApplicationEvent.h" namespace Praction { // Application is a class that allow other projects to launch the game engine's applications class PRACTION_API Application { public: Application(); virtual ~Application(); void Run(); void OnEvent(Event& e); void PushLayer(Layer* layer); void PushOverlay(Layer* layer); inline Window& GetWindow() { return *m_Window; } inline static Application& Get() { return *s_Instance; } private: bool OnWindowClose(WindowCloseEvent& e); std::unique_ptr<Window> m_Window; bool m_Running = true; LayerStack m_LayerStack; private: static Application* s_Instance; }; // Allows projects to create a new game engine application object // Client impliments method Application* CreateApplication(); } <file_sep># Project Generation Project generation is good to assist in generating new projects on different platforms. We are currently using Visual Studio on Windows (Windows Environment). We would like to add Mac, Linux, iOS and Android. To do this it is important to abstract the game engine out of the Windows environment and make it more generalizable. Premake is a utility that assists in generating project files for toolsets like Visual Studio, Xcode or GNU Make. A similar program is CMake. <file_sep># Logging Developing games are an error prone business. Some bugs are not visible using just breakpoint and watch windows. printf debugging helps display the program internal state. Win32 does not have a console however it does provide the function OutputDebugString(). The format of the string however is quite complicated with the different types of variables can output. We will use a library called spdlog to create a standard format. https://github.com/gabime/spdlog As this will be an external library, we will use Git's sub-module to attach it our repository. Open Praction directory in CMD. ~ >> git sub-module add https://github.com/gabime/spdlog Praction/vendor/spdlog In the game engines' and sandbox's properties: C/C++ >> General >> Additional Include Directories >> add $(SolutionDir)Praction\vendor\spdlog\include; <file_sep># Project Setup Things to setup * Github * Visual Studio Solution * Visual Studio Configuration Github * Create new repository * Clone the git repository to a folder Visual Studio Solution * Create an empty project in VS * Copy all files in git folder into VS project folder * .git * README.md * LICENSE Visual Studio Configuration The game engine made into a dynamic link library for the game to link to. * Platforms * We won't be supporting 32 bit * project -> properties -> configuration manager * remove x86 and Win32 * active solution platform -> x86 * project contexts -> platform -> Win32 * game engine is a dynamic library * back in properties -> General -> Configuration Type -> set to Dynamic Library (.dll) * output and intermediate directories (where files generated go, VS defaults not good enough) * Output Directory -> set to $(SolutionDir)bin\$(Configuration)-$(Platform)\$(ProjectName)\ * Intermediate Directory -> set to $(SolutionDir)bin-int\$(Configuration)-$(Platform)\$(ProjectName)\ Game Project (Sandbox) The game engine needs an application to run it. * Create a new empty project called Sandbox * Follow instructions again * Platforms * output and intermediate directories * Set Sandbox as right click -> Set as the startup project Project Ordering Other people may want to checkout the engine by downloading and hitting F5. Since the engine is a dll file it won't work automatically so changing the ordering so the Sandbox comes first will allow the Sandbox to start instead. * Close the solution * Open project solution in a text editor (not VS) * Move Sandbox line above game-engine line. I.e.: * Project("...") = "Sandbox",... * EndProject * Project("...") = "game-engine",... * EndProject Linking Projects Link Sandbox and the game engine together * Right-click -> Add -> Reference... -> game engine Project folders Add folders: * src <file_sep># Entry Point What does the program do on start up? Today we are going to setup the sandbox's ability to use the game engine's applications. We will setup a game engine application class and setup the export and importing preprocessor commands. ## In Properties: Praction: Configuration: All Configuration C/C++ >> Preprocessor >> add PT_PLATFORM_WINDOWS;PT_BUILD_DLL; SandBox: Configuration: All Configuration C/C++ >> Preprocessor >> add PT_PLATFORM_WINDOWS; Note: PT stands for Praction (game engine name) <file_sep>#include "ptpch.h" #include "Application.h" #include "Praction/Log.h" #include <glad/glad.h> namespace Praction { #define BIND_EVENT_FN(x) std::bind(&Application::x, this, std::placeholders::_1) Application* Application::s_Instance = nullptr; Application::Application() { PT_CORE_ASSERT(!s_Instance, "Application already exists!"); s_Instance = this; m_Window = std::unique_ptr<Window>(Window::Create()); m_Window->SetEventCallback(BIND_EVENT_FN(OnEvent)); } Application::~Application() { } // Wrapper for application to push new layer to layer stack void Application::PushLayer(Layer* layer) { m_LayerStack.PushLayer(layer); layer->OnAttach(); } // Wrapper for application to push new overlay to layer stack void Application::PushOverlay(Layer* layer) { m_LayerStack.PushOverlay(layer); layer->OnAttach(); } void Application::OnEvent(Event & e) { EventDispatcher dispatcher(e); dispatcher.Dispatch<WindowCloseEvent>(BIND_EVENT_FN(OnWindowClose)); // handle each event by going backwards through the layer stack // (e.g. button on top of background gets clicked first) for (auto it = m_LayerStack.end(); it != m_LayerStack.begin(); ) { (*--it)->OnEvent(e); if (e.Handled) break; } } // game engine's application run loop void Application::Run() { while (m_Running) { glClearColor(1, 0, 1, 1); glClear(GL_COLOR_BUFFER_BIT); // iterate over the layer stack and update layer (frame) for (Layer* layer : m_LayerStack) layer->OnUpdate(); m_Window->OnUpdate(); } } bool Application::OnWindowClose(WindowCloseEvent & e) { m_Running = false; return true; } } <file_sep>#pragma once #include "Core.h" #include "spdlog/spdlog.h" #include "spdlog/fmt/ostr.h" namespace Praction { class PRACTION_API Log { public: // Init customises the logger created by spdlog static void Init(); // functions to return game engine's or client logger inline static std::shared_ptr<spdlog::logger>& GetCoreLogger() { return s_CoreLogger; } inline static std::shared_ptr<spdlog::logger>& GetClientLogger() { return s_ClientLogger; } private: // smart pointers to the game engine's or client logger static std::shared_ptr<spdlog::logger> s_CoreLogger; static std::shared_ptr<spdlog::logger> s_ClientLogger; }; } // Core log macros #define PT_CORE_TRACE(...) ::Praction::Log::GetCoreLogger()->trace(__VA_ARGS__) #define PT_CORE_INFO(...) ::Praction::Log::GetCoreLogger()->info(__VA_ARGS__) #define PT_CORE_WARN(...) ::Praction::Log::GetCoreLogger()->warn(__VA_ARGS__) #define PT_CORE_ERROR(...) ::Praction::Log::GetCoreLogger()->error(__VA_ARGS__) #define PT_CORE_FATAL(...) ::Praction::Log::GetCoreLogger()->fatal(__VA_ARGS__) // Client log macros #define PT_TRACE(...) ::Praction::Log::GetClientLogger()->trace(__VA_ARGS__) #define PT_INFO(...) ::Praction::Log::GetClientLogger()->info(__VA_ARGS__) #define PT_WARN(...) ::Praction::Log::GetClientLogger()->warn(__VA_ARGS__) #define PT_ERROR(...) ::Praction::Log::GetClientLogger()->error(__VA_ARGS__) #define PT_FATAL(...) ::Praction::Log::GetClientLogger()->fatal(__VA_ARGS__) <file_sep>workspace "Praction" architecture "x64" configurations { "Debug", "Release", "Dist" } --[[ output directory is the location of built files --]] outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}" --[[ cfg.buildcfg : debug/release/etc --]] --[[ cfg.system : windows/mac/linux --]] --[[ cfg.architecture : x64/x86/etc --]] -- Include directories are set relative to root folder (solution directory) IncludeDir = {} IncludeDir["GLFW"] = "Praction/vendor/GLFW/include" IncludeDir["Glad"] = "Praction/vendor/Glad/include" IncludeDir["ImGui"] = "Praction/vendor/imgui" -- IncludeDir is a struct that will grow as more directories are to be included include "Praction/vendor/GLFW" include "Praction/vendor/Glad" include "Praction/vendor/imgui" project "Praction" location "Praction" kind "SharedLib" language "C++" staticruntime "off" --[[ binaries executable --]] targetdir ("bin/" .. outputdir .. "/%{prj.name}") --[[ prj.name : project name --]] --[[ object files --]] objdir ("bin-int/" .. outputdir .. "/%{prj.name}") --[[ precompiled files --]] pchheader "ptpch.h" pchsource "Praction/src/ptpch.cpp" files { "%{prj.name}/src/**.h", "%{prj.name}/src/**.cpp" } includedirs { "%{prj.name}/src", "%{prj.name}/vendor/spdlog/include", "%{IncludeDir.GLFW}", "%{IncludeDir.Glad}", "%{IncludeDir.ImGui}" } links { "GLFW", "Glad", "ImGui", "opengl32.lib" } filter "system:windows" cppdialect "C++17" systemversion "latest" defines { "PT_PLATFORM_WINDOWS", "PT_BUILD_DLL", "GLFW_INCLUDE_NONE" } --[[ automatically copies game engine's dll into sanbox's after each build --]] postbuildcommands { ("{COPY} %{cfg.buildtarget.relpath} ../bin/" .. outputdir .. "/Sandbox") } filter "configurations:Debug" defines "PT_DEBUG" runtime "Debug" symbols "On" filter "configurations:Release" defines "PT_RELEASE" runtime "Release" optimize "On" filter "configurations:Dist" defines "PT_DIST" runtime "Release" optimize "On" project "Sandbox" location "Sandbox" kind "ConsoleApp" language "C++" staticruntime "off" --[[ binaries --]] targetdir ("bin/" .. outputdir .. "/%{prj.name}") --[[ object files --]] objdir ("bin-int/" .. outputdir .. "/%{prj.name}") files { "%{prj.name}/src/**.h", "%{prj.name}/src/**.cpp" } includedirs { "Praction/vendor/spdlog/include", "Praction/src" } links { "Praction" } filter "system:windows" cppdialect "C++17" systemversion "latest" defines { "PT_PLATFORM_WINDOWS" } filter "configurations:Debug" defines "PT_DEBUG" runtime "Debug" symbols "On" filter "configurations:Release" defines "PT_RELEASE" runtime "Release" optimize "On" filter "configurations:Dist" defines "PT_DIST" runtime "Release" optimize "On" <file_sep>#pragma once #include "ptpch.h" #include "Praction/Core.h" #include "Praction/Events/Event.h" namespace Praction { struct WindowProps { // Window properties std::string Title; unsigned int Width; unsigned int Height; // default values of title, width and height if not specified WindowProps( const std::string& title = "Praction Engine", unsigned int width = 1280, unsigned int height = 720 ) : Title(title), Width(width), Height(height) { } }; // Interface representing a destop system based Window class PRACTION_API Window { public: // Event call back function using EventCallbackFn = std::function<void(Event&)>; // Virtual destructor virtual ~Window() {} // Various virtual window methods virtual void OnUpdate() = 0; virtual unsigned int GetWidth() const = 0; virtual unsigned int GetHeight() const = 0; // Window attributes virtual void SetEventCallback(const EventCallbackFn& callback) = 0; virtual void SetVSync(bool enabled) = 0; virtual bool IsVSync() const = 0; // Virtual method to create the window (implimented per platform) static Window* Create(const WindowProps& props = WindowProps()); }; // All methods are virtual (no data or functions) // These methods will be implimented per platform }<file_sep>We are developing a Windows class in an abstracted way. We are using GLFW. GLFW is an OpenGl extensions that add support for creating windows. GLFW does not support DirectX so at some point we will have to replace it. In anticipation of this, we will implement a window class per platform. Each platform (Windows, Mac, Linux) will have their own separate folder.<file_sep>#pragma once #include "Praction/Core.h" #include "Praction/Events/Event.h" namespace Praction { // Layer should be subclassed and have its virtual function implimented class PRACTION_API Layer { public: // Constructor for a layer (takes in a layer name for debug purposes) Layer(const std::string& name = "Layer"); virtual ~Layer(); // OnAttach: When a layer is pushed on to the layer stack virtual void OnAttach() {} // OnDetach: a layer is removed from the layer stack virtual void OnDetach() {} // OnUpdate: Called by the application to update the frame virtual void OnUpdate() {} // When an event is sent to the layer it is sent here virtual void OnEvent(Event& event) {} inline const std::string& GetName() const { return m_DebugName; } protected: // storing the layer name (should be used only for debug purposes) std::string m_DebugName; }; }<file_sep>#include "ptpch.h" #include "Log.h" #include "spdlog/sinks/stdout_color_sinks.h" namespace Praction { std::shared_ptr<spdlog::logger> Log::s_CoreLogger; std::shared_ptr<spdlog::logger> Log::s_ClientLogger; // Init customises the logger created by spdlog void Log::Init() { // spdlog pattern of formatting text spdlog::set_pattern("%^[%T] %n: %v%$"); // %^ : color // %T : timestamp // %n : name of logger // %v%$ : log message // logger for game engine s_CoreLogger = spdlog::stdout_color_mt("Praction"); s_CoreLogger->set_level(spdlog::level::trace); // set_level : set types of messages to be printed // trace : lowest level meaning all messages are printed // logger for client app s_ClientLogger = spdlog::stdout_color_mt("APP"); s_ClientLogger->set_level(spdlog::level::trace); } } <file_sep>#pragma once #include "ptpch.h" #include "Praction/Core.h" namespace Praction { // Praction is currently using blocking code to handle events. // A class to differentiate different types of events (i.e. not just using int) enum class EventType { None = 0, WindowClose, WindowResize, WindowFocus, WindowLostFocus, WindowMoved, AppTick, AppUpdate, AppRender, KeyPressed, KeyReleased, KeyTyped, MouseButtonPressed, MouseButtonReleased, MouseMoved, MouseScrolled }; // EventCategory allows filtering of events. See definition of BIT in CORE.h enum EventCategory { None = 0, EventCategoryApplication = BIT(0), EventCategoryInput = BIT(1), EventCategoryKeyboard = BIT(2), EventCategoryMouse = BIT(3), EventCategoryMouseButton = BIT(4) }; // macros to impliment the three type, name and flag virtual funtions in base event class #define EVENT_CLASS_TYPE(type) static EventType GetStaticType() { return EventType::##type; }\ virtual EventType GetEventType() const override { return GetStaticType(); }\ virtual const char* GetName() const override { return #type; } #define EVENT_CLASS_CATEGORY(category) virtual int GetCategoryFlags() const override { return category; } // base class for events class PRACTION_API Event { public: // stores if the event has been already handled bool Handled = false; // event type, name and flags get functions virtual EventType GetEventType() const = 0; virtual const char* GetName() const = 0; virtual int GetCategoryFlags() const = 0; // returns the name of the event (for debugging) virtual std::string ToString() const { return GetName(); } // function to check if the event in in a particular category inline bool IsInCategory(EventCategory category) { return GetCategoryFlags() & category; } }; // Dispatcher recieves a reference to an event (Event& event) // We can then call a differnt event function (EventFn<T> func) for each event class EventDispatcher { template<typename T> using EventFn = std::function<bool(T&)>; public: EventDispatcher(Event& event) : m_Event(event) { } template<typename T> bool Dispatch(EventFn<T> func) { // checks if the event matches with the dispatch arguement if (m_Event.GetEventType() == T::GetStaticType()) { m_Event.Handled = func(*(T*)&m_Event); return true; } return false; } private: Event& m_Event; }; inline std::ostream& operator<<(std::ostream& os, const Event& e) { return os << e.ToString(); } }<file_sep>#include <Praction.h> // Example on how to impliment the praction layer class class ExampleLayer : public Praction::Layer { public: ExampleLayer() : Layer("Example") { } void OnUpdate() override { PT_INFO("ExampleLayer::Update"); } void OnEvent(Praction::Event& event) override { PT_TRACE("{0}", event); } }; // creates a class that inherits from game engines's application class class Sandbox : public Praction::Application { public: Sandbox() { // example of how to contruct and add a layer to the layer stack. PushLayer(new ExampleLayer()); // ImGui layer i.e. debug menu PushOverlay(new Praction::ImGuiLayer()); } ~Sandbox() { } }; // CreateApplication allows Sandbox to create a new game engine application object Praction::Application* Praction::CreateApplication() { return new Sandbox(); }<file_sep>Windows Events Windows generates events (mouse, resize window, keyboard clicks). We so far we have created an event system and a window system. We need to link them. Whenever the window system creates a event, we need our event system to get it and handle it. We need a close button. The close button is needed to terminate the program. <file_sep>Precompiled headers allow headers that are used often to be precompiled so they don't have to be compiled again whenever a change is made to the source files. When compile times get very long, it is important to use precompiled headers. Precompiled headers can hide the dependencies of a file. This can hurt the modularity of a file if the dependancies are immediately shown. <file_sep>#pragma once // defining the windows platform library's exporting and importing function #ifdef PT_PLATFORM_WINDOWS #ifdef PT_BUILD_DLL #define PRACTION_API __declspec(dllexport) #else #define PRACTION_API __declspec(dllimport) #endif #else #error Praction only supports Windows! #endif #ifdef PT_DEBUG #define PT_ENABLE_ASSETS #endif // PT_ENABLE_ASSERTS checkes if the program is in debug or release, then adds or removes assert statements accordingly #ifdef PT_ENABLE_ASSERTS // ASSERTS checks a certain condition then inserts a breakpoint (windows only at the moment) #define PT_ASSERT(x, ...) { if(!(x)) { PT_EROOR("Assertion Failed: {0}", __VA_ARGS__); __debugbreak(); } } #define PT_CORE_ASSERT(x, ...) { if(!(x)) { PT_CORE_ERROR("Assertion Failed: {0}", __VA__ARGS__); __debugbreak(); } } #else #define PT_ASSERT(x, ...) #define PT_CORE_ASSERT(x, ...) #endif // BIT(x) is shift 1 to x place i.e. BIT(2) is 100 // This is to allow events to belong to multiple categories. #define BIT(x) (1 << x) #define PT_BIND_EVENT_FN(fn) std::bind(&fn, this, std::placeholders::_1));<file_sep>Layers Layers are an ordered stack and determine things are drawn. They also handle update logic. Overlays are rendered last. Events travel from the top most layer to bottom. Meaning when a button is on top of the picture, we want to allow the player to click the button and be handled on top of the graphics. <file_sep>[Window][Debug##Default] Pos=60,60 Size=400,400 Collapsed=0 [Window][ImGui Demo] Pos=413,46 Size=550,522 Collapsed=0 [Window][Example: Console] Pos=60,60 Size=520,600 Collapsed=0 [Window][Example: Log] Pos=244,39 Size=500,400 Collapsed=0 <file_sep># What is a Game Engine? Reference: https://thecherno.com/engine ## Game engine: * concept * pros and cons * plans to cover which features ## Game engine concept * broad definition * help build games quickly * suite of tools to help content creators to make models * commercialized engines (unity, unreal) * level editor * big tool * platform for building an application * game companies (EA, Ubisoft, Activision Blizzard, Value) * Unreleased game engine * Platform to construct that an visual application * doesn't have to be a game * unreal, unity * VR applications * Architectural visualizations * Simulations * Interactions * Game engine: an interactive visual data-oriented application ## Assets * The game engine manages data by storing it in files called assets * Game engines are optimized to generate these assets * Artwork, models and other data formats must be converted into asset for the game engine to use * png image * obj models * levels * etc ## Game Production Pipeline 1. Content creator creates art 2. the game engine is used to convert art into an asset 3. the game engine reads assets at run time 4. the game engine outputs visual and receives input from user 5. user can then interact with game engine ## Data transformation to assets We need a number of various systems: * platform extraction layers * Generalizes code away from platform specific implementation * desktop (windows, mac, linux) * mobile (iOS, android) * console (Xbox, Playstation, Nintendo) * run time transformations * rendering * audio * file input/output * serialization/parser * translating data into or out of marked languages * tools * level editor * scripting ## Next Planning Lessons * planned game engine features * plans on making each game engine feature
e610a5ba15f09c8c144720c66002d6c625fa0b80
[ "Lua", "Markdown", "INI", "C", "C++" ]
28
Markdown
nessarus/Praction
df753facc1ae48e3bbe8d284e5a6147a5daea525
80d1264f9604eb18d7f2f49bc9a03625d8b7df1c
refs/heads/master
<repo_name>hoist/hoist-connector-quickbooks-online<file_sep>/samples/endpoints/invoice.js /* Just copy and paste this snippet into your code */ /* create an invoice */ module.exports = function (req, res, done) { var invoice = { "Line": [{ "Amount": 100.00, "DetailType": "SalesItemLineDetail", "SalesItemLineDetail": { "ItemRef": { "value": "1", "name": "Services" } } }], "CustomerRef": { "value": "21" } }; var QBO = Hoist.connector("<key>"); //create an invoices return QBO.create('/invoice', invoice) .then(function (response) { Hoist.log('invoice posted', response); }).then(function () { done(); }); }; /* update an invoice */ module.exports = function (req, res, done) { var invoice = { "Id": 33, "SyncToken": 0, "Line": [{ "Amount": 100.00, "DetailType": "SalesItemLineDetail", "SalesItemLineDetail": { "ItemRef": { "value": "1", "name": "Services" } } }], "CustomerRef": { "value": "21" } }; var QBO = Hoist.connector("<key>"); //update the invoices return QBO.update('/invoice', invoice) .then(function (response) { Hoist.log('invoice posted', response); }).then(function () { done(); }); }; /* get an invoice */ module.exports = function (req, res, done) { var QBO = Hoist.connector("<key>"); //get the invoices return QBO.get('/invoice/33') .then(function (response) { Hoist.log('invoice retrieved', response); }).then(function () { done(); }); }; /* delete an invoice */ module.exports = function (req, res, done) { var invoice = { "Id": 33, "SyncToken": 0 }; var QBO = Hoist.connector("<key>"); //delete the invoices return QBO.delete('/invoice', invoice) .then(function (response) { Hoist.log('invoice posted', response); }).then(function () { done(); }); }; <file_sep>/src/poll.js 'use strict'; var moment = require('moment'); var QBOConnector = require('./connector'); var BBPromise = require('bluebird'); var _ = require('lodash'); function QBOPoller(context) { this.logger = require('@hoist/logger').child({ cls: 'QBOPoller', subscription: context.subscription._id, application: context.application._id }); this.logger.alert = require('@hoist/logger').alert; this.logger.info('setting up connector'); this.context = context; this.context.settings.applicationId = context.application._id; this.connector = new QBOConnector(context.settings); } QBOPoller.prototype.poll = function () { return BBPromise.try(function buildPollCalls() { this.logger.info('starting poll'); this.pollStart = moment().utc(); this.lastPolled = this.context.subscription.get('lastPolled'); if ((!this.context.subscription.endpoints) || this.context.subscription.endpoints.length < 1) { this.logger.warn('no endpoints to poll!'); return []; } var sortedEndpoints = _.map(this.context.subscription.endpoints, _.bind(function (endpoint) { var mappedEndpoint = { endpointName: endpoint }; var endpointMeta = this.context.subscription.get(endpoint); endpointMeta = endpointMeta || {}; mappedEndpoint.endpointMeta = endpointMeta; if (!endpointMeta.lastPolled) { mappedEndpoint.pollType = 'new'; } else { mappedEndpoint.pollType = 'update'; } return mappedEndpoint; }, this)); //we've polled this endpoint before so we can use cdc this.logger.info({ endpoints: sortedEndpoints }, 'sorted endpoints'); var updateEndpoints = _.filter(sortedEndpoints, function (endpoint) { return endpoint.pollType === 'update'; }); //we've not polled this endpoint before var newEndpoints = _.filter(sortedEndpoints, function (endpoint) { return endpoint.pollType === 'new'; }); this.logger.info({ newEndpoints: newEndpoints, updateEndpoints: updateEndpoints }, 'polling endpoints'); return _.map(newEndpoints, _.bind(function (newEndpoint) { return this.pollNewEndpoint(newEndpoint); }, this)).concat(this.pollForUpdates(updateEndpoints)); }, [], this) .bind(this) .then(function (polls) { this.logger.info('waiting for all polls to finish'); return BBPromise.settle(polls); }) .then(function () { _.forEach(this.context.subscription.endpoints, _.bind(function (endpoint) { var endpointMeta = this.context.subscription.get(endpoint); if (!endpointMeta) { this.context.subscription.set(endpoint, (endpointMeta = {})); } endpointMeta.lastPolled = moment().utc().format(); }, this)); this.context.subscription.delayTill(moment().utc().add(30, 'seconds').toDate()); this.logger.info('setting last polled date'); this.context.subscription.set('lastPolled', this.pollStart.format()); }); }; QBOPoller.prototype.pollForUpdates = function (endpoints) { return BBPromise.try(function () { var entityList = _.map(endpoints, 'endpointName').join(','); this.logger.info({ endpoints: endpoints, entityList: entityList }, 'calling cdc'); return this.connector.get('/cdc?entities=' + entityList + '&changedSince=' + moment(this.lastPolled).toISOString()) .bind(this) .then(function (response) { return this.flattenCDCResponse(_.map(endpoints, 'endpointName'), response); }).then(function (flattenedCDCResponse) { return _.filter(_.map(_.map(endpoints, 'endpointName'), _.bind(function (endpoint) { if (flattenedCDCResponse[endpoint]) { return this.processEntities(endpoint, flattenedCDCResponse[endpoint]); } }, this))); }); }, [], this); }; QBOPoller.prototype.pollNewEndpoint = function (endpoint) { this.logger.info({ endpoint: endpoint }, 'polling endpoint'); return this.connector.get('/query?select * from ' + endpoint.endpointName) .bind(this) .then(function (response) { this.logger.info({ endpoint: endpoint }, 'got response, processing'); return this.processEntities(endpoint.endpointName, response.QueryResponse[endpoint.endpointName]); }); }; QBOPoller.prototype.processEntities = function (endpointName, entities) { this.logger.info({ endpoint: endpointName }, 'processing entities'); return BBPromise.all(_.map(entities, _.bind(function (entity) { this.logger.info({ endpoint: endpointName }, 'processing entity'); return this.processEntity(endpointName, entity); }, this))).catch(function (err) { this.logger.error(err); }); }; QBOPoller.prototype.processEntity = function (endpointName, entity) { return BBPromise.try(function () { this.logger.info({ entity: entity.Id }, 'setting entity status'); return this.setStatus(endpointName, entity); }, [], this).bind(this).then(function () { this.logger.info({ endpointName: endpointName }, 'raising event'); return this.raiseEvent(endpointName, entity); }).catch(function (err) { this.logger.error(err); this.logger.alert(err); }); }; QBOPoller.prototype.raiseEvent = function (endpoint, entity) { return BBPromise.try(function () { var eventName = (this.context.connectorKey + ":" + entity.status + ":" + endpoint).toLowerCase(); this.logger.info({ eventName: eventName, }, 'raising event'); return this.emit(eventName, entity); }, [], this); }; QBOPoller.prototype.setStatus = function (endpoint, entity) { if (entity.status) { //deleted this.logger.info('using deleted status'); return entity; } else { var endpointMeta = this.context.subscription.get(endpoint); var newStatus = 'new'; if (!endpointMeta) { newStatus = 'modified'; this.context.subscription.set(endpoint, (endpointMeta = {})); } if (!endpointMeta.ids) { endpointMeta.ids = []; } if (endpointMeta.ids.indexOf(entity.Id) < 0) { endpointMeta.ids.push(entity.Id); this.logger.info('setting status to ', newStatus); entity.status = newStatus; } else { this.logger.info('setting status to modified'); entity.status = 'modified'; } } }; QBOPoller.prototype.flattenCDCResponse = function (endpoints, response) { return BBPromise.try(function () { var result = {}; _.forEach(endpoints, function (endpoint) { result[endpoint] = []; }); _.forEach(response.CDCResponse, function (response) { return _.forEach(response.QueryResponse, function (queryResponse) { return _.forEach(endpoints, function (endpoint) { var entities = queryResponse[endpoint]; if (entities) { result[endpoint] = result[endpoint].concat(entities); } }); }); }); return result; }); }; module.exports = function (context, raiseCallback) { var poller = new QBOPoller(context); poller.emit = raiseCallback; return poller.poll(); }; module.exports._poller = QBOPoller; <file_sep>/samples/getting-started.js /* Just copy and paste this snippet into your code */ module.exports = function (req, res, done) { var QBO = Hoist.connector("<key>"); return QBO.get('/CompanyInfo/<CompanyId>') .then(function (CompanyInfo) { return Hoist.event.raise('COMPANYINFO:FOUND', CompanyInfo); }).then(function () { done(); }); }; <file_sep>/samples/endpoints/creditMemo.js /* Just copy and paste this snippet into your code */ /* create a credit memo */ module.exports = function (req, res, done) { var creditMemo = { "Line": [{ "Amount": 50, "DetailType": "SalesItemLineDetail", "SalesItemLineDetail": { "ItemRef": { "value": "3", "name": "Concrete" } } }], "CustomerRef": { "value": "3", "name": "CoolCars" } }; var QBO = Hoist.connector("<key>"); //create a credit memo, return QBO.create('/creditmemo', creditMemo) .then(function (response) { Hoist.log('credit memo posted', response); }).then(function () { done(); }); }; /* update an credit memo */ module.exports = function (req, res, done) { var creditMemo = { "Id": 33, "SyncToken": 0, "Line": [{ "Amount": 50, "DetailType": "SalesItemLineDetail", "SalesItemLineDetail": { "ItemRef": { "value": "3", "name": "Concrete" } } }], "CustomerRef": { "value": "3", "name": "CoolCars" } }; var QBO = Hoist.connector("<key>"); //update the credit memo return QBO.update('/creditmemo', creditMemo) .then(function (response) { Hoist.log('credit memo posted', response); }).then(function () { done(); }); }; /* get a credit memo */ module.exports = function (req, res, done) { var QBO = Hoist.connector("<key>"); //get the credit memom return QBO.get('/creditmemo/33') .then(function (response) { Hoist.log('credit memo retrieved', response); }).then(function () { done(); }); }; /* delete a credit memo */ module.exports = function (req, res, done) { var creditMemo = { "Id": 33, "SyncToken": 0 }; var QBO = Hoist.connector("<key>"); //delete the credit memo return QBO.delete('/creditmemo', creditMemo) .then(function (response) { Hoist.log('credit memo deleted', response); }).then(function () { done(); }); }; <file_sep>/tests_old/unit_tests/bounce_tests.js 'use strict'; var QBOConnector = require('../../lib/connector'); var sinon = require('sinon'); var OAuth = require('@hoist/oauth').OAuth; var expect = require('chai').expect; var BBPromise = require('bluebird'); describe('QBO Connector', function () { describe('Public app', function () { describe('#receiveBounce', function () { describe('get initial bounce', function () { var mockBounce = { query: { quickbooks: true, payments: true }, get: sinon.stub(), set: sinon.stub().returns(BBPromise.resolve(null)), redirect: sinon.stub(), done: sinon.stub() }; before(function () { sinon.stub(OAuth.prototype, 'getOAuthRequestToken').yields(null, 'token', 'token_secret'); var connector = new QBOConnector({}); connector.receiveBounce(mockBounce); }); after(function () { OAuth.prototype.getOAuthRequestToken.restore(); }); it('redirects to QBO', function () { expect(mockBounce.redirect) .to.have.been .calledWith('https://appcenter.intuit.com/Connect/SessionStart?grantUrl=https%3A%2F%2Fbouncer.hoist.io%2Fbounce&datasources=quckbooks%2Cpayments'); }); it('saves setup flag', function () { expect(mockBounce.set) .to.have.been.calledWith('IntuitSetup', true); }); }); describe('get request token bounce', function () { var mockBounce = { get: sinon.stub(), set: sinon.stub().returns(BBPromise.resolve(null)), redirect: sinon.stub(), done: sinon.stub() }; before(function () { mockBounce.get.withArgs('IntuitSetup').returns(true); sinon.stub(OAuth.prototype, 'getOAuthRequestToken').yields(null, 'token', 'token_secret'); var connector = new QBOConnector({ }); connector.receiveBounce(mockBounce); }); after(function () { OAuth.prototype.getOAuthRequestToken.restore(); }); it('redirects to QBO', function () { expect(mockBounce.redirect) .to.have.been .calledWith('https://appcenter.intuit.com/Connect/Begin?oauth_token=token'); }); it('saves request token', function () { expect(mockBounce.set) .to.have.been.calledWith('RequestToken', 'token'); }); it('saves request token secret', function () { expect(mockBounce.set) .to.have.been.calledWith('RequestTokenSecret', 'token_secret'); }); }); describe('on return from QBO', function () { var mockBounce = { get: sinon.stub(), set: sinon.stub().returns(BBPromise.resolve(null)), query: { /* jshint camelcase:false */ oauth_verifier: 'oauth_verifier_value', realmId: 'realmId' }, redirect: sinon.stub(), done: sinon.stub(), delete: sinon.stub().returns(BBPromise.resolve(null)) }; before(function () { mockBounce.get.withArgs('RequestToken').returns('request_token'); mockBounce.get.withArgs('RequestTokenSecret').returns('request_token_secret'); sinon.stub(OAuth.prototype, 'getOAuthAccessToken').yields(null, 'token', 'token_secret'); var connector = new QBOConnector({}); connector.receiveBounce(mockBounce); }); after(function () { OAuth.prototype.getOAuthAccessToken.restore(); }); it('redirects back to app', function () { return expect(mockBounce.done) .to.have.been .called; }); it('sends correct params to get access token', function () { expect(OAuth.prototype.getOAuthAccessToken) .to.have.been.calledWith('request_token', 'request_token_secret', 'oauth_verifier_value'); }); it('saves companyId', function () { expect(mockBounce.set) .to.have.been.calledWith('CompanyId', 'realmId'); }); it('saves access token', function () { expect(mockBounce.set) .to.have.been.calledWith('AccessToken', 'token'); }); it('saves access token secret', function () { expect(mockBounce.set) .to.have.been.calledWith('AccessTokenSecret', 'token_secret'); }); }); }); }); }); <file_sep>/samples/endpoints/payment.js /* Just copy and paste this snippet into your code */ /* create a payment */ module.exports = function (req, res, done) { var payment = { "CustomerRef": { "value": "20", "name": "<NAME>" }, "TotalAmt": 55.00, "Line": [{ "Amount": 55.00, "LinkedTxn": [{ "TxnId": "69", "TxnType": "Invoice" }] }] }; var QBO = Hoist.connector("<key>"); //create a payment, return QBO.create('/payment', payment) .then(function (response) { Hoist.log('payment posted', response); }).then(function () { done(); }); }; /* update an payment */ module.exports = function (req, res, done) { var payment = { "CustomerRef": { "value": "16" }, "PaymentMethodRef": { "value": "16" }, "PaymentRefNum": "123456", "sparse": false, "Id": "69", "SyncToken": "0", "MetaData": { "CreateTime": "2013-03-13T14:49:21-07:00", "LastUpdatedTime": "2013-03-13T14:49:21-07:00" }, "Line": [{ "Amount": 300, "LinkedTxn": [{ "TxnId": "67", "TxnType": "Invoice" }] }, { "Amount": 300, "LinkedTxn": [{ "TxnId": "68", "TxnType": "CreditMemo" }] }] }; var QBO = Hoist.connector("<key>"); //update the payment return QBO.update('/payment', payment) .then(function (response) { Hoist.log('payment posted', response); }).then(function () { done(); }); }; /* get a payment */ module.exports = function (req, res, done) { var QBO = Hoist.connector("<key>"); //get the paymentm return QBO.get('/payment/69') .then(function (response) { Hoist.log('payment retrieved', response); }).then(function () { done(); }); }; /* delete a payment */ module.exports = function (req, res, done) { var payment = { "Id": 33, "SyncToken": 0 }; var QBO = Hoist.connector("<key>"); //delete the payment return QBO.delete('/payment', payment) .then(function (response) { Hoist.log('payment deleted', response); }).then(function () { done(); }); }; <file_sep>/README.md # hoist-connector-quickbooks-online A connector to Quickbooks Online <file_sep>/tests_old/integration/get_company_info_tests.js 'use strict'; require('../bootstrap'); var QBOConnector = require('../../lib/connector'); var config = require('config'); var expect = require('chai').expect; describe.skip('get company info', function () { this.timeout(50000); describe('valid connection to get /companyinfo', function () { var response; before(function () { var connector = new QBOConnector({ consumerKey: config.get('consumerKey'), consumerSecret: config.get('consumerSecret'), isSandbox: true }); var settings = { AccessToken: config.get('AccessToken'), AccessTokenSecret: config.get('AccessTokenSecret'), CompanyId: config.get('CompanyId') }; connector.authorize({ get: function (key) { return settings[key]; } }); response = connector.get('/companyinfo/'+config.get('CompanyId')); }); it('returns expected json', function () { return response.then(function (json) { return expect(json.CompanyInfo.CompanyName).to.eql(config.get('Company Name')); }); }); }); }); <file_sep>/tests_old/integration/poll_tests.js 'use strict'; require('../bootstrap'); var poll = require('../../lib/poll'); var model = require('@hoist/model'); var ConnectorSetting = model.ConnectorSetting; var BouncerToken = model.BouncerToken; var Application = model.Application; var sinon = require('sinon'); describe.skip('polling', function () { describe('given no previous polls', function () { var subscription; before(function () { var subscriptionSettings = { }; subscription = { get: function (key) { return subscriptionSettings[key]; }, eventEmitter: { emit: sinon.stub() } }; var connector = new ConnectorSetting({ }); var bouncerToken = new BouncerToken(); var app = new Application(); poll(app, subscription, connector, bouncerToken); }); it('raises NEW:INVOICE events', function () { }); }); }); <file_sep>/CONTRIBUTING.md # How to contribute We want to keep it as easy as possible to contribute and updates to Hoist Connect. There are a few guidelines that we need contributors to follow so that we can have a chance of keeping on top of things. ## Getting Started * Make sure you have a [GitHub account](https://github.com/signup/free) * Fork the repository on GitHub ## Making Changes * Create a topic branch from where you want to base your work. * This is usually the master branch. * Only target release branches if you are certain your fix must be on that branch. * To quickly create a topic branch based on master; `git checkout -b feature/my_contribution master`. Please avoid working directly on the `master` branch. * branch names should follow a naming convention of bug/<issuenumber> or feature/<name> * Ensure you follow the [style guide](https://github.com/hoist/javascript) for any changes * Make commits of logical units. * Check for unnecessary whitespace with `git diff --check` before committing. * Make sure your commit messages are in the proper format. * Make sure you have added or modified at least one tests for your changes. * Run _all_ the tests to assure nothing else was accidentally broken. ## Submitting Changes * Push your changes to a topic branch in your fork of the repository. * Submit a pull request to the repository in the hoist organisation # Additional Resources * [Hoist JavaScript Style Guide](https://github.com/hoist/javascript) * [General GitHub documentation](http://help.github.com/) * [GitHub pull request documentation](http://help.github.com/send-pull-requests/)
b8f547c0febea00f37bd05b439d3aaadb51cfebf
[ "JavaScript", "Markdown" ]
10
JavaScript
hoist/hoist-connector-quickbooks-online
383ecc745f20c6808514f1d187e87f624b4dbd8d
a8d4ad03f7bd784fe375176bbdb6479efc36fa10
refs/heads/master
<file_sep>"use strict"; var paths = {}; var root = "~/.droppy"; var path = require("path"); var untildify = require("untildify"); paths.get = function get() { return { home : resolve(root), pid : resolve(root, "droppy.pid"), files : resolve(root, "files"), temp : resolve(root, "temp"), cache : resolve(root, "cache"), cfg : resolve(root, "config"), cfgFile : resolve(root, "config", "config.json"), db : resolve(root, "config", "db.json"), tlsKey : resolve(root, "config", "tls.key"), tlsCert : resolve(root, "config", "tls.cert"), tlsCA : resolve(root, "config", "tls.ca"), mod : resolve(__dirname, ".."), server : resolve(__dirname, "..", "server"), client : resolve(__dirname, "..", "client"), templates : resolve(__dirname, "..", "client", "templates"), svg : resolve(__dirname, "..", "client", "svg") }; }; paths.seed = function seed(home) { root = home; }; module.exports = paths; function resolve() { var p = path.join.apply(null, arguments); return path.resolve(/^~/.test(p) ? untildify(p) : p); } <file_sep>"use strict"; module.exports = function droppy(home, options) { if (arguments.length === 1) { options = home; home = undefined; } if (!options) { options = {}; } if (typeof home === "string") { require("./server/paths.js").seed(home); } var server = require("./server/server.js"); server(options, false, function (err) { if (err) throw err; }); return server._onRequest; };
9916fdecad5ba6f86de4810aea60666ae9bcdf5a
[ "JavaScript" ]
2
JavaScript
2cats/droppy
c3d2ff9cfec73eff501a80be830dcd71a35e10b4
77e7d28a9825bcb76c0e44aa6452ec45f0b19a10
refs/heads/master
<file_sep>import React, { useState } from 'react'; import Header from './Header'; import FormPart from './FormPart'; import Display from './Display'; export default function App() { const [addData, setData] = useState([]); // Reverse Props Receive const NotesSubmit = (formInput) => { // console.log('me', formInput); setData((preData) => { return [...preData, formInput]; }); }; const NotesDelete = (id) => { // Reverse Props Receive setData((preDatas) => { // console.log(id); return preDatas.filter((Element, index) => { return index !== id; }); }); }; return ( <> <Header /> <FormPart passNote={NotesSubmit} /> <div className="container"> <div className="row"> {addData.map((data, index) => { return ( <Display key={index} id={index} {...data} deleteNote={NotesDelete} /> ); })} </div> </div> </> ); }
043dd09dc90d1a3530ec90b76587b9ec556be284
[ "JavaScript" ]
1
JavaScript
rajrachchh14/react-notes-app
edf95633f1cbd5c34367344da24b39c92daddbf5
887d2f98a1d92f8a07008d140af8639e05258498
refs/heads/master
<repo_name>xRigel/cityTalk<file_sep>/User.java package edu.temple.citytalk; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Created by Rigel on 3/22/2017. */ public class User { public String name = "default"; public int id; public static String generateName(){ String retval = ""; List<String> adjectives = new ArrayList<String>(); List<String> animals = new ArrayList<String>(); adjectives.add("Big"); adjectives.add("Small"); adjectives.add("Stinky"); adjectives.add("Fat"); adjectives.add("Blue"); adjectives.add("Red"); adjectives.add("Green"); adjectives.add("Thick"); adjectives.add("Thin"); adjectives.add("Weird"); adjectives.add("Funny"); adjectives.add("Cool"); adjectives.add("Pretty"); animals.add("Dog"); animals.add("Cat"); animals.add("Fish"); animals.add("Bear"); animals.add("Moose"); Random random = new Random(); int value = random.nextInt(13); retval += adjectives.get(value); value = random.nextInt(13); retval += adjectives.get(value); value = random.nextInt(5); retval += animals.get(value); return retval; } public void setName(String name){ this.name = name; } }
dd163f6432732c7e73795fa002f4df49b145707a
[ "Java" ]
1
Java
xRigel/cityTalk
0301a6b911439e64f35540bd5ac13fc019e23b1b
cecd2470eebde8ccfbd886a496df3de30b13f0ff
refs/heads/master
<repo_name>ProjectAwesomeRSA/WARD<file_sep>/src/app/footer/footer.component.ts import { Component, OnInit } from '@angular/core'; import { GetWorldFactorsService } from '../_services/getWorldFactors.service'; import { interval } from 'rxjs'; import { timeInterval } from 'rxjs/operators'; @Component({ selector: 'app-footer', templateUrl: './footer.component.html', styleUrls: ['./footer.component.css'] }) export class FooterComponent implements OnInit { constructor(protected getWorldFactors: GetWorldFactorsService) { } ngOnInit() { this.getWorldFactors.getWorldFactorData(); const counter = interval(240000); counter.subscribe(() => this.getWorldFactors.getWorldFactorData()); } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { RouterModule } from '@angular/router'; import { JwtModule } from '@auth0/angular-jwt'; import { AppComponent } from './app.component'; import { CharacterComponent } from './character/character.component'; import { AssetManagerComponent } from './asset-manager/asset-manager.component'; import { AssetItemComponent } from './asset-item/asset-item.component'; import { FooterComponent } from './footer/footer.component'; import { HeaderComponent } from './header/header.component'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { ModalComponent } from './modal/modal.component'; import { ModalLoginComponent } from './modal-login/modal-login.component'; import { LoginComponent } from './login/login.component'; import { RegisterComponent } from './register/register.component'; import { ModalRegisterComponent } from './modal-register/modal-register.component'; import { AuthService } from './_services/auth.service'; import { GetCharacterService } from './_services/getCharacter.service'; import { GetOrdinalNumberService } from './_services/getOrdinalNumber.service'; import { HomeComponent } from './home/home.component'; import { LoginService } from './_services/login.service'; import { CompareValidatorDirective } from './_directives/compare-validator.directive'; import { GetWorldFactorsService } from './_services/getWorldFactors.service'; import { appRoutes } from './routes'; import { AuthGuard } from './_guards/auth.guard'; import { ActionsComponent } from './actions/actions.component'; import { MarketComponent } from './market/market.component'; import { GetActionsService } from './_services/getActions.service'; import { QuestActionResolver } from './_resolvers/questAction.resolver'; import { TaskActionResolver } from './_resolvers/taskAction.resolver'; export function tokenGetter() { return localStorage.getItem('token'); } @NgModule({ declarations: [ AppComponent, CharacterComponent, AssetManagerComponent, AssetItemComponent, FooterComponent, HeaderComponent, ModalComponent, ModalLoginComponent, LoginComponent, RegisterComponent, ModalRegisterComponent, HomeComponent, CompareValidatorDirective, ActionsComponent, MarketComponent, ], imports: [ BrowserModule, FormsModule, NgbModule, RouterModule.forRoot(appRoutes), HttpClientModule, JwtModule.forRoot({ config: { tokenGetter, whitelistedDomains: ['localhost:5000'], blacklistedRoutes: ['localhost:5000/api/auth'] } }) ], providers: [ AuthService, GetCharacterService, GetOrdinalNumberService, LoginService, GetWorldFactorsService, AuthGuard, GetActionsService, QuestActionResolver, TaskActionResolver ], bootstrap: [AppComponent], entryComponents: [ ModalLoginComponent, ModalRegisterComponent ] }) export class AppModule { } <file_sep>/src/app/_models/questAction.ts export interface QuestAction { id: number; duration: number; expGain: number; reward: string; taskTitle: string; taskDescription: string; } <file_sep>/src/app/_services/getOrdinalNumber.service.spec.ts /* tslint:disable:no-unused-variable */ import { TestBed, async, inject } from '@angular/core/testing'; import { GetOrdinalNumberService } from './getOrdinalNumber.service'; describe('Service: GetOrdinalNumber', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [GetOrdinalNumberService] }); }); it('should ...', inject([GetOrdinalNumberService], (service: GetOrdinalNumberService) => { expect(service).toBeTruthy(); })); }); <file_sep>/src/app/_services/getWorldFactors.service.spec.ts /* tslint:disable:no-unused-variable */ import { TestBed, async, inject } from '@angular/core/testing'; import { GetWorldFactorsService } from './getWorldFactors.service'; describe('Service: GetWorldFactors', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [GetWorldFactorsService] }); }); it('should ...', inject([GetWorldFactorsService], (service: GetWorldFactorsService) => { expect(service).toBeTruthy(); })); }); <file_sep>/src/app/_services/getWorldFactors.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class GetWorldFactorsService { serverTime: string; currentYear: number; season: number; currentMonth: number; currentDay: number; factors: any = null; constructor(private http: HttpClient) { } getWorldFactorData() { this.http.get('http://localhost:5000/api/time').subscribe(response => { this.factors = response; this.updateFactors(); }, error => { console.log(error); }); } updateFactors() { if (this.factors != null) { this.serverTime = this.factors.serverTime; this.currentYear = this.factors.currentYear; this.season = this.factors.season; this.currentMonth = this.factors.currentMonth; this.currentDay = this.factors.currentDay; } } } <file_sep>/src/app/modal-register/modal-register.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-modal-register', template: ` <app-modal title="Register"> <app-register></app-register> </app-modal>`, styleUrls: ['./modal-register.component.css'] }) export class ModalRegisterComponent implements OnInit { constructor() { } ngOnInit() { } } <file_sep>/src/app/modal-login/modal-login.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-modal-login', template: ` <app-modal title="Login"> <app-login></app-login> </app-modal>`, styleUrls: ['./modal-login.component.css'] }) export class ModalLoginComponent implements OnInit { constructor() { } ngOnInit() { } } <file_sep>/src/app/_services/getOrdinalNumber.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class GetOrdinalNumberService { constructor() { } convert(value: number) { let lastDigits: number = parseInt(value.toString().slice(-2) , 10); let ordinal: string; if (lastDigits < 14 && lastDigits > 10) { return value + 'th'; } lastDigits = lastDigits % 10; switch (lastDigits) { case 1: { return ordinal = value + 'st'; } case 2: { return ordinal = value + 'nd'; } case 3: { return ordinal = value + 'rd'; } default: { return ordinal = value + 'th'; } } } } <file_sep>/src/app/_resolvers/taskAction.resolver.ts import { Injectable } from '@angular/core'; import { Resolve, Router, ActivatedRouteSnapshot } from '@angular/router'; import { TaskAction } from '../_models/taskAction'; import { GetActionsService } from '../_services/getActions.service'; import { Observable, of } from 'rxjs'; import { catchError } from 'rxjs/operators'; @Injectable() export class TaskActionResolver implements Resolve<TaskAction> { constructor(private getActionService: GetActionsService, private router: Router) {} resolve(route: ActivatedRouteSnapshot): Observable<TaskAction> { return this.getActionService.getTasks().pipe( catchError(error => { console.log(error); this.router.navigate(['/home']); return of(null); }) ); } } <file_sep>/src/app/actions/actions.component.ts import { Component, OnInit } from '@angular/core'; import { GetActionsService } from '../_services/getActions.service'; import { QuestAction } from '../_models/questAction'; import { ActivatedRoute } from '@angular/router'; import { TaskAction } from '../_models/taskAction'; @Component({ selector: 'app-actions', templateUrl: './actions.component.html', styleUrls: ['./actions.component.css'] }) export class ActionsComponent implements OnInit { taskActions: TaskAction[]; questActions: QuestAction[]; constructor(private getActionsService: GetActionsService, private route: ActivatedRoute) { } ngOnInit() { this.route.data.subscribe(data => { this.questActions = data.questActions; this.taskActions = data.taskActions; }); } doTask(taskId: number) { console.log(this.getActionsService.doTask(taskId)); } doQuest(questId: number) { console.log(this.getActionsService.doQuest(questId)); } } <file_sep>/src/app/character/character.component.ts import { Component, OnInit } from '@angular/core'; import { GetCharacterService } from '../_services/getCharacter.service'; @Component({ selector: 'app-character', templateUrl: './character.component.html', styleUrls: ['./character.component.css'] }) export class CharacterComponent implements OnInit { constructor(protected getCharacter: GetCharacterService) { } ngOnInit() { } } <file_sep>/src/app/_services/login.service.ts import { Injectable } from '@angular/core'; import { AuthService } from '../_services/auth.service'; import { Router } from '@angular/router'; import { GetCharacterService } from '../_services/getCharacter.service'; @Injectable({ providedIn: 'root' }) export class LoginService { constructor(private authService: AuthService, private router: Router, protected getCharacter: GetCharacterService) { } login(model: any = {}) { this.authService.login(model).subscribe(next => { console.log('Logged in successfully'); }, error => { console.log(error); }, () => { this.getCharacter.getCharacterInfo(); this.router.navigate(['/character']); }); } } <file_sep>/src/app/_models/taskAction.ts export interface TaskAction { id: number; staminaCost: number; monetaryReward: number; expGain: number; taskTitle: string; taskDescription: string; } <file_sep>/src/app/routes.ts import { Routes } from '@angular/router'; import { CharacterComponent } from './character/character.component'; import { AssetManagerComponent } from './asset-manager/asset-manager.component'; import { HomeComponent } from './home/home.component'; import { AuthGuard } from './_guards/auth.guard'; import { ActionsComponent } from './actions/actions.component'; import { MarketComponent } from './market/market.component'; import { QuestActionResolver } from './_resolvers/questAction.resolver'; import { TaskActionResolver } from './_resolvers/taskAction.resolver'; export const appRoutes: Routes = [ { path: '', component: HomeComponent }, { path: '', runGuardsAndResolvers: 'always', canActivate: [AuthGuard], children: [ { path: 'character', component: CharacterComponent }, { path: 'assets', component: AssetManagerComponent}, { path: 'actions', component: ActionsComponent, resolve: { questActions: QuestActionResolver, taskActions: TaskActionResolver }}, { path: 'market', component: MarketComponent }, ] }, { path: '**', redirectTo: '', pathMatch: 'full' }, ]; <file_sep>/src/app/header/header.component.ts import { Component, OnInit } from '@angular/core'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { ModalLoginComponent } from '../modal-login/modal-login.component'; import { ModalRegisterComponent } from '../modal-register/modal-register.component'; import { GetCharacterService } from '../_services/getCharacter.service'; import { AuthService } from '../_services/auth.service'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.css'] }) export class HeaderComponent implements OnInit { navbarOpen = false; toggleNavbar() { this.navbarOpen = !this.navbarOpen; } constructor(private modalService: NgbModal, protected getCharacter: GetCharacterService, private authService: AuthService) {} openLogin() { const modalRef = this.modalService.open(ModalLoginComponent); modalRef.componentInstance.title = 'Login'; } openRegister() { const modalRef = this.modalService.open(ModalRegisterComponent); modalRef.componentInstance.title = 'Register'; } logout() { localStorage.removeItem('token'); console.log('Logged out'); } getLoginStatus() { return this.authService.loggedIn(); } ngOnInit() { } } <file_sep>/src/app/_services/getCharacter.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { GetOrdinalNumberService } from './getOrdinalNumber.service'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class GetCharacterService { baseUrl = environment.apiUrl + 'characters/'; name: string; familyName: string; title: string; influance: number; might: number; fame: number; reputation: string; race: string; ordinalGeneration: string; birthDate: string; age: number; character: any; tempCharacterValue = 1; constructor(private http: HttpClient, private getOrdinalNumber: GetOrdinalNumberService) { } getCharacterInfo() { this.http.get(this.baseUrl + this.tempCharacterValue.toString()).subscribe(response => { this.character = response; this.updateCharacter(); }, error => { console.log(error); }); } updateCharacter() { if (this.character !== undefined) { this.name = this.character.name; this.familyName = this.character.familyName; this.title = this.character.title; this.influance = this.character.influance; this.might = this.character.might; this.fame = this.character.fame; this.reputation = this.character.reputation; this.race = this.character.race; this.ordinalGeneration = this.getOrdinalNumber.convert(this.character.generation); this.birthDate = this.character.birthDate; this.age = this.character.age; } } }
0a12b86deff9ba494f9ff44104f7a8e19c4eb4c2
[ "TypeScript" ]
17
TypeScript
ProjectAwesomeRSA/WARD
fac7e49b1cca73274e808ca4acb3f520b15d2d1c
1cbcd2e02c17933f1ed5d404a52f2ce7b1e7f296
refs/heads/master
<repo_name>galperins4/dpos-tax-core2<file_sep>/core/price.py #!/usr/bin/env python import datetime import requests import time class Price: def __init__(self): self.tsyms = 'USD,EUR' self.url = 'https://min-api.cryptocompare.com/data/pricehistorical' self.tick_convert = {'PRSN':'persona', 'XQR':'qredit', 'XPH':'phantom', 'BIND':'nos', 'HYD':'hydra-token'} self.api_key='' def get_market_price(self, ts, ticker): if ticker in ['XQR', 'PRSN', 'XPH', 'BIND','HYD']: output = self.coin_gecko(ts, ticker) else: # set request params params = {"fsym": ticker, "tsyms": self.tsyms, "ts": ts, "api_key": self.api_key} try: r = requests.get(self.url, params=params) output = [ts, r.json()[ticker]['USD'], r.json()[ticker]['EUR']] except: output = [ts, 0, 0] time.sleep(1) return output def coin_gecko(self, stamp, t): new_ticker = self.tick_convert[t] new_ts = datetime.datetime.fromtimestamp(stamp).strftime('%d-%m-%Y') url = 'https://api.coingecko.com/api/v3/coins/'+new_ticker+'/history?date='+new_ts try: r = requests.get(url) output = [stamp, r.json()['market_data']['current_price']['usd'], r.json()['market_data']['current_price']['eur']] except: output = [stamp, 0, 0] return output <file_sep>/dpos_tax.py #!/usr/bin/env python from flask import Flask, jsonify, request from flask_cors import CORS from core.taxdb import TaxDB from core.psql import DB import csv import datetime import time from util.config import use_network from crypto.identity.address import address_from_public_key from crypto.configuration.network import set_custom_network from util.client import Client from waitress import serve acct = [""] exchange_acct = {"ark":["<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>"], "qredit": ["QjmG1PUnCh1ip9tZnt24FAQv9eXnsERsYk"], "phantom": ["P9atrUx6b8naSSBedmqkvN6aAm1iiJQGbN"], "persona": ["P<KEY>ds<KEY>"], "compendia": ["<KEY>NbEbpo<KEY>"], "hydra": ["hcftLUTpLjtWJi44uJYNpdL5j1QPuLKqVH"]} exceptions = [""] n = None taxdb = None psql = None network = None atomic = 100000000 year = 86400 * 365 app = Flask(__name__) CORS(app) @app.route("/api", methods=['POST']) def tax(): try: global acct global exceptions global n global network global taxdb global psql # get addresses and exceptions req_data = request.get_json() tmp_acct = [i for i in req_data['addresses']] exceptions = [i for i in req_data["exceptions"]] network = req_data['network'] n = use_network(network) build_network(network) # convert addresses to public keys u = Client() client = u.get_client(n['port']) acct = [client.wallets.get(i)['data']['publicKey'] for i in tmp_acct] taxdb = TaxDB(n['dbuser']) psql = DB(n['database'], n['dbuser'], n['dbpassword']) out_buy, out_sell, out_summary, out_tax = process_taxes(acct) buy_cols = ['tax lot', 'timestamp', 'buy amount', 'price', 'market value', 'tx type', 'datetime', 'lot status', 'remaining_qty', 'senderId'] sell_cols = ['timestamp', 'sell amount', 'price', 'market value', 'datetime', 'short term', 'long term', 'recipientId'] summary_cols = ['year', 'income', 'short term', 'long term'] tax_cols = ['amount', 'token', 'date acquired', 'date sold', 'proceeds', 'cost basis', 'gain or loss', 'type'] acctDict = {"Buys": {"columns": buy_cols, "data":out_buy}, "Sells": {"columns": sell_cols, "data":out_sell}, "Summary": {"columns": summary_cols, "data":out_summary}, "8949": {"columns": tax_cols, "data":out_tax} } return jsonify(acctDict) except Exception as e: print(e) error ={"success":False, "msg":"API Error"} return jsonify(Error=error) def buy(acct, delegates): s = "Income" buy_agg=[] for i in acct: buys = psql.get_transactions(address_from_public_key(i), s) multi_universe = psql.get_acct_multi(address_from_public_key(i), s) buys_multi = psql.get_multi_tx(address_from_public_key(i), s, multi_universe) buy_agg += buys buy_agg += buys_multi buy_orders = create_buy_records(buy_agg, delegates) # sort and reorder lots buy_orders_sort = sorted(buy_orders, key=lambda x: x[1]) lot = 1 for j in buy_orders_sort: j[0] = lot lot+=1 return buy_orders_sort def sell(acct): s = "sell" sell_agg=[] for i in acct: sells = psql.get_transactions(i, s) multi_universe = psql.get_acct_multi(i, s) sells_multi = psql.get_multi_tx(i, s, multi_universe) sell_agg += sells sell_agg += sells_multi sell_orders = create_sell_records(sell_agg) #sort sells sell_orders_sort = sorted(sell_orders, key=lambda x: x[0]) return sell_orders_sort def create_buy_records(b, d): orders = [] for counter, i in enumerate(b): if i[4] not in exceptions and i[3] not in acct: sender_address = address_from_public_key(i[3]) # add attributes timestamp, total amount, tax lot ts = i[0] # don't include fee in incoming records order_amt = i[1] tax_lot = counter+1 price = taxdb.get_match_price(ts+n['epoch']) market_value = round((price * (order_amt/atomic)),2) convert_ts = convert_timestamp((ts+n['epoch'])) # check what type of potential income if sender_address in exchange_acct[network]: classify = "Buy - From Exchange" elif delegate_check(d, sender_address) == "Yes": classify = "Staking Reward" else: classify = "Income" remain = order_amt # create order record including t = [tax_lot, ts, order_amt, price, market_value, classify, convert_ts, "open", remain, sender_address] # append to buy_orders orders.append(t) return orders def create_sell_records(s): sells = [] # map pkeys in test_accouts to addresses so transfers check works tmp_list = map(address_from_public_key,acct) check = list(tmp_list) for i in s: if i[4] not in exceptions and i[3] not in check: # normal sell sell_amt = (i[1]+i[2]) else: # transfer out to related acct or excluded tx out. Only count tx fee out sell_amt = (i[2]) ts = i[0] price = taxdb.get_match_price(ts+n['epoch']) market_value = round((price *(sell_amt/atomic)),2) convert_ts = convert_timestamp((ts + n['epoch'])) receiver = i[3] # create sell record including t = [ts, sell_amt, price, market_value, convert_ts, 0, 0, receiver] # append to buy_orders sells.append(t) return sells def convert_timestamp(ts): return datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') def short_ts(ts): return datetime.datetime.fromtimestamp((ts+n['epoch'])).strftime('%Y-%m-%d') def lotting(b,s): tform = [] for i in s: # initialize cap gains short_cap_gain = 0 long_cap_gain = 0 sold_quantity = i[1] sold_price = i[2] for j in b: lot_quantity = j[8] # check if lot has been used up to skip and move to next lot if lot_quantity == 0: pass # check to see if another lot needs relief elif sold_quantity > lot_quantity: cap_gain = ((sold_price - j[3]) * (lot_quantity/atomic)) gain_type = gain_classification(i[0], j[1]) if gain_type == "st": short_cap_gain += cap_gain else: long_cap_gain += cap_gain # update tax form tmp = [(lot_quantity/atomic), network, short_ts(j[1]), short_ts(i[0]), (sold_price*(lot_quantity/atomic)), (j[3]*(lot_quantity/atomic)), round(cap_gain,2), gain_type] tform.append(tmp) # update lot - zero out and status j[8] -= lot_quantity j[7] = "Lot sold" # update remaining sell amount sold_quantity -= lot_quantity # this executes on the final lot to relieve for the sell else: cap_gain = ((sold_price - j[3]) * (sold_quantity/atomic)) gain_type = gain_classification(i[0], j[1]) if gain_type == "st": short_cap_gain += cap_gain else: long_cap_gain += cap_gain # update tax form tmp = [(sold_quantity/atomic), network, short_ts(j[1]), short_ts(i[0]), (sold_price*(sold_quantity/atomic)), (j[3]*(sold_quantity/atomic)), round(cap_gain,2), gain_type] tform.append(tmp) # update lot and status j[8] -= sold_quantity if j[8] == 0: j[7] = "Lot sold" else: j[7] = "Lot partially sold" break # update capital gains for sell record i[5] += round(short_cap_gain,2) i[6] += round(long_cap_gain,2) return tform def gain_classification(sts, bts): if (sts - bts) >= year: gain = "lt" else: gain = "st" return gain def write_csv(b,s,a,t): # buy file b_file = "buys.csv" with open(b_file, "w") as output: fieldnames = ['tax lot', 'timestamp', 'buy amount', 'price', 'market value', 'tx type', 'datetime', 'lot status', 'remaining_qty', 'senderId'] writer = csv.writer(output, lineterminator='\n') writer.writerow(fieldnames) writer.writerows(b) s_file = "sells.csv" with open(s_file, "w") as output: fieldnames = ['timestamp', 'sell amount', 'price', 'market value', 'datetime', 'st-gain', 'lt-gain', 'receipientId', 'lot sold'] writer = csv.writer(output, lineterminator='\n') writer.writerow(fieldnames) writer.writerows(s) a_file = "summary.csv" with open(a_file,"w") as output: fieldnames = ['year', 'income', 'short term', 'long term'] writer = csv.writer(output, lineterminator='\n') writer.writerow(fieldnames) writer.writerows(a) t_file = "8949.csv" with open(t_file,"w") as output: fieldnames = ['Amount', 'Token', 'Date Acquired', 'Date Sold', 'Proceeds', 'Cost Basis', 'Gain or Loss', 'Type'] writer = csv.writer(output, lineterminator='\n') writer.writerow(fieldnames) writer.writerows(t) def buy_convert(b): for i in b: i[2] = i[2]/atomic i[8] = i[8]/atomic def sell_convert(s): for i in s: i[1] = i[1]/atomic def delegate_check(d, check): test = "No" for i in d: if check == i[0]: test = "Yes" break return test def summarize(b,s): year1 = {"income":0, "short":0, "long":0} year2 = {"income":0, "short":0, "long":0} year3 = {"income":0, "short":0, "long":0} year4 = {"income":0, "short":0, "long":0} year5 = {"income":0, "short":0, "long":0} year6 = {"income":0, "short":0, "long":0} year7 = {"income":0, "short":0, "long":0} income = ['Staking Reward','Income'] twoeighteen = 1514786400 twonineteen = 1546322400 twotwenty = 1577858400 twotwentyone = 1609480800 twotwentytwo = 1641016800 twotwentythree = 1672552800 for i in b: if (i[1]+n['epoch']) < twoeighteen: if i[5] in income: year1['income']+=i[4] elif (i[1]+n['epoch']) < twonineteen: if i[5] in income: year2['income']+=i[4] elif (i[1]+n['epoch']) < twotwenty: if i[5] in income: year3['income']+=i[4] elif (i[1]+n['epoch']) < twotwentyone: if i[5] in income: year4['income']+=i[4] elif (i[1]+n['epoch']) < twotwentytwo: if i[5] in income: year5['income']+=i[4] elif (i[1]+n['epoch']) < twotwentythree: if i[5] in income: year6['income']+=i[4] else: if i[5] in income: year7['income']+=i[4] for j in s: if (j[0]+n['epoch']) < twoeighteen: #2017 trading year1['short']+=j[5] year1['long']+=j[6] elif (j[0]+n['epoch']) < twonineteen: year2['short']+=j[5] year2['long']+=j[6] elif (j[0]+n['epoch']) < twotwenty: year3['short']+=j[5] year3['long']+=j[6] elif (j[0]+n['epoch']) < twotwentyone: year4['short']+=j[5] year4['long']+=j[6] elif (j[0]+n['epoch']) < twotwentytwo: year5['short']+=j[5] year5['long']+=j[6] elif (j[0]+n['epoch']) < twotwentythree: year6['short']+=j[5] year6['long']+=j[6] else: year7['short']+=j[5] year7['long']+=j[6] sum_year1 = ["2017",round(year1['income'],2),round(year1['short'],2),round(year1['long'],2)] sum_year2 = ["2018",round(year2['income'],2),round(year2['short'],2),round(year2['long'],2)] sum_year3 = ["2019",round(year3['income'],2),round(year3['short'],2),round(year3['long'],2)] sum_year4 = ["2020",round(year4['income'],2),round(year4['short'],2),round(year4['long'],2)] sum_year5 = ["2021",round(year5['income'],2),round(year5['short'],2),round(year5['long'],2)] sum_year6 = ["2022",round(year6['income'],2),round(year6['short'],2),round(year6['long'],2)] sum_year7 = ["2023",round(year7['income'],2),round(year7['short'],2),round(year7['long'],2)] years = [sum_year1, sum_year2, sum_year3, sum_year4, sum_year5, sum_year6, sum_year7] return years def process_taxes(acct): tic_a = time.perf_counter() delegates = taxdb.get_delegates().fetchall() # remove delegate addresses from processing for x in acct: if delegate_check(delegates, address_from_public_key(x)) == "Yes": acct.remove(x) tic_b = time.perf_counter() print(f"Fetch Delegates in {tic_a - tic_b:0.4f} seconds") buys = buy(acct, delegates) tic_c = time.perf_counter() print(f"Get buys in {tic_b - tic_c:0.4f} seconds") sells = sell(acct) tic_d = time.perf_counter() print(f"Get sells in {tic_c - tic_d:0.4f} seconds") tax_form = lotting(buys, sells) tic_e = time.perf_counter() print(f"Lot and create tax form in {tic_d - tic_e:0.4f} seconds") buy_convert(buys) tic_f = time.perf_counter() print(f"Convert buy atomic in {tic_e - tic_f:0.4f} seconds") sell_convert(sells) tic_g = time.perf_counter() print(f"Convert sell atomic in {tic_f - tic_g:0.4f} seconds") agg_years = summarize(buys,sells) tic_h = time.perf_counter() print(f"Summarize buys and sells in {tic_g - tic_h:0.4f} seconds") # output to buy and sell csv #write_csv(buys, sells, agg_years, tax_form) return buys, sells, agg_years, tax_form def build_network(network): if network == 'ark': e = ["2017", "3", "21", "13", "00", "00"] version = 23 wif = 170 elif network == 'qredit': e = ["2017", "3", "21", "13", "00", "00"] version = 58 wif = 187 elif network == 'hydra': e = ["2019", "9", "1", "00", "00", "00"] version = 100 wif = 111 elif network == 'compendia': e = ["2020", "8", "21", "16", "00", "00"] version = 88 wif = 171 else: pass t = [int(i) for i in e] epoch = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5]) set_custom_network(epoch, version, wif) if __name__ == '__main__': #app.run(host="127.0.0.1", threaded=False) serve(app, host='127.0.01', port=5000) <file_sep>/requirements.txt psycopg2 flask arkecosystem-crypto arkecosystem-client waitress <file_sep>/util/config.py import os from configparser import ConfigParser config_file = os.path.abspath('config.ini') settings = ConfigParser() settings.read(config_file) network = {} def use_network(network_name): """Select what network you want to use Args: network_name (str): name of a network, default ones are ARK's mainnet, kapu & persona """ global network network = { 'epoch': int(settings.get(network_name, 'epoch')), 'database': settings.get(network_name, 'database'), 'dbuser': settings.get(network_name, 'dbuser'), 'dbpassword': settings.get(network_name, 'dbpassword'), 'ticker': settings.get(network_name, 'ticker'), 'port': settings.get(network_name, 'port') } return network def get_network(): """Get settings for a selected network Returns: dict: network settings """ if not network: pass return network def set_custom_network(epoch, database, dbpassword): """Set custom network Args: epoch (int): chains epoch time database (str): chains database dbuser (str): chains database user database password (str): chains database password ticker (str): ticker symbol port (int): port for public api """ section_name = 'custom' if section_name not in settings.sections(): settings.add_section(section_name) settings.set(section_name, 'epoch', int(epoch)) settings.set(section_name, 'database', str(database)) settings.set(section_name, 'database', str(dbuser)) settings.set(section_name, 'dbpassword', str(dbpassword)) settings.set(section_name, 'ticker', str(ticker)) settings.set(section_name, 'port', int(port)) <file_sep>/config.ini [ark] epoch = 1490083200 database = ark_mainnet dbuser = user dbpassword = <PASSWORD> ticker = ARK port = 4003 [hydra] epoch = 1567306800 database = hydra_mainnet dbuser = user dbpassword = <PASSWORD> ticker = HYD port = 4703 [qredit] epoch = 1490079600 database = qredit_mainnet dbuser = user dbpassword = <PASSWORD> ticker = XQR port = 4103 [phantom] epoch = 1546495200 database = phantom_mainnet dbuser = user dbpassword = <PASSWORD> ticker = XPH port = 4003 [compendia] epoch = 1598004000 database = compendia_realmainnet dbuser = user dbpassword = <PASSWORD> ticker = BIND port = 4003 <file_sep>/README.md # dpos-tax-core2 Core2 DPOS Tax Calculator <file_sep>/reference.py #!/usr/bin/env python from core.psql import DB from core.taxdb import TaxDB from core.price import Price from util.config import use_network from util.client import Client import time import sys day = 86400 def get_offset(e): offset = 0 while ((e+offset) % day) != 0: offset += 1 return (e+offset) def get_timestamps(first, ts): l = [] while first <= ts: l.append(first) first += day return l if __name__ == '__main__': option = sys.argv[1] n = use_network(option) u = Client() client = u.get_client(n['port']) psql = DB(n['database'], n['dbuser'], n['dbpassword']) taxdb = TaxDB(n['dbuser']) # update delegate list delegates = [] start = 1 d = client.delegates.all() counter = d['meta']['pageCount'] while start <= counter: delist = client.delegates.all(page=start) for j in delist['data']: delegates.append(j['address']) start += 1 taxdb.update_delegates(delegates) # pull prices from database and get last one db_prices = taxdb.get_prices().fetchall() newEpoch = db_prices[-1][0] # add new prices p = Price() t = int(time.time()) timestamps = get_timestamps(newEpoch, t) for i in timestamps: price = [p.get_market_price(i, n['ticker'])] taxdb.update_prices(price) <file_sep>/core/taxdb.py #!/usr/bin/env python import sqlite3 import threading lock = threading.Lock() class TaxDB: def __init__(self, u): self.connection = sqlite3.connect('/home/'+u+'/dpos-tax-core2/tax.db') self.cursor = self.connection.cursor() def commit(self): return self.connection.commit() def execute(self, query, args=[]): try: lock.acquire(True) res = self.cursor.execute(query, args) finally: lock.release() return res def executemany(self, query, args): try: lock.acquire(True) res = self.cursor.executemany(query, args) finally: lock.release() return res def fetchone(self): return self.cursor.fetchone() def fetchall(self): return self.cursor.fetchall() def setup(self): self.cursor.execute( "CREATE TABLE IF NOT EXISTS prices (timestamp int, usd float, eur float )") self.cursor.execute( "CREATE TABLE IF NOT EXISTS delegates (address varchar(64) )") self.connection.commit() def update_prices(self, prices): newPrices=[] for p in prices: self.cursor.execute("SELECT timestamp FROM prices WHERE timestamp = ?", (p[0],)) if self.cursor.fetchone() is None: newPrices.append((p[0], p[1], p[2])) self.executemany("INSERT INTO prices VALUES (?,?,?)", newPrices) self.commit() def get_prices(self): return self.cursor.execute("SELECT * FROM prices") def get_match_price(self, ts): # day adjust if needed # ts = ts + 86400 self.cursor.execute(f"""SELECT "usd" FROM prices WHERE "timestamp" >= '{ts}' ORDER BY "timestamp" ASC limit 1""") price = self.cursor.fetchall() if len(price) == 0: self.cursor.execute(f"""SELECT "usd" from prices ORDER BY "timestamp" DESC limit 1""") price = self.cursor.fetchall() return price[0][0] else: return price[0][0] def single_price(self, ts): return self.cursor.execute("SELECT * FROM prices WHERE timestamp = '{ts}'") def update_delegates(self, delegates): newDelegates=[] for d in delegates: self.cursor.execute("SELECT address FROM delegates WHERE address = ?", (d,)) if self.cursor.fetchone() is None: newDelegates.append((d,)) self.executemany("INSERT INTO delegates VALUES (?)", newDelegates) self.commit() def get_delegates(self): return self.cursor.execute("SELECT * FROM delegates") def single_delegate(self, addr): return self.cursor.execute("SELECT * FROM delegates WHERE address = '{addr}'") <file_sep>/core/psql.py #!/usr/bin/env python import psycopg2 class DB: def __init__(self, db, u, pw): self.connection = psycopg2.connect( dbname=db, user=u, password=pw, host='localhost', port='5432' ) self.cursor = self.connection.cursor() def get_transactions(self, account, side): try: if side == "Income": self.cursor.execute(f"""SELECT "timestamp", "amount", "fee", "sender_public_key", "id" FROM transactions WHERE "recipient_id" = '{ account}' AND "type" = {0} ORDER BY "timestamp" ASC""") else: self.cursor.execute(f"""SELECT "timestamp", "amount", "fee", "recipient_id", "id" FROM transactions WHERE "sender_public_key" = '{ account}' AND "type" <> {6} ORDER BY "timestamp" ASC""") return self.cursor.fetchall() except Exception as e: print(e) def get_acct_multi(self, account, side): # only grab multi-payments associated with account try: if side == "Income": self.cursor.execute("""SELECT "timestamp", "fee", "sender_public_key", "asset", "id" from "transactions" WHERE asset::jsonb @> '{ "payments": [{"recipientId":"%s"}]}'::jsonb order by "timestamp" DESC;""" % (account)) else: self.cursor.execute(f"""SELECT "timestamp", "fee", "sender_public_key", "asset", "id" FROM transactions WHERE "type" = 6 AND "sender_public_key" = '{account}' order by "timestamp" DESC""") return self.cursor.fetchall() except Exception as e: print(e) def get_multi_tx(self, account, side, universe): try: acct_multi=[] if side == "Income": for i in universe: for j in i[3]['payments']: if j['recipientId'] == account: tmp = (i[0], int(j['amount']), i[1], i[2], i[4]) acct_multi.append(tmp) else: # need to figure out how to get fee and divide across transactions for i in universe: if i[2] == account: multi_count = len(i[3]['payments']) fee = int(i[1] / multi_count) for j in i[3]['payments']: tmp = (i[0], int(j['amount']), fee, j['recipientId'], i[4]) acct_multi.append(tmp) return acct_multi except Exception as e: print(e) def get_delegates(self): try: self.cursor.execute(f"""SELECT "address" from wallets WHERE "username" is NOT NULL""") return self.cursor.fetchall() except Exception as e: print(e) <file_sep>/createdb.py from core.taxdb import TaxDB from core.psql import DB from core.price import Price from reference import get_offset, get_timestamps from util.config import use_network from util.client import Client import os.path import time import sys if __name__ == "__main__": option = sys.argv[1] n = use_network(option) u = Client() client = u.get_client(n['port']) # check to see if tax.db exists, if not initialize db, etc if os.path.exists('tax.db') == False: taxdb = TaxDB(n['dbuser']) psql = DB(n['database'], n['dbuser'], n['dbpassword']) taxdb.setup() # setup initial delegates delegates = [] start = 1 d = client.delegates.all() counter = d['meta']['pageCount'] while start <= counter: delist = client.delegates.all(page=start) for j in delist['data']: delegates.append(j['address']) start += 1 taxdb.update_delegates(delegates) # get prices p = Price() t = int(time.time()) newEpoch = get_offset(n['epoch']) timestamps = get_timestamps(newEpoch, t) for i in timestamps: price = [p.get_market_price(i, n['ticker'])] taxdb.update_prices(price)
d4e7b0645c306e746b51b832c90fbd62eeb3fa7d
[ "Markdown", "Python", "Text", "INI" ]
10
Python
galperins4/dpos-tax-core2
d739c5efb1f1619be02ff6b44ceb81c8d6fe1b5c
de652b5d074d4238af3e6f81921b4ce19548a334
refs/heads/master
<file_sep>checkElmKillaStatus(setIcon); chrome.browserAction.onClicked.addListener(toggleElmKilla); chrome.tabs.onUpdated.addListener(tabUpdated); function initializeScript() { verifyTabs(setStateAndRunScript); }; function tabUpdated(tabID, changeInfo, tab) { let isTabReady = changeInfo.status === 'complete'; checkElmKillaStatus((status) => { if (isTabReady && status) { runElmKilla(tab); } }); }; function setIcon(status) { status ? setActiveIcon() : setInactiveIcon(); }; function runElmKilla(tab) { if (tab.url.search(/https?:\/\//) === 0) { chrome.tabs.executeScript(tab.id, { file: "./elm-killa-script.js" }); }; }; function toggleElmKilla() { checkElmKillaStatus((status) => { status = !status; chrome.storage.local.set({ "elmKillaActive": status }); setIcon(status); chrome.tabs.query({}, (tabs) => { tabs.forEach((tab) => { runElmKilla(tab); }); }); }); }; function checkElmKillaStatus(callback) { chrome.storage.local.get(["elmKillaActive"], function(result) { callback(result.elmKillaActive); }); } function setInactiveIcon() { chrome.browserAction.setIcon({ path : { "16": "images/elm-lives16.png", "32": "images/elm-lives32.png", "48": "images/elm-lives48.png", "128": "images/elm-lives128.png" } }); } function setActiveIcon() { chrome.browserAction.setIcon({ path : { "16": "images/elm-dies16.png", "32": "images/elm-dies32.png", "48": "images/elm-dies48.png", "128": "images/elm-dies128.png" } }); } <file_sep># Elm Killa (for Chrome) TL;DR: This is a super simple Chrome plugin that hides the elm debugger launcher, lest you need to see something underneath it. [elm](https://elm-lang.org/) is a functional programming language that compiles down to JavaScript. We use it extensively at [carwow](https://carwow.co.uk), and as such, we ran across an issue: #### elm debugger launcher ![elm debugger launcher](/readme-images/debugger-launcher.png) In development mode when using elm, this div is overlaid on top of your app in the bottom-right corner; clicking on it launches the elm debugger window: #### elm debugger window ![elm debugger window](/readme-images/debugger-window.png) This is great until you need to see underneath it. Then you must dig through the DOM elements in your browser's development tools and find the offending element so you can either delete it, or hide it. Unfortunately, at the time of writing this element does not ship with an identifiable `class` or `id` attribute, making it rather tricky to track down. Added to the complication is that since it is possible to have multiple instances of an elm app running, the debugger launcher can have multiple instances of itself stacked, so you have to isolate them all before dealing with them. If this bothers you, then you need to meet **elmKilla:** ![elmKilla logo](/readme-images/elmKilla-logo.png) **elmKilla** will happily scour your DOM and remove the offending element (it actually just adds `display: none`, so you can have elmKilla resurrect its victims at the touch of a button. #### elmKilla deactivated: ![elmKilla in-situ — deactivated](/readme-images/in-situ-deactivated.png) #### elmKilla activated: ![elmKilla in-situ — activated](/readme-images/in-situ-activated.png) ### Installation Currently elmKilla is available for the following platforms: - [Link to Chrome Extension (Chrome Web Store)](https://chrome.google.com/webstore/detail/elm-killa/imncilbiiemenecndahiafoafbiicgpl) - [Link to Firefox Add-on (Mozilla Add-on store)](https://addons.mozilla.org/en-GB/firefox/addon/elm-killa/)
f902e15a1a819dd28836cd592c06d4466bb66d92
[ "JavaScript", "Markdown" ]
2
JavaScript
oceansize/chromeElmKilla
d76a5548162be4d44c102681b73f4983b401493f
1baae2294227fd4690493d100b1e64ad9a5bebf9
refs/heads/master
<repo_name>MattyCips/ReactTodoList<file_sep>/README.md App Instructions: - Write your task in the input box provided and click the add button to add your task to the list. - Once added, you will find some action buttons to the right, Edit and Delete. - If you click on Edit, you will be prompted with an input box to edit your task - Once you are done editing, you can click the Save button which takes the place of the Edit button when clicked on. - If you click on the Delete button, the task will be removed from the list. - If you want to Edit, and then want to undo, you can click the Cancel button which takes the place of the Delete button when editing. - Notice the tasks are all red when first added. This signifies that they are incomplete. - To mark a task complete, simply click on the task name and it will change colors to green. Jon: I will be honest I did follow a YouTube tutorial for this app. I used it more as a learning opportunity to give me a better understanding of React, and I'm happy to say that's what I got from this. References: https://www.youtube.com/watch?v=IR6smI_YJDE <file_sep>/src/todo-list-header.js import React, { Component } from 'react'; class TodoListHeader extends Component { render() { return ( <table> <thead> <tr> <th class="header">Task</th> <th class="action">Action</th> </tr> </thead> </table> ); } } export default TodoListHeader;
3ffbf7a6f680459d57611536dac060be5eab2a44
[ "Markdown", "JavaScript" ]
2
Markdown
MattyCips/ReactTodoList
84ae85241372d96bd4cda18a9f5861f0d68efee3
4a64940fed86742866b9446b4fb35246171cd64a
refs/heads/master
<repo_name>Rajan-Aggarwal/link_sharing_website<file_sep>/accounts/views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout def signup(request): if request.method=="POST": username = request.POST['username'] password = request.POST['<PASSWORD>1'] password_check = request.POST['<PASSWORD>2'] if password == password_check: try: user = User.objects.get(username=username) return render(request, 'accounts/signup.html', {'msg':'username already exists. try again'}) except User.DoesNotExist: user = User.objects.create_user(username, password=<PASSWORD>) return render(request, 'accounts/login.html', {'msg':'successfully registered. login here'}) else: return render(request, 'accounts/signup.html', {'msg':'couldn\'t match passwords. try again'}) else: return render(request, 'accounts/signup.html') def signin(request): if request.method=="POST": username = request.POST['username'] password = request.POST['<PASSWORD>'] user = authenticate(request, username=username, password=<PASSWORD>) #gives a User object if user is not None: login(request, user) if 'next' in request.POST: #if request.POST['next'] exists return redirect(request.POST['next']) return redirect('home') else: return render(request, 'accounts/login.html', {'msg':'invalid username or password'}) else: return render(request, 'accounts/login.html') def logout_view(request): logout(request) return redirect('home') <file_sep>/README.md # link_sharing_website website that allows users to post links of other webpages/websites, sort of like a basic reddit clone..
079ca0382aaeb1708d4063fb1d3118a9e9a9c355
[ "Markdown", "Python" ]
2
Python
Rajan-Aggarwal/link_sharing_website
364657350cfd0715c24298f8fcba579d5b7927e6
cd99e25a164912c73508dee2906d772dc705f260
refs/heads/master
<file_sep>#!/usr/bin/env ruby Dir['*'].each do |file| if file =~ /\?/ puts %Q!mv '#{file}' '#{file.gsub(/\?.*/, "")}'! end end<file_sep>Disposable script ================= A collection of one-off scripts. http://www.urbandictionary.com/define.php?term=one%20off
a3dd339054fba55a12b1cee1b1b7479d4cec30d1
[ "Markdown", "Ruby" ]
2
Ruby
chengguangnan/disposable_script
1a405233fe1c5fb6ed3bf1479babbea31100382a
47b60a3848275d76a37b22269dfea585243f88f7
refs/heads/master
<repo_name>emmiehe/basic-shading<file_sep>/README.md # Basic Shading Displays a circular shape that is shaded using the Phong Illumination Model. The skeleton was from [Fall 2016 UC Berkeley CS184/284A Foundations of Computer Graphics](https://inst.eecs.berkeley.edu/~cs184/fa16/assignments.html) ## Examples * An image showing diffuse only shading from a single directional light source. (-kd 0.5 0.5 0.5 -dl -1 -1 -1 1 1 1) ![alt text](img/1.png) * An image showing diffuse only shading from a single point light source. (-kd 0.5 0.5 0.5 -pl 1 0 1 0 1 0) ![alt text](img/2.png) * An image showing specular only shading from a single point light source. (-ks 0.5 0.5 0.5 -pl 1 0 1 1 1 1 ) ![alt text](img/3.png) * An image showing specular only shading from a single directional light source. (-ks 0.5 0.5 0.5 -dl -1 -1 -1 1 1 1) ![alt text](img/4.png) * An image showing combined specular and diffuse shading with only one directional light source. (-ks 0.5 0.5 0.5 -kd 0.5 0.5 0.5 -dl -1 -1 -1 1 1 1) ![alt text](img/5.png) * An image showing combined specular and diffuse shading with one directional light source and one point light source. (-ks 0.5 0.5 0.5 -kd 0.5 0.5 0.5 -dl -1 -1 -1 1 1 1 -pl 1 0 1 0.8 0.2 0.8) ![alt text](img/6.png) * An image showing combined specular and diffuse shading with one directional light source and one point light source on an isotropic material. (-ks 0.5 0.5 0.5 -kd 0.5 0.5 0.5 -dl -1 -1 -1 1 1 1 -pl 1 0 1 0.8 0.2 0.8 -sp 300) ![alt text](img/7.png) * An image showing combined specular and diffuse shading with one directional light source and one point light source on an anisotrophic material. (-ks 0.5 0.5 0.5 -kd 0.5 0.5 0.5 -dl -1 -1 -1 1 1 1 -pl 1 0 1 0.8 0.2 0.8 -sp 2 -spu 10 -spv 100) ![alt text](img/8.png) * An image showing combined specular and diffuse shading with one directional light source and one point light source on an anisotrophic material. (-ks 0.5 0.5 0.5 -kd 0.5 0.5 0.5 -dl -1 -1 -1 1 1 1 -pl 1 0 1 0.8 0.2 0.8 -sp 2 -spu 100 -spv 10) ![alt text](img/9.png) * An image showing combined specular and diffuse shading with one directional light source and two point light source on an isotrophic material. (-ks 0.5 0.5 0.5 -kd 0.5 0.5 0.5 -dl -1 -1 -1 1 1 1 -pl 1 0 1 0.8 0.2 0.8 -sp 2 -pl -1 -1 1 0.5 0.6 0.9) ![alt text](img/10.png) * An image showing combined specular and diffuse shading with one directional light source and two point light source on an isotrophic material (larger sp value). (-kd 0.5 0.5 0.5 -ks 0.5 0.5 0.5 -dl -1 -1 -1 0.2 0.2 0.7 -sp 250 -ka 0.1 0.2 0.1 -pl -1 1 1 1 1 1 -pl 1 -1 1 0 0.2 0.5) ![alt text](img/12.png) * An image showing combined specular and diffuse shading with one directional light source and three point light source on an isotrophic material. (-ks 0.5 0.5 0.5 -kd 0.5 0.5 0.5 -dl -1 -1 -1 1 1 1 -pl 1 0 1 0.8 0.2 0.8 -sp 2 -pl -1 -1 1 0.5 0.6 0.9 -pl -1 1 1 0.1 0.8 0.2) ![alt text](img/11.png) * An image showing combined specular and diffuse shading with one directional light source and one point light source on an Ashikhmin-Shirley material. (-ks .5 .5 .5 -kd .5 .5 .5 -spu 1 -spv 70 -dl -1 -1 -0.2 4 2 1 -pl -1 1 1 0.3 0.8 0.2 -asm) ![alt text](img/14.png) * An image showing combined ambient, specular and diffuse shading with two directional light source on an isotrophic material. (-kd 0.5 0.5 0.5 -ks 0.5 0.5 0.5 -sp 200 -dl -1 -1 -1 0.8 0 0.2 -dl 1 -1 -1 0.4 1 0 -ka 0.3 0.3 0.3) ![alt text](img/15.png) ## Get Started 1. `cd basic-shading` 2. `mkdir build` 3. `cd build` 4. `cmake ..` 5. `make` 6. `./shader <options>` ## Command Line Options * -ka r g b * This is the ambient color coefficients of the sphere material. The parameters r g b are numbers between 0 and 1 inclusive. * -kd r g b * This is the diffuse color coefficients of the sphere material. The parameters r g b are numbers between 0 and 1 inclusive. * -ks r g b * This is the specular color coefficients of the sphere material. The parameters r g b are numbers between 0 and 1 inclusive. * -spu pu * This is the power coefficient on the specular term in the u direction for an anisotropic material. It is a number between 0 and max_float. * -spv pv * This is the power coefficient on the specular term in the v direction for an anisotropic material. It is a number between 0 and max_float. * -sp p * This is the power coefficient on the specular term for an isotropic material. It is a number between 0 and max_float. (i.e. the same as setting pu and pv the the same value.) * -pl x y z r g b * This adds a point light to the scene. The x y z values are the location of the light. The r g b values are it's color. Note that the x y z values are relative to the sphere. That is, the center of the sphere is at the origin and the radius of the sphere defines one unit of length. The Y direction is UP, the X direction is to the right on the screen, and the Z direction is "in your face." The r g b value are between 0 and max_float, NOT between 0 and 1 (that is, the r g b values encode the brightness of the light). * -dl x y z r g b * This adds a directional light to the scene. The x y z values are the direction that the light points in. The r g b values are it's color. * -asm * Ashikhmin-Shirley materials ## Keyboard features 1. 'ESC': Exit 2. 'Q': Exit 3. 'F': Full screen 4. '↓': Translate objects down 5. '↑': Translate objects up 6. '←': Translate objects left 7. '→': Translate objects right <file_sep>/build/src/CMakeFiles/shader.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/shader.dir/shading.cpp.o" "../shader.pdb" "../shader" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/shader.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/src/shading.cpp #include <vector> #include <iostream> #include <fstream> #include <cmath> #include <string.h> //include header file for glfw library so that we can use OpenGL #include <GLFW/glfw3.h> #include <stdlib.h> #include <time.h> #include <math.h> #ifdef _WIN32 static DWORD lastTime; #else static struct timeval lastTime; #endif #define PI 3.14159265 // Should be used from mathlib using namespace std; //**************************************************** // Global Variables //**************************************************** GLfloat translation[3] = {0.0f, 0.0f, 0.0f}; bool auto_strech = false; int Width_global = 400; int Height_global = 400; inline float sqr(float x) { return x*x; } float*** cmd = (float***)calloc(1, sizeof(float**)); // More global varibles // ds is <= 5 groups of directional light sources; float** ds; // ps is <= 5 groups of point light sources; float** ps; float* dl; float* I_d; float* pl; float* I_p; float* ka; float* kd; float* ks; // view direction float* view; // exponent float* sp_coef; float* spu; float* spv; float* a_sm; //**************************************************** // Simple init function //**************************************************** void initializeRendering() { glfwInit(); } //**************************************************** // A routine to set a pixel by drawing a GL point. This is not a // general purpose routine as it assumes a lot of stuff specific to // this example. //**************************************************** void setPixel(float x, float y, GLfloat r, GLfloat g, GLfloat b) { glColor3f(r, g, b); glVertex2f(x+0.5, y+0.5); // The 0.5 is to target pixel centers // Note: Need to check for gap bug on inst machines. } //**************************************************** // Keyboard inputs //**************************************************** static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { switch (key) { case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(window, GLFW_TRUE); break; case GLFW_KEY_Q: glfwSetWindowShouldClose(window, GLFW_TRUE); break; case GLFW_KEY_LEFT : if (action) translation[0] -= 0.01f * Width_global; break; case GLFW_KEY_RIGHT: if (action) translation[0] += 0.01f * Width_global; break; case GLFW_KEY_UP : if (action) translation[1] += 0.01f * Height_global; break; case GLFW_KEY_DOWN : if (action) translation[1] -= 0.01f * Height_global; break; case GLFW_KEY_F: if (action) auto_strech = !auto_strech; break; case GLFW_KEY_SPACE: break; default: break; } } //**************************************************** // Some helper functions I used to draw the sphere //**************************************************** // normalize takes in a vector and normalize it; float* normalize(float *ar) { float *result = (float*) calloc(3, sizeof(float)); float length = sqrt(ar[0] * ar[0] + ar[1] * ar[1] + ar[2]*ar[2]); result[0] = ar[0] / length; result[1] = ar[1] / length; result[2] = ar[2] / length; //cout << "( " << result[0] << ", "<< result[1] << ", " << result[2] << " )" <<endl; return result; } // max returns the bigger float float max(float a, float b){ if (a < b) { return b; } return a; } // dot product of two vectors, return a float number float dot(float* a, float* b) { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]; } // cross product of two vectors, return a vector float* cross(float *a, float *b){ float *c = (float*) calloc(3, sizeof(float)); c[0] = a[1]*b[2] - a[2]*b[1]; c[1] = a[2]*b[0] - a[0]*b[2]; c[2] = a[0]*b[1] - a[1]*b[0]; return c; } // vector addition float* vector_add(float *a, float *b){ float *c = (float*) calloc(3, sizeof(float)); c[0] = a[0] + b[0]; c[1] = a[1] + b[1]; c[2] = a[2] + b[2]; return c; } // vector scaling float* vector_scal(float *a, float s){ float *b = (float*) calloc(3, sizeof(float)); b[0] = s*a[0]; b[1] = s*a[1]; b[2] = s*a[2]; return b; } // ambient component = I * k_a float* ambient(float *ka, float * I) { float *result = (float*) calloc(3, sizeof(float)); result[0] = ka[0] * I[0]; result[1] = ka[1] * I[1]; result[2] = ka[2] * I[2]; return result; } // diffuse component = I * k_d * max(dot(normalized light, surface normal), 0) float* diffuse(float* kd, float * I, float *nl, float *nn){ float *result = (float*) calloc(3, sizeof(float)); float m = max(dot(nl, nn), 0); result[0] = kd[0] * I[0] * m; result[1] = kd[1] * I[1] * m; result[2] = kd[2] * I[2] * m; //cout << "( " << result[0] << ", "<< result[1] << ", " << result[2] << " )" <<endl; return result; } // specular component = I * k_s * max(dot(r, view), 0)_p; r = -l + 2(dot(l, n))*n float* specular(float* ks, float * I, float *nl, float *nn, float *nv, float* sp_coef){ float *result = (float*) calloc(3, sizeof(float)); float *nr = (float*) calloc(3, sizeof(float)); nr = vector_add(vector_scal(nl, -1), vector_scal(nn, 2*dot(nl, nn))); nr = normalize(nr); float m = max(dot(nr, nv), 0); //nv should be already normalized float m_p = pow(m, sp_coef[0]); result[0] = ks[0] * I[0] * m_p; result[1] = ks[1] * I[1] * m_p; result[2] = ks[2] * I[2] * m_p; //free(nr); //free(temp); return result; } float* asm_diff(float* kd, float* ks, float *nl, float *nn, float *nv, float *I){ float *result = (float*) calloc(3, sizeof(float)); float temp1 = 28/(23*PI); float temp2 = (1 - pow((1 - dot(nn, nv)/2), 5)) * (1 - pow((1 - dot(nn, nl)/2), 5)); float *f = (float*) calloc(3, sizeof(float)); f[0] = kd[0]*(1 - ks[0]); f[1] = kd[1]*(1 - ks[1]); f[2] = kd[2]*(1 - ks[2]); result[0] = temp1*temp2*f[0]*I[0]; result[1] = temp1*temp2*f[1]*I[1]; result[2] = temp1*temp2*f[2]*I[2]; return result; } float* asm_spec(float* ks, float *nl, float *nn, float *nv, float* spu, float* spv, float* h, float* U, float* V, float* I){ float *result = (float*) calloc(3, sizeof(float)); float p = (spu[0]*pow(dot(h, U), 2) + spv[0]*pow(dot(h, V), 2))/(1 - pow(dot(h, nn), 2)); float temp1 = sqrt((spu[0] + 1)*(spv[0]+1))/(8*PI); float temp2 = (pow(dot(nn, h), p))/(dot(h, nv)*max(dot(nn, nv), dot(nn, nl))); float* f = (float*)calloc(3, sizeof(float)); f[0] = ks[0] + (1-ks[0])*pow((1 - dot(h, nv)), 5); f[1] = ks[1] + (1-ks[1])*pow((1 - dot(h, nv)), 5); f[2] = ks[2] + (1-ks[2])*pow((1 - dot(h, nv)), 5); result[0] = temp1*temp2*f[0]*I[0]; result[1] = temp1*temp2*f[1]*I[1]; result[2] = temp1*temp2*f[2]*I[2]; return result; } //**************************************************** // Draw a filled circle. //**************************************************** void drawCircle(float centerX, float centerY, float radius) { // Draw inner circle glBegin(GL_POINTS); // We could eliminate wasted work by only looping over the pixels // inside the sphere's radius. But the example is more clear this // way. In general drawing an object by loopig over the whole // screen is wasteful. int minI = max(0,(int)floor(centerX-radius)); int maxI = min(Width_global-1,(int)ceil(centerX+radius)); int minJ = max(0,(int)floor(centerY-radius)); int maxJ = min(Height_global-1,(int)ceil(centerY+radius)); // viewing point float view[3] = {0, 0, 1}; for (int i = 0; i < Width_global; i++) { for (int j = 0; j < Height_global; j++) { // Location of the center of pixel relative to center of sphere float x = (i+0.5-centerX); float y = (j+0.5-centerY); float dist = sqrt(sqr(x) + sqr(y)); if (dist <= radius) { // This is the front-facing Z coordinate float z = sqrt(radius*radius-dist*dist); //cout << "( " << x << ", "<< y << ", " << z << " )" <<endl; float *temp = (float*) calloc(3, sizeof(float)); temp[0] = x; temp[1] = y; temp[2] = z; float *normal = normalize(temp); //free(temp); float *nv = normalize(view); // V and U float *y = (float*) calloc(3, sizeof(float)); y[0] = 0; y[1] = 1; y[2] = 0; float *V = normalize(vector_add(y, vector_scal(normal, (-1)*dot(normal, y)))); float *U = normalize(cross(V, normal)); // default rgb should be (0, 0, 0); float *rgb1 = (float*) calloc(3, sizeof(float)); rgb1[0] = 0; rgb1[1] = 0; rgb1[2] = 0; float *rgb2 = (float*) calloc(3, sizeof(float)); rgb2[0] = 0; rgb2[1] = 0; rgb2[2] = 0; //if there are multiple directional sources if (ds){ int i = 0; while (ds[i]) { dl = &(ds[i][0]); I_d = &(ds[i][3]); // normalize directional light float *ndl = normalize(vector_scal(dl, -1)); // half vector float *hdl = normalize(vector_add(ndl, nv)); // asm attempt if (spu&&spv&&a_sm){ //cout << "ASM" <<endl; rgb1 = vector_add(vector_add(vector_add(ambient(ka, I_d), asm_diff(kd, ks, ndl, normal, nv, I_d)), asm_spec(ks, ndl, normal, nv, spu, spv, hdl, U, V, I_d)), rgb1); }else if (spu && spv && !a_sm){ // if there is spu and spv to replace exp float *new_dp = (float*) calloc(1, sizeof(float)); //alternative way of calculating the exponent //new_dp[0] = spu[0] * pow(dot(normalize(vector_add(hdl, vector_scal(normal, (-1)*dot(hdl, normal)))), U), 2) + spv[0] * (1 - pow(dot(normalize(vector_add(hdl, vector_scal(normal, (-1)*dot(hdl, normal)))), U), 2)); new_dp[0] = (spu[0]*pow(dot(hdl, U), 2) + spv[0]*pow(dot(hdl, V), 2))/(1 - pow(dot(hdl, normal), 2)); rgb1 = vector_add(vector_add(vector_add(ambient(ka, I_d), diffuse(kd, I_d, ndl, normal)), specular(ks, I_d, ndl, normal, nv, new_dp)), rgb1); }else { rgb1 = vector_add(vector_add(vector_add(ambient(ka, I_d), diffuse(kd, I_d, ndl, normal)), specular(ks, I_d, ndl, normal, nv, sp_coef)), rgb1); } i += 1; //cout << i << " directional light" << endl; } } if (ps){ //cout << "there is point light!" << endl; int i = 0; while (ps[i]) { pl = &(ps[i][0]); I_p = &(ps[i][3]); float *npl = normalize(vector_add(pl, vector_scal(normal, -1))); float *hpl = normalize(vector_add(npl, nv)); // asm attempt if (spu&&spv&& a_sm){ rgb2 = vector_add(vector_add(vector_add(ambient(ka, I_p), asm_diff(kd, ks, npl, normal, nv, I_p)), asm_spec(ks, npl, normal, nv, spu, spv, hpl, U, V, I_p)), rgb2); }else if (spu && spv && !a_sm){ float *new_pp = (float*) calloc(1, sizeof(float)); //new_pp[0] = spu[0] * pow(dot(normalize(vector_add(hpl, vector_scal(normal, (-1)*dot(hpl, normal)))), U), 2) + spv[0] * (1 - pow(dot(normalize(vector_add(hpl, vector_scal(normal, (-1)*dot(hpl, normal)))), U), 2)); new_pp[0] = (spu[0]*pow(dot(hpl, U), 2) + spv[0]*pow(dot(hpl, V), 2))/(1 - pow(dot(hpl, normal), 2)); rgb2 = vector_add(vector_add(vector_add(ambient(ka, I_p), diffuse(kd, I_p, npl, normal)), specular(ks, I_p, npl, normal, nv, new_pp)), rgb2); }else { rgb2 = vector_add(vector_add(vector_add(ambient(ka, I_p), diffuse(kd, I_p, npl, normal)), specular(ks, I_p, npl, normal, nv, sp_coef)), rgb2); //cout << rgb2[0] << ", "<< rgb2[1] << ", " << rgb2[2] << endl; } i += 1; } } //cout << "( " << rgb2[0] << ", "<< rgb2[1] << ", " << rgb2[2] << " )" <<endl; float *rgb = vector_add(rgb1, rgb2); //cout << "( " << rgb[0] << ", "<< rgb[1] << ", " << rgb[2] << " )" <<endl; setPixel(i, j, rgb[0], rgb[1], rgb[2]); //free(rgb1); //free(rgb2); //free(rgb); // This is amusing, but it assumes negative color values are treated reasonably. // setPixel(i,j, x/radius, y/radius, z/radius ); // Just for fun, an example of making the boundary pixels yellow. /* if (dist > (radius-1.0)) { setPixel(i, j, 1.0, 1.0, 0.0); } */ } } } glEnd(); } //**************************************************** // function that does the actual drawing of stuff //*************************************************** void display( GLFWwindow* window) { glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); //clear background screen to black glClear(GL_COLOR_BUFFER_BIT); // clear the color buffer (sets everything to black) glMatrixMode(GL_MODELVIEW); // indicate we are specifying camera transformations glLoadIdentity(); // make sure transformation is "zero'd" //----------------------- code to draw objects -------------------------- glPushMatrix(); glTranslatef (translation[0], translation[1], translation[2]); drawCircle(Width_global / 2.0 , Height_global / 2.0 , min(Width_global, Height_global) * 0.9 / 2.0); glPopMatrix(); glfwSwapBuffers(window); } //**************************************************** // function that is called when window is resized //*************************************************** void size_callback(GLFWwindow* window, int width, int height) { // Get the pixel coordinate of the window // it returns the size, in pixels, of the framebuffer of the specified window glfwGetFramebufferSize(window, &Width_global, &Height_global); glViewport(0, 0, Width_global, Height_global); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, Width_global, 0, Height_global, 1, -1); display(window); } //**************************************************** // function that is reading the command line opt //*************************************************** float*** readCmd(int argc, char *argv[]){ //ka, kd, ks, spu, spv, sp, pl, dl float*** retVal = (float***)calloc(9, sizeof(float**)); int i = 1, plc = 0, dlc = 0; while (i < argc) { //cout<<"start"<<endl; if (strcmp(argv[i], "-ka") == 0){ //cout<<"ka found"<<endl; float** ret = (float**)calloc(1, sizeof(float*)); retVal[0] = ret; float* r = (float*)calloc(3, sizeof(float)); ret[0] = r; r[0] = stof(argv[i+1]); r[1] = stof(argv[i+2]); r[2] = stof(argv[i+3]); i += 4; } else if (strcmp(argv[i], "-kd") == 0){ //cout<<"kd found"<<endl; float** ret = (float**)calloc(1, sizeof(float*)); retVal[1] = ret; float* r = (float*)calloc(3, sizeof(float)); ret[0] = r; r[0] = stof(argv[i+1]); r[1] = stof(argv[i+2]); r[2] = stof(argv[i+3]); i += 4; } else if (strcmp(argv[i], "-ks") == 0){ //cout<<"ks found"<<endl; float** ret = (float**)calloc(1, sizeof(float*)); retVal[2] = ret; float* r = (float*)calloc(3, sizeof(float)); ret[0] = r; r[0] = stof(argv[i+1]); r[1] = stof(argv[i+2]); r[2] = stof(argv[i+3]); i += 4; } else if (strcmp(argv[i], "-spu") == 0){ //cout<<"spu found"<<endl; float** ret = (float**)calloc(1, sizeof(float*)); retVal[3] = ret; float* r = (float*)calloc(1, sizeof(float)); ret[0] = r; r[0] = stof(argv[i+1]); i += 2; } else if (strcmp(argv[i], "-spv") == 0){ //cout<<"spv found"<<endl; float** ret = (float**)calloc(1, sizeof(float*)); retVal[4] = ret; float* r = (float*)calloc(1, sizeof(float)); ret[0] = r; r[0] = stof(argv[i+1]); i += 2; } else if (strcmp(argv[i], "-sp") == 0){ //cout<<"sp found"<<endl; float** ret = (float**)calloc(1, sizeof(float*)); retVal[5] = ret; float* r = (float*)calloc(1, sizeof(float)); ret[0] = r; r[0] = stof(argv[i+1]); i += 2; } else if (strcmp(argv[i], "-pl") == 0){ //cout<<"pl found"<<endl; if (plc == 0){ float** ret = (float**)calloc(5, sizeof(float*)); retVal[6] = ret; } float* r = (float*) calloc(6, sizeof(float)); retVal[6][plc] = r; r[0] = stof(argv[i+1]); r[1] = stof(argv[i+2]); r[2] = stof(argv[i+3]); r[3] = stof(argv[i+4]); r[4] = stof(argv[i+5]); r[5] = stof(argv[i+6]); plc += 1; i += 7; } else if (strcmp(argv[i], "-dl") == 0){ //cout<<"dl found"<<endl; if (dlc == 0){ float** ret = (float**)calloc(5, sizeof(float*)); retVal[7] = ret; } float* r = (float*) calloc(6, sizeof(float)); retVal[7][dlc] = r; r[0] = stof(argv[i+1]); r[1] = stof(argv[i+2]); r[2] = stof(argv[i+3]); r[3] = stof(argv[i+4]); r[4] = stof(argv[i+5]); r[5] = stof(argv[i+6]); dlc += 1; i += 7; }else if (strcmp(argv[i], "-asm") == 0){ //cout<<"asm found"<<endl; float** ret = (float**)calloc(1, sizeof(float*)); retVal[8] = ret; float* r = (float*)calloc(1, sizeof(float)); ret[0] = r; r[0] = 1; i += 1; } else { cout << "Unrecognized command! " << endl; return NULL; } } return retVal; } //**************************************************** // the usual stuff, nothing exciting here //**************************************************** int main(int argc, char *argv[]) { //cout << argc << endl; if (argc > 1) { cmd = readCmd(argc, argv); if (cmd) { for (int i = 0; i < 9; ++i) { //cout << "start assigning" << endl; if (cmd[i]){ if (i == 0) { ka = cmd[i][0]; }else if (i == 1) { kd = cmd[i][0]; }else if (i == 2) { ks = cmd[i][0]; }else if (i == 3) { spu = cmd[i][0]; }else if (i == 4) { spv = cmd[i][0]; }else if (i == 5) { sp_coef = cmd[i][0]; }else if (i == 6) { ps = cmd[i]; //pl = &(ps[0][0]); //I_p = &(ps[0][3]); }else if (i == 7) { ds = cmd[i]; //dl = &(ds[0][0]); //I_d = &(ds[0][3]); }else if (i == 8) { a_sm = cmd[i][0]; } } } } } if (!ka) { ka = (float*)calloc(3, sizeof(float)); ka[0] = 0; ka[1] = 0; ka[2] = 0; } if (!kd) { kd = (float*)calloc(3, sizeof(float)); kd[0] = 0; kd[1] = 0; kd[2] = 0; } if (!ks) { ks = (float*)calloc(3, sizeof(float)); ks[0] = 0; ks[1] = 0; ks[2] = 0; } /* if (!spu) { spu = (float*) calloc(1, sizeof(float)); spu[0] = 1; } if (!spv) { spv = (float*) calloc(1, sizeof(float)); spv[0] = 1; } */ if (!sp_coef) { sp_coef = (float*) calloc(1, sizeof(float)); sp_coef[0] = 1; } if (!ps){ pl = (float*) calloc(3, sizeof(float)); pl[0] = 0; pl[1] = 0; pl[2] = 0; I_p = (float*) calloc(3, sizeof(float)); I_p[0] = 0; I_p[1] = 0; I_p[2] = 0; } if (!ds){ dl = (float*) calloc(3, sizeof(float)); dl[0] = 0; dl[1] = 0; dl[2] = 0; I_d = (float*) calloc(3, sizeof(float)); I_d[0] = 0; I_d[1] = 0; I_d[2] = 0; } if (!a_sm) { a_sm = NULL; } //This initializes glfw initializeRendering(); GLFWwindow* window = glfwCreateWindow( Width_global, Height_global, "CS184", NULL, NULL ); if ( !window ) { cerr << "Error on window creating" << endl; glfwTerminate(); return -1; } const GLFWvidmode * mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); if ( !mode ) { cerr << "Error on getting monitor" << endl; glfwTerminate(); return -1; } glfwMakeContextCurrent( window ); // Get the pixel coordinate of the window // it returns the size, in pixels, of the framebuffer of the specified window glfwGetFramebufferSize(window, &Width_global, &Height_global); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, Width_global, 0, Height_global, 1, -1); glfwSetWindowTitle(window, "CS184"); glfwSetWindowSizeCallback(window, size_callback); glfwSetKeyCallback(window, key_callback); while( !glfwWindowShouldClose( window ) ) // infinite loop to draw object again and again { // because once object is draw then window is terminated display( window); if (auto_strech){ glfwSetWindowSize(window, mode->width, mode->height); glfwSetWindowPos(window, 0, 0); } glfwPollEvents(); } return 0; }
475dcae7867e6f7a80816f608435cb341e39d8ce
[ "Markdown", "CMake", "C++" ]
3
Markdown
emmiehe/basic-shading
e21bfcde7ee8eab70fa9511573029e1b64aa5cc6
c264a675524ddf8e34d1d17551cb4bdc2508c2a5
refs/heads/master
<repo_name>WebLanjut41-02/praktikum-1-frznst-1<file_sep>/models/arrayan.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Arrayan extends CI_Model { public $usera=[]; public $passa=[]; public function __construct() { parent::__construct(); } public function insert($user,$pass) { # code... array_push($this->usera,$user); array_push($this->passa,$pass); $this->session->set_userdata('user',$this->usera); $this->session->set_userdata('pass',$this->passa); //print_r($this->usera); } public function get($user,$pass) { # code... if(in_array($user,$this->usera)&&in_array($pass, $this->passa)){ return true; } else{ return false; } } } /* End of file array.php */ /* Location: ./application/models/array.php */<file_sep>/controllers/C_login.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class C_login extends My_Controller { public function __construct() { parent::__construct(); $this->load->library('form_validation'); $this->load->model('arrayan'); $this->load->helper('form'); } public function index($halaman="login") { $this->load->view($halaman); } function cek(){ $this->form_validation->set_rules('username', 'user', 'trim|required',array('required'=>'Harap isi kolom user')); $this->form_validation->set_rules('password', 'pass', 'trim|required',array('required'=>'Harap isi kolom password')); if ($this->form_validation->run() == FALSE) { $this->index(); } else { # code... $username = $this->input->post('username'); $password = $this->input->post('password'); if($username=='admin' && $password=='<PASSWORD>'){ $this->arrayan->insert($username,$password); $this->index('list'); } else{ $this->session->set_flashdata('fail', 'username dan password salah'); $this->index(); } } } public function logout() { # code... $this->session->sess_destroy(); redirect('C_login/index','refresh'); } public function tambah() { $user = $this->input->post('username'); $pass = $this->input->post('password'); $this->arrayan->insert($user,$pass); $this->index('list'); } } /* End of file C_login.php */ /* Location: ./application/controllers/C_login.php */<file_sep>/views/login.php <body> <?php if($this->session->flashdata('fail')){ echo $this->session->flashdata('fail'); } ?> <form action="<?php echo base_url();?>/index.php/C_login/cek" method="POST"> <table> <tr><td>USERNAME</td><td><input type="text" name="username"></td> <?php if (form_error('username')) { # code... echo "<td>".form_error('username')."</td>"; }?> </tr> <tr><td>PASSWORD</td><td><input type="password" name="password"></td> <?php if (form_error('password')) { # code... echo "<td>".form_error('password')."</td>"; }?> </tr> <tr><td><input type="submit" name="submit" value="submit"></td></tr> </table> </form> </body> </html><file_sep>/views/list.php <body> <table border=1 align="center"> <th>USERNAME</th><th>PASSWORD</th> <?php for ($i=0; $i < count($this->session->userdata('user')); $i++) { # code... echo"<tr><td>". $this->session->userdata('user')[$i]."</td><td>".$this->session->userdata('pass')[$i]."</td></tr>"; } ?> </table> <form action="<?php echo base_url()?>index.php/C_login/Logout" method="POST"> <input type="submit" name="logout" value="logout"> </form> <form action="<?php echo base_url();?>/index.php/C_login/tambah" method="POST"> <table> <tr><h1> UBAH DATA</h1></tr> <tr><td>USERNAME</td><td><input type="text" name="username"></td> </tr> <tr><td>PASSWORD</td><td><input type="<PASSWORD>" name="password"></td> </tr> <tr><td><input type="submit" name="submit" value="submit"></td></tr> </table> </form> </body> </html>
d8e72a15f08d226959ac645c04181052e2e6a330
[ "PHP" ]
4
PHP
WebLanjut41-02/praktikum-1-frznst-1
909cb36c852f85dc62b656f2462abf9766c1e232
ee0038331c0602b2f565880624d1bbb5cb8be7eb
refs/heads/master
<repo_name>quanon/bitcoinrb<file_sep>/spec/bitcoin/ext_key_spec.rb require 'spec_helper' # BIP-32 test # https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Test_Vectors describe Bitcoin::ExtKey, network: :mainnet do describe 'Test Vector 1' do before do @master_key = Bitcoin::ExtKey.generate_master('000102030405060708090a0b0c0d0e0f') end it 'Chain m' do expect(@master_key.depth).to eq(0) expect(@master_key.number).to eq(0) expect(@master_key.fingerprint).to eq('3442193e') expect(@master_key.chain_code.bth).to eq('873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508') expect(@master_key.priv).to eq('<KEY>') expect(@master_key.addr).to eq('<KEY>') expect(@master_key.pub).to eq('0339a36013301597daef41fbe593a02cc513d0b55527ec2df1050e2e8ff49c85c2') expect(@master_key.hash160).to eq('3442193e1bb70916e914552172cd4e2dbc9df811') expect(@master_key.to_base58).to eq('<KEY>') expect(@master_key.ext_pubkey.to_base58).to eq('<KEY>') expect(@master_key.ext_pubkey.pub).to eq('0339a36013301597daef41fbe593a02cc513d0b55527ec2df1050e2e8ff49c85c2') expect(@master_key.ext_pubkey.hash160).to eq('3442193e1bb70916e914552172cd4e2dbc9df811') expect(@master_key.ext_pubkey.addr).to eq('<KEY>') end it 'Chain m/0H' do key = @master_key.derive(2**31) expect(key.depth).to eq(1) expect(key.hardened?).to be true expect(key.fingerprint).to eq('5c1bd648') expect(key.chain_code.bth).to eq('47fdacbd0f1097043b78c63c20c34ef4ed9a111d980047ad16282c7ae6236141') expect(key.priv).to eq('edb2e14f9ee77d26dd93b4ecede8d16ed408ce149b6cd80b0715a2d911a0afea') expect(key.pub).to eq('<KEY>') expect(key.addr).to eq('<KEY>') expect(key.segwit_addr).to eq('<KEY>') expect(key.to_base58).to eq('<KEY>') expect(key.ext_pubkey.to_base58).to eq('<KEY>') expect(key.ext_pubkey.segwit_addr).to eq('<KEY>') expect(key.ext_pubkey.hardened?).to be true end it 'Chain m/0H/1' do key = @master_key.derive(2**31).derive(1) expect(key.depth).to eq(2) expect(key.hardened?).to be false expect(key.fingerprint).to eq('bef5a2f9') expect(key.chain_code.bth).to eq('2a7857631386ba23dacac34180dd1983734e444fdbf774041578e9b6adb37c19') expect(key.priv).to eq('<KEY>') expect(key.to_base58).to eq('<KEY>') expect(key.ext_pubkey.to_base58).to eq('<KEY>') # pubkey derivation ext_pubkey = @master_key.derive(2**31).ext_pubkey.derive(1) expect(ext_pubkey.to_base58).to eq('<KEY>') expect(key.ext_pubkey.hardened?).to be false end it 'Chain m/0H/1/2H' do key = @master_key.derive(2**31).derive(1).derive(2**31 + 2) expect(key.depth).to eq(3) expect(key.hardened?).to be true expect(key.fingerprint).to eq('ee7ab90c') expect(key.chain_code.bth).to eq('04466b9cc<KEY>') expect(key.priv).to eq('cbce0d719ecf7431d88e6a89fa1483e02e35092af60c042b1df2ff59fa424dca') expect(key.to_base58).to eq('<KEY>') expect(key.ext_pubkey.to_base58).to eq('<KEY>') expect(key.ext_pubkey.hardened?).to be true end it 'Chain m/0H/1/2H/2' do key = @master_key.derive(2**31).derive(1).derive(2**31 + 2).derive(2) expect(key.depth).to eq(4) expect(key.hardened?).to be false expect(key.fingerprint).to eq('d880d7d8') expect(key.chain_code.bth).to eq('cfb71883f01676f587d023cc53a35bc7f88f724b1f8c2892ac1275ac822a3edd') expect(key.priv).to eq('<KEY>') expect(key.to_base58).to eq('<KEY>') expect(key.ext_pubkey.to_base58).to eq('<KEY>') expect(key.ext_pubkey.hardened?).to be false end it 'Chain m/0H/1/2H/2/1000000000' do key = @master_key.derive(2**31).derive(1).derive(2**31 + 2).derive(2).derive(1000000000) expect(key.depth).to eq(5) expect(key.hardened?).to be false expect(key.fingerprint).to eq('d69aa102') expect(key.chain_code.bth).to eq('c783e67b921d2beb8f6b389cc646d7263b4145701dadd2161548a8b078e65e9e') expect(key.priv).to eq('471b76e389e528d6de6d816857e012c5455051cad6660850e58372a6c3e6e7c8') expect(key.to_base58).to eq('<KEY>') expect(key.ext_pubkey.to_base58).to eq('<KEY>') expect(key.ext_pubkey.hardened?).to be false end end describe 'Test Vector 2' do before do @master_key = Bitcoin::ExtKey.generate_master('<KEY>') end it 'Chain m' do expect(@master_key.depth).to eq(0) expect(@master_key.number).to eq(0) expect(@master_key.to_base58).to eq('<KEY>') expect(@master_key.ext_pubkey.to_base58).to eq('<KEY>') end it 'Chain m/0' do key = @master_key.derive(0) expect(key.depth).to eq(1) expect(key.hardened?).to be false expect(key.number).to eq(0) expect(key.to_base58).to eq('<KEY>') expect(key.ext_pubkey.to_base58).to eq('<KEY>') expect(key.ext_pubkey.hardened?).to be false end it 'Chain m/0/2147483647H' do key = @master_key.derive(0).derive(2**31 + 2147483647) expect(key.depth).to eq(2) expect(key.hardened?).to be true expect(key.number).to eq(2**31 + 2147483647) expect(key.to_base58).to eq('<KEY>') expect(key.ext_pubkey.to_base58).to eq('<KEY>') expect(key.ext_pubkey.hardened?).to be true end it 'Chain m/0/2147483647H/1' do key = @master_key.derive(0).derive(2**31 + 2147483647).derive(1) expect(key.depth).to eq(3) expect(key.hardened?).to be false expect(key.number).to eq(1) expect(key.to_base58).to eq('<KEY>') expect(key.ext_pubkey.to_base58).to eq('<KEY>') expect(key.ext_pubkey.hardened?).to be false end it 'Chain m/0/2147483647H/1/2147483646H' do key = @master_key.derive(0).derive(2**31 + 2147483647).derive(1).derive(2**31 + 2147483646) expect(key.depth).to eq(4) expect(key.hardened?).to be true expect(key.number).to eq(2**31 + 2147483646) expect(key.to_base58).to eq('<KEY>') expect(key.ext_pubkey.to_base58).to eq('<KEY>') expect(key.ext_pubkey.hardened?).to be true end it 'Chain m/0/2147483647H/1/2147483646H/2' do key = @master_key.derive(0).derive(2**31 + 2147483647).derive(1).derive(2**31 + 2147483646).derive(2) expect(key.depth).to eq(5) expect(key.hardened?).to be false expect(key.number).to eq(2) expect(key.to_base58).to eq('<KEY>') expect(key.ext_pubkey.to_base58).to eq('<KEY>') ext_pubkey = @master_key.derive(0).derive(2**31 + 2147483647).derive(1).derive(2**31 + 2147483646).ext_pubkey.derive(2) expect(ext_pubkey.to_base58).to eq('<KEY>') expect(key.ext_pubkey.hardened?).to be false end end describe 'import from base58 address' do it 'import private key' do # normal key key = Bitcoin::ExtKey.from_base58('<KEY>') expect(key.depth).to eq(2) expect(key.number).to eq(1) expect(key.chain_code.bth).to eq('2a7857631386ba23dacac34180dd1983734e444fdbf774041578e9b6adb37c19') expect(key.priv).to eq('<KEY>') expect(key.ext_pubkey.to_base58).to eq('<KEY>') # hardended key key = Bitcoin::ExtKey.from_base58('<KEY>') expect(key.depth).to eq(3) expect(key.number).to eq(2**31 + 2) expect(key.fingerprint).to eq('ee7ab90c') expect(key.chain_code.bth).to eq('<KEY>') expect(key.priv).to eq('cbce0d719ecf7431d88e6a89fa1483e02e35092af60c042b1df2ff59fa424dca') expect(key.to_base58).to eq('<KEY>') expect(key.ext_pubkey.to_base58).to eq('<KEY>') end it 'import public key' do # normal key key = Bitcoin::ExtPubkey.from_base58('<KEY>') expect(key.depth).to eq(2) expect(key.number).to eq(1) expect(key.chain_code.bth).to eq('2a7857631386ba23dacac34180dd1983734e444fdbf774041578e9b6adb37c19') expect(key.to_base58).to eq('<KEY>') expect(key.pubkey).to eq('<KEY>') # hardended key key = Bitcoin::ExtPubkey.from_base58('<KEY>') expect(key.depth).to eq(3) expect(key.number).to eq(2**31 + 2) expect(key.fingerprint).to eq('ee7ab90c') expect(key.chain_code.bth).to eq('<KEY>') expect(key.pubkey).to eq('<KEY>') end end describe 'pubkey hardended derive' do it 'should raise error' do key = Bitcoin::ExtPubkey.from_base58('<KEY>') expect{key.derive(2**31)}.to raise_error('hardened key is not support') end end end <file_sep>/lib/openassets/marker_output.rb module OpenAssets module MarkerOutput # whether this output is marker output for open assets. def open_assets_marker? return false unless script_pubkey.op_return? payload = Payload.parse_from_payload(script_pubkey.op_return_data) !payload.nil? end end end <file_sep>/lib/bitcoin/wallet/base.rb require 'leveldb' module Bitcoin module Wallet class Base attr_accessor :wallet_id attr_reader :db attr_reader :path DEFAULT_PATH_PREFIX = "#{Bitcoin.base_dir}/db/wallet/" VERSION = 1 # Create new wallet. If wallet already exist, throw error. # The wallet generates a seed using SecureRandom and store to db at initialization. # @param [String] wallet_id new wallet id. # @param [String] path_prefix wallet file path prefix. # @return [Bitcoin::Wallet::Base] the wallet def self.create(wallet_id = 1, path_prefix = DEFAULT_PATH_PREFIX) raise ArgumentError, "wallet_id : #{wallet_id} already exist." if self.exist?(wallet_id, path_prefix) w = self.new(wallet_id, path_prefix) # generate seed raise RuntimeError, 'the seed already exist.' if w.db.registered_master? master = Bitcoin::Wallet::MasterKey.generate w.db.register_master_key(master) w.create_account('Default') w end # load wallet with specified +wallet_id+ # @return [Bitcoin::Wallet::Base] the wallet def self.load(wallet_id, path_prefix = DEFAULT_PATH_PREFIX) raise ArgumentError, "wallet_id : #{wallet_id} dose not exist." unless self.exist?(wallet_id, path_prefix) self.new(wallet_id, path_prefix) end # get wallets path # @return [Array] Array of paths for each wallet dir. def self.wallet_paths(path_prefix = DEFAULT_PATH_PREFIX) Dir.glob("#{path_prefix}wallet*/").sort end # get current wallet def self.current_wallet(path_prefix = DEFAULT_PATH_PREFIX) path = wallet_paths.first # TODO default wallet selection return nil unless path wallet_id = path.delete(path_prefix + '/wallet').delete('/').to_i self.load(wallet_id, path_prefix) end # get account list based on BIP-44 def accounts db.accounts.map do |raw| a = Account.parse_from_payload(raw) a.wallet = self a end end def create_account(purpose = Account::PURPOSE_TYPE[:nested_witness], index = 0, name) account = Account.new(purpose, index, name) account.wallet = self account.init account end # get wallet version. def version db.version end # close database wallet def close db.close end # get master key # @return [Bitcoin::Wallet::MasterKey] def master_key db.master_key end # encrypt wallet # @param [String] passphrase the wallet passphrase def encrypt(passphrase) end # decrypt wallet # @param [String] passphrase the wallet passphrase def decrypt(passphrase) end private def initialize(wallet_id, path_prefix) @path = "#{path_prefix}wallet#{wallet_id}/" @db = Bitcoin::Wallet::DB.new(@path) @wallet_id = wallet_id end def self.exist?(wallet_id, path_prefix) path = "#{path_prefix}wallet#{wallet_id}" Dir.exist?(path) end end end end <file_sep>/lib/bitcoin/ext_key.rb module Bitcoin # Integers modulo the order of the curve(secp256k1) CURVE_ORDER = 115792089237316195423570985008687907852837564279074904382605163141518161494337 # BIP32 Extended private key class ExtKey attr_accessor :depth attr_accessor :number attr_accessor :chain_code attr_accessor :key attr_accessor :parent_fingerprint # generate master key from seed. # @params [String] seed a seed data with hex format. def self.generate_master(seed) ext_key = ExtKey.new ext_key.depth = ext_key.number = 0 ext_key.parent_fingerprint = '00000000' l = Bitcoin.hmac_sha512('Bitcoin seed', seed.htb) left = l[0..31].bth.to_i(16) raise 'invalid key' if left >= CURVE_ORDER || left == 0 ext_key.key = Bitcoin::Key.new(priv_key: l[0..31].bth) ext_key.chain_code = l[32..-1] ext_key end # get ExtPubkey from priv_key def ext_pubkey k = ExtPubkey.new k.depth = depth k.number = number k.parent_fingerprint = parent_fingerprint k.chain_code = chain_code k.pubkey = key.pubkey k end # serialize extended private key def to_payload Bitcoin.chain_params.extended_privkey_version.htb << [depth].pack('C') << parent_fingerprint.htb << [number].pack('N') << chain_code << [0x00].pack('C') << key.priv_key.htb end # Base58 encoded extended private key def to_base58 h = to_payload.bth hex = h + Bitcoin.calc_checksum(h) Base58.encode(hex) end # get private key(hex) def priv key.priv_key end # get public key(hex) def pub key.pubkey end def hash160 Bitcoin.hash160(pub) end # get address def addr key.to_p2pkh end # get segwit p2wpkh address def segwit_addr ext_pubkey.segwit_addr end # get key identifier def identifier Bitcoin.hash160(key.pubkey) end # get fingerprint def fingerprint identifier.slice(0..7) end # whether hardened key. def hardened? number >= 2**31 end # derive new key def derive(number) new_key = ExtKey.new new_key.depth = depth + 1 new_key.number = number new_key.parent_fingerprint = fingerprint if number > (2**31 -1) data = [0x00].pack('C') << key.priv_key.htb << [number].pack('N') else data = key.pubkey.htb << [number].pack('N') end l = Bitcoin.hmac_sha512(chain_code, data) left = l[0..31].bth.to_i(16) raise 'invalid key' if left >= CURVE_ORDER child_priv = (left + key.priv_key.to_i(16)) % CURVE_ORDER raise 'invalid key ' if child_priv >= CURVE_ORDER new_key.key = Bitcoin::Key.new(priv_key: child_priv.to_s(16).rjust(64, '0')) new_key.chain_code = l[32..-1] new_key end # import private key from Base58 private key address def self.from_base58(address) data = StringIO.new(Base58.decode(address).htb) ext_key = ExtKey.new data.read(4).bth # version ext_key.depth = data.read(1).unpack('C').first ext_key.parent_fingerprint = data.read(4).bth ext_key.number = data.read(4).unpack('N').first ext_key.chain_code = data.read(32) data.read(1) # 0x00 ext_key.key = Bitcoin::Key.new(priv_key: data.read(32).bth) ext_key end end # BIP-32 Extended public key class ExtPubkey attr_accessor :depth attr_accessor :number attr_accessor :chain_code attr_accessor :pubkey # hex format attr_accessor :parent_fingerprint # serialize extended pubkey def to_payload Bitcoin.chain_params.extended_pubkey_version.htb << [depth].pack('C') << parent_fingerprint.htb << [number].pack('N') << chain_code << pub.htb end def pub pubkey end def hash160 Bitcoin.hash160(pub) end # get address def addr Bitcoin::Key.new(pubkey: pubkey).to_p2pkh end # get segwit p2wpkh address def segwit_addr hash160 = Bitcoin.hash160(pub) p2wpkh = [ ["00", "14", hash160].join ].pack("H*").bth segwit_addr = Bech32::SegwitAddr.new segwit_addr.hrp = Bitcoin.chain_params.address_version == '00' ? 'bc' : 'tb' segwit_addr.script_pubkey = p2wpkh segwit_addr.addr end # get key identifier def identifier Bitcoin.hash160(pub) end # get fingerprint def fingerprint identifier.slice(0..7) end # Base58 encoded extended pubkey def to_base58 h = to_payload.bth hex = h + Bitcoin.calc_checksum(h) Base58.encode(hex) end # whether hardened key. def hardened? number >= 2**31 end # derive child key def derive(number) new_key = ExtPubkey.new new_key.depth = depth + 1 new_key.number = number new_key.parent_fingerprint = fingerprint raise 'hardened key is not support' if number > (2**31 -1) data = pub.htb << [number].pack('N') l = Bitcoin.hmac_sha512(chain_code, data) left = l[0..31].bth.to_i(16) raise 'invalid key' if left >= CURVE_ORDER p1 = Bitcoin::Secp256k1::GROUP.generator.multiply_by_scalar(left) p2 = Bitcoin::Key.new(pubkey: pubkey).to_point new_key.pubkey = ECDSA::Format::PointOctetString.encode(p1 + p2, compression: true).bth new_key.chain_code = l[32..-1] new_key end # import pub key from Base58 private key address def self.from_base58(address) data = StringIO.new(Base58.decode(address).htb) ext_pubkey = ExtPubkey.new data.read(4).bth # version ext_pubkey.depth = data.read(1).unpack('C').first ext_pubkey.parent_fingerprint = data.read(4).bth ext_pubkey.number = data.read(4).unpack('N').first ext_pubkey.chain_code = data.read(32) ext_pubkey.pubkey = data.read(33).bth ext_pubkey end end end <file_sep>/spec/bitcoin/wallet/wallet_spec.rb require 'spec_helper' describe Bitcoin::Wallet do describe '#load' do context 'existing wallet' do subject { wallet = create_test_wallet wallet.close Bitcoin::Wallet::Base.load(1, TEST_WALLET_PATH) } it 'should return wallet' do expect(subject.wallet_id).to eq(1) expect(subject.path).to eq(test_wallet_path(1)) expect(subject.version).to eq(Bitcoin::Wallet::Base::VERSION) end end context 'dose not exist wallet' do it 'should raise error' do expect{Bitcoin::Wallet::Base.load(2, TEST_WALLET_PATH)}.to raise_error(ArgumentError) end end end describe '#create' do context 'should create new wallet' do subject {Bitcoin::Wallet::Base.create(2, TEST_WALLET_PATH)} it 'should be create' do expect(subject.wallet_id).to eq(2) expect(subject.master_key.mnemonic.size).to eq(24) expect(subject.version).to eq(Bitcoin::Wallet::Base::VERSION) end after{ subject.close FileUtils.rm_r(test_wallet_path(2)) } end context 'same wallet_id already exist' do it 'should raise error' do expect{Bitcoin::Wallet::Base.create(1, TEST_WALLET_PATH)}.to raise_error(ArgumentError) end end end describe '#wallets_path' do subject { Bitcoin::Wallet::Base.wallet_paths(TEST_WALLET_PATH) } it 'should return wallet dir.' do expect(subject[0]).to eq("#{TEST_WALLET_PATH}wallet1/") end end describe '#create_account' do subject { wallet = create_test_wallet(3) wallet.create_account('hoge') wallet.accounts } it 'should be created' do expect(subject.size).to eq(2) expect(subject[0].purpose).to eq(49) expect(subject[0].index).to eq(0) expect(subject[0].name).to eq('Default') expect(subject[0].receive_depth).to eq(10) receive_keys = subject[0].derived_receive_keys expect(receive_keys.size).to eq(10) expect(receive_keys[0].hardened?).to be false expect(subject[0].change_depth).to eq(10) change_keys = subject[0].derived_change_keys expect(change_keys.size).to eq(10) expect(change_keys[0].hardened?).to be false expect(subject[0].lookahead).to eq(10) expect(subject[1].name).to eq('hoge') expect(subject[1].index).to eq(1) end end end <file_sep>/lib/bitcoin/rpc.rb module Bitcoin module RPC autoload :HttpServer, 'bitcoin/rpc/http_server' autoload :RequestHandler, 'bitcoin/rpc/request_handler' end end <file_sep>/spec/bitcoin/rpc/request_handler_spec.rb require 'spec_helper' describe Bitcoin::RPC::RequestHandler do class HandlerMock include Bitcoin::RPC::RequestHandler attr_reader :node def initialize(node) @node = node end end let(:chain) { load_chain_mock } let(:wallet) { create_test_wallet } subject { node_mock = double('node mock') allow(node_mock).to receive(:chain).and_return(chain) allow(node_mock).to receive(:pool).and_return(load_pool_mock(node_mock.chain)) allow(node_mock).to receive(:broadcast).and_return(nil) allow(node_mock).to receive(:wallet).and_return(wallet) HandlerMock.new(node_mock) } after { chain.db.close wallet.close } describe '#getblockchaininfo' do it 'should return chain info' do result = subject.getblockchaininfo expect(result[:chain]).to eq('testnet') expect(result[:headers]).to eq(1210339) expect(result[:bestblockhash]).to eq('00000000ecae98e551fde86596f9e258d28edefd956f1e6919c268332804b668') expect(result[:mediantime]).to eq(1508126989) end end describe '#getblockheader' do it 'should return header info' do result = subject.getblockheader('00000000fb0350a72d7316a2006de44e74c16b56843a29bd85e0535d71edbc5b', true) expect(result[:hash]).to eq('00000000fb0350a72d7316a2006de44e74c16b56843a29bd85e0535d71edbc5b') expect(result[:height]).to eq(1210337) expect(result[:version]).to eq(536870912) expect(result[:versionHex]).to eq('20000000') expect(result[:merkleroot]).to eq('ac92cbb5ccd160f9b474f27a1ed50aa9f503b4d39c5acd7f24ef0a6a0287c7c6') expect(result[:time]).to eq(1508130596) expect(result[:mediantime]).to eq(1508125317) expect(result[:nonce]).to eq(1647419287) expect(result[:bits]).to eq('1d00ffff') expect(result[:previousblockhash]).to eq('00000000cd01007346f9a3d384a507f97afb164c057bcd1694ca20bb3302bb8d') expect(result[:nextblockhash]).to eq('000000008f71fb3f76a19075987a5d5653efce9bab90474497c9e1151ac94b69') header = subject.getblockheader('00000000fb0350a72d7316a2006de44e74c16b56843a29bd85e0535d71edbc5b', false) expect(header).to eq('000000208dbb0233bb20ca9416cd7b054c16fb7af907a584d3a3f946730001cd00000000c6c787026a0aef247fcd5a9cd3b403f5a90ad51e7af274b4f960d1ccb5cb92ac243fe459ffff001d979f3162') end end describe '#getpeerinfo' do it 'should return connected peer info' do result = subject.getpeerinfo expect(result.length).to eq(2) expect(result[0][:id]). to eq(1) expect(result[0][:addr]). to eq('192.168.0.1:18333') expect(result[0][:addrlocal]). to eq('192.168.0.3:18333') expect(result[0][:services]). to eq('000000000000000c') expect(result[0][:relaytxes]). to be false expect(result[0][:lastsend]). to eq(1508305982) expect(result[0][:lastrecv]). to eq(1508305843) expect(result[0][:bytessent]). to eq(31298) expect(result[0][:bytesrecv]). to eq(1804) expect(result[0][:conntime]). to eq(1508305774) expect(result[0][:pingtime]). to eq(0.593433) expect(result[0][:minping]). to eq(0.593433) expect(result[0][:version]). to eq(70015) expect(result[0][:subver]). to eq('/Satoshi:0.14.1/') expect(result[0][:inbound]). to be false expect(result[0][:startingheight]). to eq(1210488) expect(result[0][:best_hash]). to eq(-1) expect(result[0][:best_height]). to eq(-1) end end describe '#sendrawtransaction' do it 'should return txid' do raw_tx = '0100000001b827a4b3edeb56a5598e22c1a54205de3b9c6b749fbfdb6a494bd1cb550cc93f000000006b483045022100aedbe7fa2f0dff58222d15665471266ff539bf1285b0ce69b22ae030d13535f602206d1272f2437e2e8c5185d59dc51a8169b0fb61b8a7aaa9576a878e8a4baafbe8012103fd8474629e95865deff1b8d72004055b03a87714d8288e33330f2b0a966f46b8ffffffff01adfcdf07000000001976a914f38f47c0b9de955bb9aca788525a8281ed50973b88ac00000000' expect(subject.sendrawtransaction(raw_tx)).to eq('dfbf28c96d21bb7f2c3fb278c7cfa85a4b68874db29327dd930aeb31efbe70cb') end end describe '#createwallet' do before { path = test_wallet_path(3) FileUtils.rm_r(path) if Dir.exist?(path) } after { path = test_wallet_path(3) FileUtils.rm_r(path) if Dir.exist?(path) } it 'should be create new wallet' do result = subject.createwallet(3, TEST_WALLET_PATH) expect(result[:wallet_id]).to eq(3) expect(result[:mnemonic].size).to eq(24) end end describe '#listwallets' do it 'should return wallet list.' do result = subject.listwallets(TEST_WALLET_PATH) expect(result[0]).to eq(test_wallet_path(1)) end end describe '#getwalletinfo' do context 'node has no wallet.' do subject { node_mock = double('node mock') allow(node_mock).to receive(:wallet).and_return(nil) HandlerMock.new(node_mock) } it 'should return empty hash' do expect(subject.getwalletinfo).to eq({}) end end context 'node has wallet.' do it 'should return current wallet data' do result = subject.getwalletinfo expect(result[:wallet_id]).to eq(1) expect(result[:version]).to eq(Bitcoin::Wallet::Base::VERSION) end end end private def load_entry(payload, height) header = Bitcoin::BlockHeader.parse_from_payload(payload.htb) Bitcoin::Store::ChainEntry.new(header, height) end def load_chain_mock chain_mock = create_test_chain latest_entry = load_entry('00000020694bc91a15e1c997444790ab9bceef53565d7a987590a1763ffb718f0000000024fe00f0aa7507e54a4a586be1ea7c7d9e077e049e08a8e397da4a4c1a02d14b8d48e459ffff001dc735461c', 1210339) allow(chain_mock).to receive(:latest_block).and_return(latest_entry) # recent 11 block allow(chain_mock).to receive(:find_entry_by_hash).with('00000000ecae98e551fde86596f9e258d28edefd956f1e6919c268332804b668').and_return(latest_entry) allow(chain_mock).to receive(:find_entry_by_hash).with('000000008f71fb3f76a19075987a5d5653efce9bab90474497c9e1151ac94b69').and_return(load_entry('000000205bbced715d53e085bd293a84566bc1744ee46d00a216732da75003fb00000000a0f199af05f22972246d9a380130e498f03df945f482718ee0787ca6dad24808d843e459ffff001d983d2926', 1210338)) allow(chain_mock).to receive(:find_entry_by_hash).with('00000000fb0350a72d7316a2006de44e74c16b56843a29bd85e0535d71edbc5b').and_return(load_entry('000000208dbb0233bb20ca9416cd7b054c16fb7af907a584d3a3f946730001cd00000000c6c787026a0aef247fcd5a9cd3b403f5a90ad51e7af274b4f960d1ccb5cb92ac243fe459ffff001d979f3162', 1210337)) allow(chain_mock).to receive(:find_entry_by_hash).with('00000000cd01007346f9a3d384a507f97afb164c057bcd1694ca20bb3302bb8d').and_return(load_entry('0000002080244a62f307b3b885a253a3614a3fe6e78de3895512d6e8d44d65aa00000000d1574450981c63e36214035a38aeb1d9fa582bac452ac178c75e9dd8efdf9fd9733ae459ffff001d051759a0', 1210336)) allow(chain_mock).to receive(:find_entry_by_hash).with('00000000aa654dd4e8d6125589e38de7e63f4a61a353a285b8b307f3624a2480').and_return(load_entry('00000020426410aa5fcdca74b3598160417f9e2c986edc8fb8633b7f6000000000000000c928ae0f8ed48979bfbdf851ca8a49198731b8e8830139217043e004ce76881bc235e459ffff001d6496f136', 1210335)) allow(chain_mock).to receive(:find_entry_by_hash).with('00000000000000607f3b63b88fdc6e982c9e7f41608159b374cacd5faa106442').and_return(load_entry('00000020f91653ebd7535d498a3cd62db46e939b676a04ae6a35e33f418c0e1800000000b47bfeae2b2201b7b86f34e948099788cfd5ae7fdf1b8fe51bb2651a85946a510d31e45980e17319eee6f292', 1210334)) allow(chain_mock).to receive(:find_entry_by_hash).with('00000000180e8c413fe3356aae046a679b936eb42dd63c8a495d53d7eb5316f9').and_return(load_entry('00000020cd931c47b454b2d67a99e380cd051f33d316263548748bdee5a6b3ec0000000035c824c91f310d2b19b772fba5f0fcd9e9e8d0f189e47f5064fc7770ef0957bc362fe459ffff001d13beb4a8', 1210333)) allow(chain_mock).to receive(:find_entry_by_hash).with('00000000ecb3a6e5de8b7448352616d3331f05cd80e3997ad6b254b4471c93cd').and_return(load_entry('00000020949c2f5f9083dd4ec45b2c26c28ca701c0f640d62e52551b4b000000000000009305fca54fae340d5b2c9dceb8a559443d5cfb44504bc939820984cbb26b1e2d852ae459ffff001d6babc9be', 1210332)) allow(chain_mock).to receive(:find_entry_by_hash).with('000000000000004b1b55522ed640f6c001a78cc2262c5bc44edd83905f2f9c94').and_return(load_entry('0000002046194705aa7b0aca636c5a45a3c8857640cddaaab27e44cbc43f5d7f00000000439414cce8f17b94cf2ef654cc96f85e87b5f0a5c615ae474151e02b8ea9f3cdd125e45980e17319eb2ea570', 1210331)) allow(chain_mock).to receive(:find_entry_by_hash).with('000000007f5d3fc4cb447eb2aadacd407685c8a3455a6c63ca0a7baa05471946').and_return(load_entry('000000206984d6f872f6499432f66d5bb8eec0f30248e79483382af621000000000000007246d107520e77f6b08c8d74ac0b06f4a8e229070ff95dc07b1fc477a68a0b0b7421e459ffff001d0e7bcc94', 1210330)) allow(chain_mock).to receive(:find_entry_by_hash).with('0000000000000021f62a388394e74802f3c0eeb85b6df6329449f672f8d68469').and_return(load_entry('00000020f1bd62cf4502b7f88eeae4bb8cf2caa3615caac0dde9bf064994e4350000000067f8d203143e834fd6572aef4bc961b4f9ef4d18b63d6a73ed6342403406e815bf1ce45980e173198907b9ad', 1210329)) allow(chain_mock).to receive(:find_entry_by_hash).with('0000000035e4944906bfe9ddc0aa5c61a3caf28cbbe4ea8ef8b70245cf62bdf1').and_return(load_entry('04000000587b7ec2f7b00aecadc816f74c4734f5d3b57744fa98061b2452245300000000acf407f07491f3c7e326702c84c2319b98989b1d287e612385b35f01bb49a29e7518e459ffff001d40cce489', 1210328)) allow(chain_mock).to receive(:find_entry_by_hash).with('00000000532452241b0698fa4477b5d3f534474cf716c8adec0ab0f7c27e7b58').and_return(load_entry('00000020b5b07293524eece44221a180a6c67538b5685b474015993ea9422e7600000000ae01949e6bac5a828216d89ea91fc7dfe0bee5488644c7f228e15e0b87b3322fc113e459ffff001d5ef80539', 1210327)) allow(chain_mock).to receive(:find_entry_by_hash).with('00000000762e42a93e991540475b68b53875c6a680a12142e4ec4e529372b0b5').and_return(load_entry('00000020fbf65774599e7bf53452a61f0784f30159ffa98e4bfa7091624bb3760000000012e5e283f096b9c14669c38049f4012462f48adb7d7d5e6dc32f3576688ef5480c0fe459ffff001dabe97de2', 1210326)) # previous block allow(chain_mock).to receive(:next_hash).with('00000000fb0350a72d7316a2006de44e74c16b56843a29bd85e0535d71edbc5b').and_return('000000008f71fb3f76a19075987a5d5653efce9bab90474497c9e1151ac94b69') chain_mock end def load_pool_mock(chain) conn1 = double('connection_mock1') conn2 = double('connection_mock1') allow(conn1).to receive(:version).and_return(Bitcoin::Message::Version.new( version: 70015, user_agent: '/Satoshi:0.14.1/', start_height: 1210488, remote_addr: '192.168.0.3:60519', services: 12 )) allow(conn2).to receive(:version).and_return(Bitcoin::Message::Version.new) configuration = Bitcoin::Node::Configuration.new(network: :testnet) pool = Bitcoin::Network::Pool.new(chain, configuration) peer1 =Bitcoin::Network::Peer.new('192.168.0.1', 18333, pool, configuration) peer1.id = 1 peer1.last_send = 1508305982 peer1.last_recv = 1508305843 peer1.bytes_sent = 31298 peer1.bytes_recv = 1804 peer1.conn_time = 1508305774 peer1.last_ping = 1508386048 peer1.last_pong = 1508979481 allow(peer1).to receive(:conn).and_return(conn1) pool.peers << peer1 peer2 =Bitcoin::Network::Peer.new('192.168.0.2', 18333, pool, configuration) peer2.id = 2 allow(peer2).to receive(:conn).and_return(conn2) pool.peers << peer2 pool end end<file_sep>/lib/bitcoin/message/filter_load.rb module Bitcoin module Message # filterload message # https://bitcoin.org/en/developer-reference#filterload class FilterLoad < Base COMMAND = 'filterload' BLOOM_UPDATE_NONE = 0 BLOOM_UPDATE_ALL = 1 BLOOM_UPDATE_P2PUBKEY_ONLY = 2 attr_accessor :filter # bin format attr_accessor :func_count attr_accessor :tweak attr_accessor :flag def initialize(filter, func_count, tweak = 0, flag = BLOOM_UPDATE_ALL) @filter = filter @func_count = func_count @tweak = tweak @flag = flag end def self.parse_from_payload(payload) buf = StringIO.new(payload) filter_count = Bitcoin.unpack_var_int_from_io(buf) filter = buf.read(filter_count).unpack('C*') func_count = buf.read(4).unpack('V').first tweak = buf.read(4).unpack('V').first flag = buf.read(1).unpack('C').first new(filter, func_count, tweak, flag) end def to_payload Bitcoin.pack_var_int(filter.size) << filter.pack('C*') << [func_count, tweak, flag].pack('VVC') end end end end <file_sep>/spec/bitcoin/network/pool_spec.rb require 'spec_helper' describe Bitcoin::Network::Pool do describe '#allocate_peer_id' do let (:chain) { create_test_chain } subject { configuration = Bitcoin::Node::Configuration.new pool = Bitcoin::Network::Pool.new(chain, configuration) peer1 = Bitcoin::Network::Peer.new('192.168.0.1', 18333, pool, configuration) peer2 = Bitcoin::Network::Peer.new('192.168.0.2', 18333, pool, configuration) peer3 = Bitcoin::Network::Peer.new('192.168.0.3', 18333, pool, configuration) allow(peer1).to receive(:start_block_header_download).and_return(nil) allow(peer2).to receive(:start_block_header_download).and_return(nil) allow(peer3).to receive(:start_block_header_download).and_return(nil) pool.handle_new_peer(peer1) pool.handle_new_peer(peer2) pool.handle_new_peer(peer3) pool } after { chain.db.close } it 'should allocate peer id' do expect(subject.peers.size).to eq(3) expect(subject.peers[0].id).to eq(0) expect(subject.peers[1].id).to eq(1) expect(subject.peers[2].id).to eq(2) end end end<file_sep>/spec/bitcoin/store/spv_chain_spec.rb require 'spec_helper' require 'tmpdir' require 'fileutils' describe Bitcoin::Store::SPVChain do let (:chain) { create_test_chain } subject { chain } after { chain.db.close } describe '#append_header' do context 'correct header' do it 'should store data' do genesis = subject.latest_block expect(genesis.height).to eq(0) expect(genesis.header).to eq(Bitcoin.chain_params.genesis_block.header) expect(subject.next_hash('000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943')).to be nil next_header = Bitcoin::BlockHeader.parse_from_payload('0100000043497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000bac8b0fa927c0ac8234287e33c5f74d38d354820e24756ad709d7038fc5f31f020e7494dffff001d03e4b672'.htb) subject.append_header(next_header) block = subject.latest_block expect(block.height).to eq(1) expect(block.header).to eq(next_header) expect(subject.next_hash('000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943')).to eq('00000000b873e79784647a6c82962c70d228557d24a747ea4d1b8bbe878e1206') end end context 'invalid header' do it 'should raise error' do # pow is invalid next_header = Bitcoin::BlockHeader.parse_from_payload('0100000043497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000bac8b0fa927c0ac8234287e33c5f74d38d354820e24756ad709d7038fc5f31f020e7494dffff001d03e4b672'.htb) next_header.nonce = 1 expect{subject.append_header(next_header)}.to raise_error(StandardError) # previous hash mismatch next_header = Bitcoin::BlockHeader.parse_from_payload('0100000006128e87be8b1b4dea47a7247d5528d2702c96826c7a648497e773b800000000e241352e3bec0a95a6217e10c3abb54adfa05abb12c126695595580fb92e222032e7494dffff001d00d23534'.htb) expect{subject.append_header(next_header)}.to raise_error(StandardError) end end end end <file_sep>/lib/bitcoin/wallet/account.rb module Bitcoin module Wallet # the account in BIP-44 class Account PURPOSE_TYPE = {legacy: 44, nested_witness: 49} attr_reader :purpose # either 44 or 49 attr_reader :index # BIP-44 index attr_reader :name # account name attr_accessor :receive_depth # receive address depth(address index) attr_accessor :change_depth # change address depth(address index) attr_accessor :lookahead attr_accessor :wallet def initialize(purpose = PURPOSE_TYPE[:nested_witness], index = 0, name = '') @purpose = purpose @index = index @name = name @receive_depth = 0 @change_depth = 0 @lookahead = 10 end def self.parse_from_payload(payload) name, payload = Bitcoin.unpack_var_string(payload) name = name.force_encoding('utf-8') purpose, index, receive_depth, change_depth, lookahead = payload.unpack('I*') a = Account.new(purpose, index, name) a.receive_depth = receive_depth a.change_depth = change_depth a.lookahead = lookahead a end def to_payload payload = Bitcoin.pack_var_string(name.unpack('H*').first.htb) payload << [purpose, index, receive_depth, change_depth, lookahead].pack('I*') payload end # whether support witness def witness? purpose == PURPOSE_TYPE[:nested_witness] end def init @receive_depth = lookahead @change_depth = lookahead @index = wallet.accounts.size save end # derive receive key def derive_receive(address_index) derive_key(0, address_index) end # derive change key def derive_change(address_index) derive_key(1, address_index) end # save this account payload to database. def save wallet.db.save_account(self) end # get the list of derived keys for receive key. def derived_receive_keys receive_depth.times.map{|i|derive_key(0,i)} end # get the list of derived keys for change key. def derived_change_keys change_depth.times.map{|i|derive_key(1,i)} end private def derive_key(branch, address_index) account_key.derive(branch).derive(address_index) end def account_key return @cached_account_key if @cached_account_key coin_type = Bitcoin.chain_params.bip44_coin_type # m / purpose' / coin_type' / account_index' @cached_account_key = wallet.master_key.key.derive(2**31 + purpose).derive(2**31 + coin_type).derive(2**31 + index) end end end end <file_sep>/lib/bitcoin/util.rb # Porting part of the code from bitcoin-ruby. see the license. # https://github.com/lian/bitcoin-ruby/blob/master/COPYING module Bitcoin # bitcoin utility. # following methods can be used as follows. # Bitcoin.pack_var_int(5) module Util def pack_var_string(payload) pack_var_int(payload.bytesize) + payload end def unpack_var_string(payload) size, payload = unpack_var_int(payload) size > 0 ? payload.unpack("a#{size}a*") : [nil, payload] end def pack_var_int(i) if i < 0xfd [i].pack('C') elsif i <= 0xffff [0xfd, i].pack('Cv') elsif i <= 0xffffffff [0xfe, i].pack('CV') elsif i <= 0xffffffffffffffff [0xff, i].pack('CQ') else raise "int(#{i}) too large!" end end def unpack_var_int(payload) case payload.unpack('C').first when 0xfd payload.unpack('xva*') when 0xfe payload.unpack('xVa*') when 0xff payload.unpack('xQa*') else payload.unpack('Ca*') end end def unpack_var_int_from_io(buf) uchar = buf.read(1).unpack('C').first case uchar when 0xfd buf.read(2).unpack('v').first when 0xfe buf.read(4).unpack('V').first when 0xff buf.read(8).unpack('Q').first else uchar end end def pack_boolean(b) b ? [0xFF].pack('C') : [0x00].pack('C') end def unpack_boolean(payload) data, payload = payload.unpack('Ca*') [(data.zero? ? false : true), payload] end def sha256(payload) Digest::SHA256.digest(payload) end def double_sha256(payload) sha256(sha256(payload)) end # byte convert to the sequence of bits packed eight in a byte with the least significant bit first. def byte_to_bit(byte) byte.unpack('b*').first end # generate sha256-ripemd160 hash for value def hash160(hex) Digest::RMD160.hexdigest(Digest::SHA256.digest(hex.htb)) end def encode_base58_address(hex, addr_version) base = addr_version + hex Base58.encode(base + calc_checksum(base)) end def calc_checksum(hex) double_sha256(hex.htb).bth[0..7] end DIGEST_NAME_SHA256 = 'sha256' def hmac_sha256(key, data) OpenSSL::HMAC.digest(DIGEST_NAME_SHA256, key, data) end end end <file_sep>/spec/bitcoin/wallet/account_spec.rb require 'spec_helper' describe Bitcoin::Wallet::Account do describe '#parse_from_payload' do subject { Bitcoin::Wallet::Account.parse_from_payload('09e38386e382b9e38388310000000a000000110000000f0000000a000000'.htb) } it 'generate account instance' do expect(subject.purpose).to eq(49) expect(subject.index).to eq(10) expect(subject.name).to eq('テスト') expect(subject.receive_depth).to eq(17) expect(subject.change_depth).to eq(15) expect(subject.lookahead).to eq(10) expect(subject.witness?).to be true expect(subject.to_payload.bth).to eq('09e38386e382b9e38388310000000a000000110000000f0000000a000000') end end describe 'bip-49 key derivation' do subject { words = %w(abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about) master_key = Bitcoin::Wallet::MasterKey.recover_from_words(words) wallet = double('wallet') db = double('walletdb') allow(wallet).to receive(:accounts).and_return([]) allow(wallet).to receive(:master_key).and_return(master_key) allow(wallet).to receive(:db).and_return(db) allow(db).to receive(:save_account) account = Bitcoin::Wallet::Account.new account.wallet = wallet account.init account } it 'should derive key' do expect(subject.send(:account_key).to_base58).to eq('<KEY>') expect(subject.derived_receive_keys.first.priv).to eq('<KEY>') end end end<file_sep>/lib/bitcoin/script_witness.rb module Bitcoin # witness class ScriptWitness attr_reader :stack def initialize(stack = []) @stack = stack end def empty? stack.empty? end def to_payload p = Bitcoin.pack_var_int(stack.size) p << stack.map { |s| Bitcoin.pack_var_int(s.bytesize) << s }.join end def to_s stack.map{|s|s.bth}.join(' ') end end end<file_sep>/lib/bitcoin/node/cli.rb require 'rest-client' require 'thor' require 'json' module Bitcoin module Node class CLI < Thor class_option :network, aliases: '-n', default: :mainnet desc 'getblockchaininfo', 'Returns an object containing various state info regarding blockchain processing.' def getblockchaininfo request('getblockchaininfo') end desc 'stop', 'Stop Bitcoin server.' def stop request('stop') end desc 'getblockheader "hash" ( verbose )', 'If verbose is false, returns a string that is serialized, hex-encoded data for blockheader "hash". If verbose is true, returns an Object with information about blockheader <hash>.' def getblockheader(hash, verbose = true) verbose = verbose.is_a?(String) ? (verbose == 'true') : verbose request('getblockheader', hash, verbose) end desc 'getpeerinfo', 'Returns data about each connected network node as a json array of objects.' def getpeerinfo request('getpeerinfo') end desc 'sendrawtransaction', 'Submits raw transaction (serialized, hex-encoded) to local node and network.' def sendrawtransaction(hex_tx) request('sendrawtransaction', hex_tx) end desc 'createwallet "wallet_id"', 'Create new HD wallet. It returns an error if an existing wallet_id is specified. ' def createwallet(wallet_id) request('createwallet', wallet_id) end desc 'listwallets', 'Returns a list of currently loaded wallets. For full information on the wallet, use "getwalletinfo"' def listwallets request('listwallets') end desc 'getwalletinfo', 'Returns an object containing various wallet state info.' def getwalletinfo request('getwalletinfo') end private def config opts = {} opts[:network] = options['network'] if options['network'] @conf ||= Bitcoin::Node::Configuration.new(opts) end def request(command, *params) data = { :method => command, :params => params, :id => 'jsonrpc' } begin RestClient::Request.execute(method: :post, url: config.server_url, payload: data.to_json, headers: {content_type: :json}) do |response, request, result| return false if !result.kind_of?(Net::HTTPSuccess) && response.empty? begin json = JSON.parse(response.to_str) puts JSON.pretty_generate(json) rescue Exception puts response.to_str end end rescue Exception => e puts e.message end end end end end <file_sep>/lib/bitcoin/rpc/request_handler.rb module Bitcoin module RPC # RPC server's request handler. module RequestHandler # Returns an object containing various state info regarding blockchain processing. def getblockchaininfo h = {} h[:chain] = Bitcoin.chain_params.network best_block = node.chain.latest_block h[:headers] = best_block.height h[:bestblockhash] = best_block.hash h[:chainwork] = best_block.header.work h[:mediantime] = node.chain.mtp(best_block.hash) h end # shutdown node def stop node.shutdown end # get block header information. def getblockheader(hash, verbose) entry = node.chain.find_entry_by_hash(hash) if verbose { hash: hash, height: entry.height, version: entry.header.version, versionHex: entry.header.version.to_s(16), merkleroot: entry.header.merkle_root, time: entry.header.time, mediantime: node.chain.mtp(hash), nonce: entry.header.nonce, bits: entry.header.bits.to_s(16), previousblockhash: entry.prev_hash, nextblockhash: node.chain.next_hash(hash) } else entry.header.to_payload.bth end end # Returns connected peer information. def getpeerinfo node.pool.peers.map do |peer| local_addr = peer.remote_version.remote_addr[0..peer.remote_version.remote_addr.rindex(':')] + '18333' { id: peer.id, addr: "#{peer.host}:#{peer.port}", addrlocal: local_addr, services: peer.remote_version.services.to_s(16).rjust(16, '0'), relaytxes: peer.remote_version.relay, lastsend: peer.last_send, lastrecv: peer.last_recv, bytessent: peer.bytes_sent, bytesrecv: peer.bytes_recv, conntime: peer.conn_time, pingtime: peer.ping_time, minping: peer.min_ping, version: peer.remote_version.version, subver: peer.remote_version.user_agent, inbound: !peer.outbound?, startingheight: peer.remote_version.start_height, best_hash: peer.best_hash, best_height: peer.best_height } end end # broadcast transaction def sendrawtransaction(hex_tx) tx = Bitcoin::Tx.parse_from_payload(hex_tx.htb) # TODO check wether tx is valid node.broadcast(tx) tx.txid end # wallet api # create wallet def createwallet(wallet_id = 1, wallet_path_prefix = Bitcoin::Wallet::Base::DEFAULT_PATH_PREFIX) wallet = Bitcoin::Wallet::Base.create(wallet_id, wallet_path_prefix) node.wallet = wallet unless node.wallet {wallet_id: wallet.wallet_id, mnemonic: wallet.master_key.mnemonic} end # get wallet list. def listwallets(wallet_path_prefix = Bitcoin::Wallet::Base::DEFAULT_PATH_PREFIX) Bitcoin::Wallet::Base.wallet_paths(wallet_path_prefix) end # get current wallet information. def getwalletinfo return {} unless node.wallet {wallet_id: node.wallet.wallet_id, version: node.wallet.version} end end end end
8220f05a7696a322ab3cbfd33cae2fdf762d74a6
[ "Ruby" ]
16
Ruby
quanon/bitcoinrb
375695d69533db5f7073b5824694b3e7bb3ae6b9
f40e37220da7c6301fe372b07b92d2a122853bc3
refs/heads/master
<file_sep><?php interface travailler { public function travailler(); } ?><file_sep><?php interface action { public function affichage(); } ?><file_sep><?php require_once 'vivants.php'; require_once 'affichage.php'; class animal extends vivant implements action { private $_race; private $_pates; private $_cri; const chien = 'chien'; const chat = 'chat'; public function __construct($couleur, $sexe, $nom, $pates, $race) { parent::__construct($couleur, $sexe, $nom); if($pates >= 0 && $pates <= 20) { $this->_pates = $pates; } if(in_array($race, [self::chien, self::chat])) { $this->_race = $race; } } public function affichage() { $type_cri; $this->_race = 'chien' ? $type_cri = 'aboyer' : $type_cri = 'miauler'; echo 'je vais ' . $type_cri; } public function cri() { $type_cri; $this->_race = 'chien' ? $type_cri = 'aboyer' : $type_cri = 'miauler'; echo $type_cri; } } ?><file_sep><?php class humain extends vivant implements travailler { private $_bla; public function __construct($couleur, $sexe, $nom, $bla) { parent::__construct($couleur, $sexe, $nom); $this->_bla = $bla; } public function travailler() { echo "je taffe"; } public function affichage() { $type = $this->get_sexe(); $type = 'H' ? $type = "L'homme" : $type = 'La femme'; echo $type . ' ' . $this->get_nom() . ' ' . $this->get_color() .' va travailler'; } } ?><file_sep><?php include_once 'animal.php'; include_once 'robot.php'; include_once 'vivants.php'; include_once 'travailler.php'; include_once 'humain.php'; //$seb = new humain('rouge', 'H', 'seb','yo'); // $seb->affichage(); function op() { $k = 0; $x = 0; $animaux = array(); $personne = array(); for ($i=0; $i < 8 ; $i++) { $j = rand(1,3); $couleur = rand(1,3); $sexe = rand(1,2); switch($couleur) { case 1: $couleur = "rouge"; break; case 2: $couleur = "noir"; break; case 3: $couleur = "bleu"; break; default: trigger_error('je ne comprends pas'); break; } if($sexe == 1) { $sexe = 'F'; } else { $sexe = 'M'; } switch ($j) { case 1: $pet[$i] = new animal($couleur, $sexe, 'nom'.$i, 4, 'chien' ); $animaux[$k] = $pet[$i]; $k++; break; case 2: $pet[$i] = new animal($couleur, $sexe, 'nom'.$i, 4, 'chat' ); $animaux[$k] = $pet[$i]; $k++; break; case 3: $humain[$i] = new humain($couleur, $sexe, 'nom'.$i, 'yo' ); $personne[$x] = $humain[$i]; $x++; break; case 1: $robot[$i] = new robot($i, $couleur); $personne[$x] = $robot[$i]; $x++; break; default: trigger_error('je ne comprends pas'); break; } } action($animaux, $personne); } function action(array $animaux, array $personne) { // var_dump($animaux); // var_dump($personne); for ($x=0; $x < 10 ; $x++) { $i = rand(0, (count($animaux) -1)); $j = rand(0, (count($personne) -1)); if(empty($animaux) == false) echo $animaux[$i]->cri() . '<br>'; if(empty($personne) == false) echo $personne[$j]->travailler() . '<br>'; } } op(); ?><file_sep><?php class listes{ private $name; public function first(){ } } ?><file_sep><?php require 'travailler.php'; class robot implements travailler, action { private $_color; private $_id; public function __construct($id, $color) { $this->$_id = $id; $this->$_color = $color; } public function travailler() { echo "je taffe"; } public function affichage() { echo $_id . ' '. $_color . ' va travailler'; } public function get_id() { return $this->_id; } } ?><file_sep><?php class maillons{ private $_value; private $_next = null; public function __construct($valeur, $liste){ $this->_value = $valeur; $this->_liste = $liste; } public function set_value($value){ $this->_value = $value; } public function set_next($next){ $this->_next = $next; } public function get_next(){ return $this->_next->get_value(); } public function get_value(){ return $this->_value; } } $m1 = new maillons(1,'x'); $m2 = new maillons(4,'x'); $m3 = new maillons(2,'x'); $m1->set_next($m2); $m1->get_next(); ?> <file_sep><?php require_once 'affichage.php'; class vivant { private $_couleur_poils; private $_sexe; private $_nom; const F = 'F'; const M = 'M'; public function __construct($couleur, $sexe, $nom) { $this->_couleur_poils = $couleur; $this->_nom = $nom; if(in_array($sexe, [self::F, self::M])) { $this->_sexe = $sexe; } } public function get_color() { return $this->_couleur_poils; } public function get_sexe() { return $this->_sexe; } public function get_nom() { return $this->_nom; } }
829cd20123fa9a926692884d37b78bf7edf94672
[ "PHP" ]
9
PHP
nartco/Jeu_poo_php
67ffad2a6d752afadb2ed481f7ada0bcedb3f545
f79218b7e92bde7f0670b6a2d1d6207e0338d98c
refs/heads/master
<repo_name>krisss85/gcp-python-playground<file_sep>/instances.py import googleapiclient.discovery import json import pandas as pd def list_instances(compute, project, zone): result = compute.instances().list(project=project, zone=zone).execute() return result['items'] def main(project, zone): compute = googleapiclient.discovery.build('compute', 'v1') instances = list_instances(compute, project, zone) table = [] for instance in instances: #print [m['value'] for m in instance['metadata']['items'] if m['key'] == 'dataproc-bucket'] key_value = filter(lambda x: x['key'] == 'dataproc-bucket', instance['metadata']['items']) table.append({'hostname': instance['name'], 'metadata': key_value[0]['value']}) json_payload = json.dumps(table, ensure_ascii=False, encoding="utf-8") results = pd.read_json(json_payload) print results #my_list = [x for x in my_list if x.attribute == value] #my_list = filter(lambda x: x.attribute == value, my_list)<file_sep>/README.md # gcp-python-playground
18e0bc01b50c68d9e21d51b0b6afca4f0e33db7a
[ "Markdown", "Python" ]
2
Python
krisss85/gcp-python-playground
d00453bfe4733307bff0714fe6f3d3184360f8c1
cdc7f49831e894884a6358442428f45cadd7e16d
refs/heads/dev
<file_sep>Find bounding box around the polygon ==================================== Find bounding box around the polygon [![CircleCI](https://circleci.com/gh/dostolu/boundingbox.svg?style=svg)](https://circleci.com/gh/dostolu/boundingbox)<file_sep>/** * Get the bounding square around the polygon * @param {Object} polygon * @param {Number} fixed - numbers after decimal * @returns {{left: Number, top: Number, right: Number, bottom: Number}} */ module.exports = (polygon, fixed = 4) => { const sq = { left: undefined, top: undefined, right: undefined, bottom: undefined }; polygon.map(parts => parts.map(coords => { const x = coords[0]; const y = coords[1]; if (x < sq.left || undefined === sq.left) sq.left = x; else if (x > sq.right || undefined === sq.right) sq.right = x; if (y < sq.bottom || undefined === sq.bottom) sq.bottom = y; else if (y > sq.top || undefined === sq.top) sq.top = y; })); sq.left = sq.left.toFixed(fixed); sq.top = sq.top.toFixed(fixed); sq.right = sq.right.toFixed(fixed); sq.bottom = sq.bottom.toFixed(fixed); return sq; }; <file_sep>/* eslint-disable no-undef */ const { expect } = require('chai'); const sq2po = require('./index.js'); const polygonFixture = [[ [1, 2], [3, 4], [5, 6], [7, 8] ], [ [5, 6], [7, 8], [9, 10] ], [ [2, 4], [1, 3], [5, 8] ]]; const expectedSquare = { left: '1', top: '10', right: '9', bottom: '2' }; describe('Polygon to square', () => { it('should return proper values for square within the random polygon', () => { expect(expectedSquare).to.be.deep.equal(sq2po(polygonFixture, 0)); }); });
33ce468cb94cc6d3a84692e1e05a3ee8c3f1b231
[ "Markdown", "JavaScript" ]
3
Markdown
dostolu/boundingbox
d8266bc7820466ff621b7b453d91c4a90f765253
8c614b779f39ea6878d56e0c64a98b52114cf75b
refs/heads/main
<file_sep>import React, { useEffect, useState } from "react"; import { Link, Redirect, withRouter } from "react-router-dom"; import { useTranslation } from "react-i18next"; import logo from "../../assets/logo-Toma.png"; import i18n from "i18n"; import NavBar from "./NavBar"; import * as path from "constants/routes"; import "./style.scss"; const AuthSystemWrapp = (props) => { const { t } = useTranslation(); const [language, setLanguage] = useState( localStorage.getItem("i18nextLng") || "en" ); useEffect(() => { i18n.changeLanguage(language); }, [language]); const handleLanguageChange = (value) => { localStorage.setItem("i18nextLng", value); setLanguage(value); i18n.changeLanguage(language); }; const default_route = ( <div className="container_sign_buttons"> <Link to="/sign_up"> <button className="primary_button">{t("Sign Up")}</button> </Link> <Link to="/sign_in"> <button className="primary_button">{t("Sign In")}</button> </Link>{" "} </div> ); const content = ( <div className="auth"> <div className="auth_wrapp"> <div className="auth_left_wrapp"> <div> <img src={logo} alt="" /> </div> </div> <div className="auth_right_wrapp"> {props.children || default_route} <div className="language_container"> <h2 className="language_header">{t("Language")}:</h2> <p onClick={() => handleLanguageChange("ua")} className={`language_content ${ language === "ua" ? "bold" : null }`} > {t("Ukraine")} </p> <p onClick={() => handleLanguageChange("ru")} className={`language_content ${ language === "ru" ? "bold" : null }`} > {t("Russian")} </p> <p onClick={() => handleLanguageChange("en")} className={`language_content ${ language === "en" ? "bold" : null }`} > {t("English")} </p> </div> </div> </div> </div> ); return window.localStorage.getItem("forHeader") ? ( <Redirect to="procedures" /> ) : ( content ); }; export default withRouter(AuthSystemWrapp); <file_sep>import React from "react"; import Navbar from "./Navbar"; import Footer from "./Footer"; import "./style.scss"; import { Redirect } from "react-router"; const ProceduresWrapp = (props) => { const proceduresWrapp = ( <div className="bg-white"> <Navbar /> {props.children} <Footer /> </div> ); return window.localStorage.getItem("forHeader") ? ( proceduresWrapp ) : ( <Redirect to="/" /> ); }; export default ProceduresWrapp; <file_sep>import logo from "../assets/logo-Toma.png"; import { useTranslation } from "react-i18next"; export const error = (t) => { return ( <div style={{ height: "100vh", width: "100vw", display: "flex", alignItems: "center", justifyContent: "center", }} > <div style={{ height: "200px", width: "300px" }}> {t("Error from backend. Tamara will fix it soon")} </div> </div> ); }; export const loading = ( <div style={{ height: "100vh", width: "100vw", display: "flex", alignItems: "center", justifyContent: "center", }} > <div style={{ height: "200px", width: "200px" }}> <img src={logo} alt="" /> </div> </div> ); <file_sep>import React from "react"; import instLogo from "../../assets/inst-icon.png"; import { useTranslation } from "react-i18next"; const Footer = () => { const { t } = useTranslation(); return ( <div className="footer"> <span style={{ color: "white", marginRight: "10px" }}> {t("Subscribe Me in Instagram")} </span> <a target="_blank" href="https://www.instagram.com/talking_toma"> <img src={instLogo} alt="" /> </a> </div> ); }; export default Footer; <file_sep>import React, { useEffect, useState } from "react"; import { Icon, Label, Menu, Table, Loader } from "semantic-ui-react"; import { detail_procedures, detail_patient } from "../../../constants/config"; import { API } from "../../../api/APIOptions"; import ProceduresWrapp from "../index"; import { error } from "../../../utils/index"; import { useTranslation } from "react-i18next"; const ProceduresList = () => { const { t } = useTranslation(); const header = window.localStorage.getItem("forHeader"); const [links, setLinks] = useState(null); const [noMore, setNoMore] = useState(false); const [procedures, setProcedures] = useState({ data: [], loading: false, error: false, }); const handleAddProcedures = () => { setProcedures({ ...procedures, loading: true }); API.get(links.next, header) .then((response) => response.json()) .then((result) => { setLinks(result.links); const patientsId = []; for (let i = 0; i < result.data.length; i++) { patientsId.push(result.data[i].relationships.patient.data.id); } return Promise.all( patientsId.map((id) => API.get(`${detail_patient}/${id}`, header).then((response) => response.json() ) ) ); }) .then((result) => { if (result.length == 0) { setNoMore(true); return; } setProcedures({ ...procedures, loading: false, data: [...procedures.data, ...result], }); }) .catch((e) => setProcedures({ ...procedures, error: true })); }; console.log(noMore); useEffect(() => { API.get(detail_procedures, header) .then((response) => response.json()) .then((result) => { setLinks(result.links); const patientsId = []; for (let i = 0; i < result.data.length; i++) { patientsId.push(result.data[i].relationships.patient.data.id); } return Promise.all( patientsId.map((id) => API.get(`${detail_patient}/${id}`, header).then((response) => response.json() ) ) ); }) .then((result) => { setProcedures({ ...procedures, data: [...result], loading: false, }); }); }, []); if (procedures.error) { return error(t); } return ( <ProceduresWrapp> <div className="procedures_list_wrapp"> <Table celled> <Table.Header> <Table.Row> <Table.HeaderCell>{t("Name")}</Table.HeaderCell> <Table.HeaderCell>{t("Last Name")}</Table.HeaderCell> <Table.HeaderCell>{t("Birthday")}</Table.HeaderCell> <Table.HeaderCell>{t("Country")}</Table.HeaderCell> <Table.HeaderCell>{t("City")}</Table.HeaderCell> <Table.HeaderCell>{t("Passport ID")}</Table.HeaderCell> <Table.HeaderCell>{t("Email")}</Table.HeaderCell> <Table.HeaderCell>{t("Phone")}</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> {procedures?.data?.map((item) => ( <Table.Row> <Table.Cell>{item.data.attributes.name}</Table.Cell> <Table.Cell>{item.data.attributes.last_name}</Table.Cell> <Table.Cell>{item.data.attributes.b_day}</Table.Cell> <Table.Cell>{item.data.attributes.country}</Table.Cell> <Table.Cell>{item.data.attributes.city}</Table.Cell> <Table.Cell>{item.data.attributes.passport_id}</Table.Cell> <Table.Cell>{item.data.attributes.email}</Table.Cell> <Table.Cell>{item.data.attributes.phone}</Table.Cell> </Table.Row> ))} </Table.Body> </Table> {procedures.data?.length > 100 || noMore ? null : ( <div className="loader_container"> {procedures.loading ? null : ( <button onClick={() => handleAddProcedures()} className="primary_button" > {t("Load more")} </button> )} <Loader active={procedures.loading} /> </div> )} </div> </ProceduresWrapp> ); }; export default ProceduresList; <file_sep>import React from "react"; import AuthSystemWrapp from "./pages/AuthSystem/index"; import SignIn from "./pages/AuthSystem/SignIn/index"; import SignUp from "./pages/AuthSystem/SignUp/index"; import * as path from "constants/routes"; import { Switch, Route, Link } from "react-router-dom"; import "./App.css"; import ProceduresList from "pages/Procedures/ProceduresList/index"; import CreateProcedure from "pages/Procedures/CreateProcedure"; function App() { const APP_ROUTES = [ { id: "1", path: "/", component: AuthSystemWrapp }, { id: "2", path: path.SIGN_UP, component: SignUp }, { id: "3", path: path.SIGN_IN, component: SignIn }, { id: "4", path: path.PROCEDURES, component: ProceduresList }, { id: "5", path: path.CREATE_PROCEDURE, component: CreateProcedure }, // { id: "6", path: path.VERIFICATION, component: Verification }, ]; return ( <Switch> {APP_ROUTES.map((route) => ( <Route exact key={route.id} path={route.path} component={route.component} /> ))} </Switch> ); } export default App; <file_sep>import React from "react"; import { Link, Redirect, withRouter } from "react-router-dom"; import signOut from "../../assets/sign-out.svg"; import logo from "../../assets/logo-Toma.png"; import * as path from "../../constants/routes"; import { useTranslation } from "react-i18next"; const Navbar = (props) => { const { t } = useTranslation(); return ( <div className="header"> <div className="header_container"> <img className="header_logo" src={logo} alt="" /> <div> <Link to={path.PROCEDURES}> <button style={{ width: "auto", height: "auto" }} className="primary_button" > {t("Procedures list")} </button> </Link> <Link to={path.CREATE_PROCEDURE}> <button style={{ width: "auto", height: "auto" }} className="primary_button" > {t("Create New Procedure")} </button> </Link> </div> <Link to="/"> <div onClick={() => { if (window.localStorage.getItem("forHeader")) { window.localStorage.removeItem("forHeader"); } }} style={{ display: "flex", alignItems: "center" }} > <img src={signOut} alt="" /> <span className="header_signout">{t("Sign out")}</span> </div> </Link> </div> </div> ); }; export default Navbar; <file_sep>import React, { useState } from "react"; import { Input, Icon } from "semantic-ui-react"; export const CustomInput = (props) => { const { type, label, icon, placeholder, onBlur, onChange, value, style, defaultValue, className, maxLength, field, // { name, value, onChange, onBlur } form, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc. wrappStyles, customOnChange, pattern, } = props; const [showPass, togglePass] = useState(false); const isInvalid = form && form.touched[field.name] && form.errors[field.name]; const showFieldType = type === "password" ? !showPass ? "password" : showPass ? "text" : "text" : type; const withIcon = icon && { iconPosition: "left", icon, }; return ( <div className="w-100 position-relative" style={wrappStyles ? { ...wrappStyles } : { padding: "0 0 20px 0" }} > {label && ( <div className="d-flex justify-content-between align-items-center"> <label className="d-block">{label}</label> </div> )} <div className="position-relative"> <Input {...field} type={showFieldType} placeholder={placeholder} onChange={(e) => customOnChange ? customOnChange(e) : form ? form.setFieldValue(field.name, e.target.value) : onChange(e) } value={value} defaultValue={defaultValue} className={isInvalid ? `error-field ${className}` : className} onBlur={onBlur} maxLength={maxLength} style={{ ...style }} pattern={pattern} {...withIcon} /> {type === "password" && ( <Icon name={showPass ? "eye slash" : "eye"} size="large" onClick={() => togglePass(!showPass)} /> )} </div> <div className="error-field text-left" style={{ opacity: isInvalid ? 1 : 0, transition: "0.3s all" }} > {form.errors[field.name]} </div> </div> ); }; <file_sep>export const URL = "http://localhost:8000/api"; export const WS_URL = ""; export const endpointSignUp = "/data/signup"; export const endpointSignIn = "/data/signin"; export const detail_procedures = "/data/procedures"; export const detail_patient = "/data/patients"; <file_sep>import React, { useState } from "react"; import { Link, Redirect, withRouter } from "react-router-dom"; import { Formik, Form, Field } from "formik"; import { Button } from "semantic-ui-react"; import { API } from "../../../api/APIOptions"; import { endpointSignUp } from "../../../constants/config"; import token from "basic-auth-token"; import * as Yup from "yup"; import { error, loading } from "../../../utils/index"; import { useTranslation } from "react-i18next"; import { CustomInput } from "../../../components/Forms/CustomInput"; import AuthSystemWrapp from "../index"; import * as path from "constants/routes"; const SignUp = (props) => { const [signOut, setSignOut] = useState({ loading: false, error: false, }); const { t } = useTranslation(); const phoneRegExp = /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/; const SignupSchema = Yup.object().shape({ // email: Yup.string() // .email(t("E-mail is not valid!")) // .required(t("E-mail is required!")), name: Yup.string().required(t("Name is required!")), city: Yup.string().required(t("City is required!")), country: Yup.string().required(t("Country is required!")), phone: Yup.string() .matches(phoneRegExp, t("Phone is incorrect!")) .required(t("Phone is required!")), address: Yup.string().required(t("Address is required!")), password1: Yup.string() .min(8, t(`Password has to be longer than 8 characters!`)) .required(t("Password is required!")), password2: Yup.string() .min(8) .oneOf([Yup.ref("password1"), null], t("Password doesn't match")) .required(t("Password confirm is required")), }); const handleSubmit = async (form, data) => { setSignOut({ ...signOut, loading: true }); API.post(endpointSignUp, { data: { type: "hospitals", attributes: { email: form.email, password_hashed: <PASSWORD>, city: form.city, country: form.country, name: form.name, phone: form.phone, address: form.address, }, }, }) .then((response) => response.json()) .then((result) => { if (result.data.id.length) { window.localStorage.setItem( "forHeader", `Basic ${token(form.email, form.password)}` ); window.localStorage.setItem("id", result.data.id); props.history.push(path.PROCEDURES); setSignOut({ ...signOut, loading: false }); } }) .catch((e) => { setSignOut({ ...signOut, error: true }); console.log(e); }); }; if (signOut.error) { return error(t); } if (signOut.loading) { return loading; } return ( <AuthSystemWrapp> <div className="sign_in_wrapp"> <h1>{t("Sign Up")}</h1> <Formik initialValues={{ email: "<EMAIL>", password1: "<EMAIL>", password2: "<EMAIL>", city: "<EMAIL>", country: "<EMAIL>", name: "<EMAIL>", phone: "<EMAIL>", address: "<EMAIL>", }} onSubmit={(form, data) => handleSubmit(form, data)} validationSchema={SignupSchema} > {({ values, touched, errors, setFieldValue }) => ( <Form> <div style={{ display: "flex" }}> <div style={{ width: "50%", marginRight: "10px" }}> <Field label={t("Name")} name="name" component={CustomInput} placeholder={t("Your Name")} value={values.name} /> <Field label={t("Email")} name="email" type="email" component={CustomInput} placeholder="<EMAIL>" value={values.email} /> <Field label={t("Password")} name="password1" type="password" component={CustomInput} placeholder={t("New Password")} value={values.password1} /> <Field label={t("Password")} name="password2" type="password" component={CustomInput} placeholder={t("New Password")} value={values.password2} /> </div> <div style={{ width: "50%" }}> <Field label={t("Country")} name="country" component={CustomInput} placeholder={t("Your country")} value={values.country} /> <Field label={t("City")} name="city" component={CustomInput} placeholder={t("Your city")} value={values.city} /> <Field label={t("Address")} name="address" component={CustomInput} placeholder="Your address" value={values.address} /> <Field label={t("Phone")} name="phone" component={CustomInput} placeholder="Your phone" value={values.phone} /> </div> </div> <div style={{ width: "100%", display: "flex", justifyContent: "center", }} > <Button type="submit" className="primary_button"> {t("Sign Up")} </Button> </div> </Form> )} </Formik> <div style={{ width: "100%", display: "flex", justifyContent: "center", marginTop: "10px", }} > <span style={{ fontSize: "14px" }}> {t("Already have an account?")} </span> <Link to="sign_in">{t("Sign In")}</Link> </div> </div> </AuthSystemWrapp> ); }; export default withRouter(SignUp); <file_sep>export const SIGN_UP = "/sign_up"; export const SIGN_IN = "/sign_in"; export const PROCEDURES = "/procedures"; export const CREATE_PROCEDURE = "/create_procedure"; <file_sep>import i18n from "i18next"; import { initReactI18next } from "react-i18next"; i18n.use(initReactI18next).init({ resources: { en: { translations: { "Error from backend. Tamara will fix it soon": "Error from backend. Tamara will fix it soon", "E-mail is not valid!": "E-mail is not valid!", "E-mail is required!": "E-mail is required!", "Password has to be longer than 8 characters!": "Password has to be longer than 8 characters!", "Password is required!": "Password is <PASSWORD>!", "User with specified email does not exists.": "User with specified email does not exists.", "Your password": "<PASSWORD>", "Sign In": "Sign In", "Don't have an account?": "Don't have an account?", "Sign Up": "Sign Up", "Name is required!": "Name is required!", "City is required!": "City is required!", "Country is required!": "Country is required!", "Phone is incorrect!": "Phone is incorrect!", "Phone is required!": "Phone is required!", "Address is required!": "Address is required!", "Password doesn't match": "<PASSWORD>", "Password confirm is required": "<PASSWORD> confirm <PASSWORD>", "Your Name": "Your Name", "New Password": "<PASSWORD>", "Your country": "Your country", "Your city": "Your city", "Your address": "Your address", "Your phone": "Your phone", "Already have an account?": "Already have an account?", Language: "Language", Ukraine: "Ukrainian", Russian: "Russian", English: "English", Name: "Name", Time: "Time", "Load more": "Load more", "Subscribe Me in Instagram": "Subscribe Me in Instagram", "Create New Procedure": "Create New Procedure", "Create procedure": "Create procedure", "Procedures list": "Procedures list", "Sign out": "Sign out", "Last Name": "Last Name", Email: "Email", Country: "Country", City: "City", Phone: "Phone", "Passport ID": "Passport ID", Birthday: "Birthday", Address: "Address", Password: "<PASSWORD>", }, }, ru: { translations: { "Error from backend. Tamara will fix it soon": "Ошибка с бекенда. Тамара скоро пофиксит это", "E-mail is not valid!": "Почта некорректна!", "E-mail is required!": "Почта необходима!", "Password has to be longer than 8 characters!": "Пароль должен быть длиннее 8 символов!", "Password is required!": "Пароль необходим!", "User with specified email does not exists.": "Пользователя с указанной почтой не существует", "Your password": "<PASSWORD>", "Sign In": "Войти", "Don't have an account?": "Нету аккаунта?", "Sign Up": "Зарегистрироваться", "Name is required!": "Имя необходимо!", "City is required!": "Город необходим!", "Country is required!": "Страна необходима!", "Phone is incorrect!": "Телефон некорректный!", "Phone is required!": "Телефон необходим!", "Address is required!": "Адрес необходим!", "Password doesn't match": "Пароль не совпадает", "Password confirm is required": "Подтверждение пароля необходимо", "Your Name": "Ваше имя", "New Password": "<PASSWORD>", "Your country": "Ваша страна", "Your city": "Ваш город", "Your address": "Ваш адрес", "Your phone": "Ваш телефон", "Already have an account?": "Уже есть аккаунт?", Language: "Язык", Ukraine: "Украинский", Russian: "Русский", English: "Английский", Name: "Имя", Time: "Время", "Load more": "Загрузить еще", "Subscribe Me in Instagram": "Подписуйтесь на меня в Instagram", "Create New Procedure": "Создать новую процедуру", "Create procedure": "Создать процедуру", "Procedures list": "Лист процедур", "Sign out": "Выйти", "Last Name": "Фамилия", Email: "Почта", Country: "Страна", City: "Город", Phone: "Телефон", "Passport ID": "Пасспорт ID", Birthday: "День рождения", Address: "Адрес", Password: "<PASSWORD>", }, }, ua: { translations: { "Error from backend. Tamara will fix it soon": "Помилка з бекенда. Тамара це скоро виправить", "E-mail is not valid!": "Електронна пошта недійсна!", "E-mail is required!": "Пошта необхiдна", "Password has to be longer than 8 characters!": "Пароль повинен містити більше 8 символів!", "Password is required!": "Пароль необхiден!", "User with specified email does not exists.": "Користувач із вказаною електронною адресою не існує.", "Your password": "<PASSWORD>", "Sign In": "Увійти", "Don't have an account?": "Не маєте аккаунту?", "Sign Up": "Зареєструватися", "Name is required!": "Потрібно вказати ім’я!", "City is required!": "Місто обов’язкове!", "Country is required!": "Країна обов’язкова!", "Phone is incorrect!": "Телефон неправильний!", "Phone is required!": "Телефон потрібен!", "Address is required!": "Адреса обов’язкова!", "Password doesn't match": "Пароль не збігається", "Password confirm is required": "Потрібно підтвердити пароль", "Your Name": "<NAME>", "New Password": "<PASSWORD>", "Your country": "Твоя країна", "Your city": "Твоє місто", "Your address": "Вашу адресу", "Your phone": "Ваш телефон", "Already have an account?": "Вже є аккаунт?", Language: "Мова", Ukraine: "Український", Russian: "Російська", English: "Англійська", Name: "Ім'я", Time: "Час", "Load more": "Завантажити ще", "Subscribe Me in Instagram": "Підпишіться на мене в Instagram", "Create New Procedure": "Створити нову процедуру", "Procedures list": "Лист процедур", "Create procedure": "Создати процедуру", "Sign out": "Вийти з аккаунта", "Last Name": "Прізвище", Email: "Пошта", Country: "Країна", City: "Місто", Phone: "Телефон", "Passport ID": "Паспорт ID", Birthday: "День народження", Address: "Адреса", Password: "<PASSWORD>", }, }, }, lng: window.localStorage.getItem("i18nextLng") || "en", fallbackLng: window.localStorage.getItem("i18nextLng") || "en", debug: true, ns: ["translations"], defaultNS: "translations", keySeparator: false, interpolation: { escapeValue: false, formatSeparator: ",", }, react: { wait: true, }, }); export default i18n;
ed2356a9183fdad67799284884cc1a3104bdae56
[ "JavaScript" ]
12
JavaScript
mykhayloyuminov/pet-project-procedures
89c09a747fe6250ec4c822f4d984158f9ff4eb8e
922bcbe4a84e32d7ed9fb7a02235f9b025324e3d
refs/heads/main
<file_sep> /*Final Project Milestone FP Module: TriagePatient Filename: TriagePatient.h Version 1.0 Author <NAME> Revision History ----------------------------------------------------------- I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. -----------------------------------------------------------*/ #ifndef SDDS_TRIAGE_H #define SDDS_TIRAGE_H #include <iostream> #include "Patient.h" namespace sdds { class TriagePatient: public Patient { char* m_symptoms; public: TriagePatient(); ~TriagePatient(); char type() const; std::ostream& csvWrite(std::ostream& os) const; std::istream& csvRead(std::istream& is); std::ostream& write(std::ostream& os) const; std::istream& read(std::istream& is); }; } #endif // !SDDS_ <file_sep> /*Final Project Milestone FP Module: CovidPatient Filename: CovidPatient.h Version 1.0 Author <NAME> Revision History ----------------------------------------------------------- I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. -----------------------------------------------------------*/ #ifndef SDDS_COVIDPATIENT_H_ #define SDDS_COVIDPATIENT_H_ #include <iostream> #include "Patient.h" namespace sdds { class CovidPatient: public Patient { public: CovidPatient(); char type() const; std::ostream& csvWrite(std::ostream& os) const; std::istream& csvRead(std::istream& is); std::ostream& write(std::ostream& os) const; std::istream& read(std::istream& is); }; } #endif // !SDDS_COVIDPATIENT_H_ <file_sep> /*Final Project Milestone FP Module: TriagePatient Filename: TriagePatient.cpp Version 1.0 Author <NAME> Revision History ----------------------------------------------------------- I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. -----------------------------------------------------------*/ #include <cstring> #include "TriagePatient.h" using namespace std; namespace sdds { int nextTriageTicket = 1; TriagePatient::TriagePatient(): Patient(nextTriageTicket) { m_symptoms = nullptr; nextTriageTicket++; } TriagePatient::~TriagePatient() { delete [] m_symptoms; } char TriagePatient::type() const { return 'T'; } ostream& TriagePatient::csvWrite(ostream& os) const { Patient::csvWrite(os); os << "," << m_symptoms; return os; } istream& TriagePatient::csvRead(istream& is) { delete [] m_symptoms; Patient::csvRead(is); is.ignore(2000, ','); char temp[511]; is.get(temp, 511, '\n'); m_symptoms = new char[strlen(temp)+1]; strcpy(m_symptoms, temp); nextTriageTicket = number() + 1; return is; } istream& TriagePatient::read(istream& is) { if (fileIO()) { csvRead(is); } else { delete [] m_symptoms; Patient::read(is); is.ignore(2000, '\n'); cout << "Symptoms: "; char temp[511]; is.get(temp, 511, '\n'); m_symptoms = new char[strlen(temp)+1]; strcpy(m_symptoms, temp); } return is; } ostream& TriagePatient::write(ostream& os) const { if (fileIO()) { csvWrite(os); } else { os << "TRIAGE" << endl; Patient::write(os); os << endl; os << "Symptoms: "; os << m_symptoms << endl; } return os; } } <file_sep> /*Final Project Milestone FP Module: Menu Filename: Menu.h Version 1.0 Author <NAME> Revision History ----------------------------------------------------------- I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. -----------------------------------------------------------*/ #ifndef SDDS_MENU_H_ #define SDDS_MENU_H_ #include <iostream> #include <cstring> namespace sdds { class Menu{ char* m_text; int m_noOfSel; public: Menu(const char* text, int NoOfSelections); virtual ~Menu(); Menu(const Menu&) = delete; Menu& operator=(const Menu&) = delete; std::ostream& display(std::ostream& ostr = std::cout)const; int& operator>>(int& Selection); }; } #endif // !SDDS_MENU_H_ <file_sep> /*Final Project Milestone FP Module: Time Filename: Time.cpp Version 1.0 Author <NAME> Revision History ----------------------------------------------------------- I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. -----------------------------------------------------------*/ #include "Time.h" #include "utils.h" using namespace std; namespace sdds { Time& Time::reset() { m_min = getTime(); return *this; } Time::Time(unsigned int min) { m_min = min; } ostream& Time::write(ostream& ostr) const { int hour = m_min / 60; // 2 int mins = m_min % 60; ostr.width(2); ostr.fill('0'); ostr << hour << ":"; ostr.width(2); ostr << mins; return ostr; } istream& Time::read(istream& istr) { int hour; int min; istr >> hour; char c = 'X'; istr >> c; if (c != ':') { istr.setstate(ios::failbit); } else { istr >> min; m_min = hour*60 + min; } return istr; } Time::operator int()const { return m_min; } Time& Time::operator *= (int val) { m_min *= val; return *this; } Time& Time::operator-=(const Time& D) { if (m_min < D.m_min) { m_min += 24*60; } m_min -= D.m_min; return *this; } Time Time::operator-(const Time& ROperand) { Time LOperand = *this; LOperand -= ROperand; return LOperand; } ostream& operator<<(ostream& os, const Time& t) { return t.write(os); } istream& operator>>(istream& is, Time& t) { return t.read(is); } } <file_sep> /*Final Project Milestone FP Module: IOAble Filename: IOAble.cpp Version 1.0 Author <NAME> Revision History ----------------------------------------------------------- I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. -----------------------------------------------------------*/ #ifndef SDDS_IOABLE_H_ #define SDDS_IOABLE_H_ #include <iostream> namespace sdds { class IOAble { public: virtual std::ostream& csvWrite(std::ostream& os) const = 0; virtual std::istream& csvRead(std::istream& is) = 0; virtual std::ostream& write(std::ostream& os) const = 0; virtual std::istream& read(std::istream& is) = 0; virtual ~IOAble(); }; std::ostream& operator<<(std::ostream& os, const IOAble& ioa); std::istream& operator>>(std::istream& is, IOAble& ioa); } #endif // !SDDS_IOABLE_H_ <file_sep> /*Final Project Milestone FP Module: IOAble Filename: IOAble.h Version 1.0 Author <NAME> Revision History ----------------------------------------------------------- I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. -----------------------------------------------------------*/ #include <iostream> #include "IOAble.h" using namespace std; namespace sdds { IOAble::~IOAble() { } std::ostream& operator<<(std::ostream& os, const IOAble& ioa) { return ioa.write(os); } std::istream& operator>>(std::istream& is, IOAble& ioa) { return ioa.read(is); } } <file_sep> /*Final Project Milestone FP Module: utils Filename: utils.h Version 1.0 Author <NAME> Revision History ----------------------------------------------------------- I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. -----------------------------------------------------------*/ #ifndef SDDS_UTILS_H_ #define SDDS_UTILS_H_ #include <iostream> namespace sdds { int getInt(); int getTime(); // returns the time of day in minutes extern bool debug; // this makes bool sdds::debug variable in utils.cpp global to // all the files which include: "utils.h" //(you will learn this in detail in oop345) template <typename type> void removeDynamicElement(type* array[], int index, int& size) { delete array[index]; for (int j = index; j < size; j++) { array[j] = array[j + 1]; } size--; } } #endif // !SDDS_UTILS_H_ <file_sep> /*Final Project Milestone FP Module: CovidPatient Filename: CovidPatient.cpp Version 1.0 Author <NAME> Revision History ----------------------------------------------------------- I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. -----------------------------------------------------------*/ #include "CovidPatient.h" using namespace std; namespace sdds { int nextCovidTicket = 1; CovidPatient::CovidPatient(): Patient(nextCovidTicket) { nextCovidTicket++; } char CovidPatient::type() const { return 'C'; } ostream& CovidPatient::csvWrite(ostream& os) const { return Patient::csvWrite(os); } istream& CovidPatient::csvRead(istream& is) { Patient::csvRead(is); nextCovidTicket = number()+1; return is; } ostream& CovidPatient::write(ostream& os) const { if (fileIO()) { csvWrite(os); } else { os << "COVID TEST" << endl; Patient::write(os); os << endl; } return os; } istream& CovidPatient::read(istream& is) { if (fileIO()) { csvRead(is); } else { Patient::read(is); } return is; } } <file_sep> /*Final Project Milestone FP Module: Menu Filename: Menu.cpp Version 1.0 Author <NAME> Revision History ----------------------------------------------------------- I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. -----------------------------------------------------------*/ #include "utils.h" #include "Menu.h" using namespace std; namespace sdds { Menu::Menu(const char* text, int NoOfSelections) { m_text = new char[strlen(text)+1]; strcpy(m_text, text); m_noOfSel = NoOfSelections; } Menu::~Menu() { delete [] m_text; } ostream& Menu::display(ostream& ostr) const { ostr << m_text << endl; ostr << "0- Exit" << endl; ostr << "> "; return ostr; } int& Menu::operator>>(int& Selection) { display(); bool validate = true; do { validate = true; cin >> Selection; if (cin.fail()) { cin.clear(); cout << "Bad integer value, try again: "; cin.ignore(2000, '\n'); validate = false; } else if (Selection < 0 || Selection > m_noOfSel) { cout << "Invalid value entered, retry[0 <= value <= "; cout << m_noOfSel << "]: "; validate = false; } } while(!validate); return Selection; } } <file_sep> /*Final Project Milestone FP Module: Patient Filename: Patient.h Version 1.0 Author <NAME> Revision History ----------------------------------------------------------- I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. -----------------------------------------------------------*/ #include <iostream> #include "IOAble.h" #include "Ticket.h" #ifndef SDDS_PATIENT_H_ #define SDDS_PATIENT_H_ namespace sdds { class Patient: public IOAble { char* m_patientName; int m_ohipNumber; Ticket m_ticket; bool m_fileIOFlag; public: Patient(int ticketNumber = 0, bool fileIOFlag = false); Patient(const Patient&) = delete; Patient& operator=(const Patient&) = delete; ~Patient(); virtual char type() const = 0; bool fileIO() const; void fileIO(bool fileIOFlag); bool operator==(char c) const; bool operator==(const Patient& p) const; void setArrivalTime(); operator Time()const; int number() const; std::ostream& csvWrite(std::ostream& os) const; std::istream& csvRead(std::istream& is); std::ostream& write(std::ostream& os) const; std::istream& read(std::istream& is); }; } #endif<file_sep> /*Final Project Milestone FP Module: PreTriage Filename: PreTriage.cpp Version 1.0 Author <NAME> Revision History ----------------------------------------------------------- I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. -----------------------------------------------------------*/ #include <cstring> #include <fstream> #include "Time.h" #include "PreTriage.h" #include "utils.h" #include "CovidPatient.h" #include "TriagePatient.h" using namespace std; namespace sdds { void PreTriage::reg() { if (m_lineupSize == maxNoOfPatients) { cout << "Line up full!" << endl; return; } int selection; while (m_pMenu >> selection) { switch (selection) { case 1: m_lineup[m_lineupSize] = new CovidPatient; break; case 2: m_lineup[m_lineupSize] = new TriagePatient; break; case 0: return; default: break; } m_lineup[m_lineupSize]->setArrivalTime(); cout << "Please enter patient information: " << endl; m_lineup[m_lineupSize]->fileIO(false); cin >> *m_lineup[m_lineupSize]; cout << endl << "******************************************" << endl; cout << *m_lineup[m_lineupSize]; cout << "Estimated Wait Time: "; cout << getWaitTime(*m_lineup[m_lineupSize]); cout << endl << "******************************************" << endl << endl; m_lineupSize++; break; } } void PreTriage::admit() { int selection; while (m_pMenu >> selection) { char type = 'X'; switch (selection) { case 1: type = 'C'; break; case 2: type = 'T'; break; case 0: return; } int index = indexOfFirstInLine(type); if (index == -1) { return; } cout << endl; cout << "******************************************" << endl; m_lineup[index]->fileIO(false); cout << "Calling for " << *m_lineup[index]; cout << "******************************************" << endl << endl; setAverageWaitTime(*m_lineup[index]); removePatientFromLineup(index); break; } } const Time PreTriage::getWaitTime(const Patient& p)const { for (int i=0; i<m_lineupSize; i++) { if (p.number() == m_lineup[i]->number()) { if (p.type() == 'C') { return (m_lineup[i]->number()-1) * m_averCovidWait; } else { return (m_lineup[i]->number()-1) * m_averTriageWait; } } } return Time(); } void PreTriage::setAverageWaitTime(const Patient& p) { Time awt; if (p.type() == 'C') { awt = m_averCovidWait; m_averCovidWait = ((getTime() - Time(p)) + (awt * (p.number()-1))) / p.number(); } else { awt = m_averTriageWait; m_averTriageWait = ((getTime() - Time(p)) + (awt * (p.number()-1))) / p.number(); } } void PreTriage::removePatientFromLineup(int index) { delete m_lineup[index]; m_lineup[index] = nullptr; removeDynamicElement(m_lineup, index, m_lineupSize); } void PreTriage::load() { cout << "Loading data..." << endl; ifstream ifs(m_dataFilename); if (!ifs.is_open()) { cout << "No data or bad data file!" << endl; } else { ifs >> m_averCovidWait; ifs.ignore(); ifs >> m_averTriageWait; ifs.ignore(); for (int i=0; i<maxNoOfPatients; i++) { if (ifs.eof()) { break; } char type = 'X'; ifs >> type; Patient *p = nullptr; if (type == 'C') { p = new CovidPatient; } else if (type == 'T'){ p = new TriagePatient; } else if (type == 'X') { break; } ifs.ignore(); p->fileIO(true); ifs >> *p; p->fileIO(false); m_lineup[m_lineupSize] = p; m_lineupSize++; } if (m_lineupSize == 0) { cout << "No data or bad data file!" << endl; } else { if (!ifs.eof()) { cout << "Warning: number of records exceeded " << maxNoOfPatients << endl; } cout << m_lineupSize << " Records imported..." << endl; } } if (m_lineupSize > maxNoOfPatients) { m_lineupSize = maxNoOfPatients; } cout << endl; } int PreTriage::indexOfFirstInLine(char type) const { int index = -1; for(int i=0; i<m_lineupSize; i++) { if (m_lineup[i] != nullptr) { if (m_lineup[i]->type() == type) { return i; } } } return index; } PreTriage::PreTriage(const char* dataFilename): m_appMenu("General Hospital Pre-Triage Application\n1- Register\n2- Admit", 2), m_pMenu("Select Type of Admittance:\n1- Covid Test\n2- Triage", 2) { m_averCovidWait = Time(15); m_averTriageWait = Time(5); m_dataFilename = new char[strlen(dataFilename)+1]; strcpy(m_dataFilename, dataFilename); load(); } PreTriage::~PreTriage() { ofstream ofs(m_dataFilename); cout << "Saving Average Wait Times," << endl; cout << " COVID Test: " << m_averCovidWait << endl; cout << " Triage: " << m_averTriageWait << endl; ofs << m_averCovidWait << "," << m_averTriageWait << endl; cout << "Saving m_lineup..." << endl; int rowNo = 0; for (int i=0; i<m_lineupSize; i++) { if (m_lineup[i] != nullptr) { m_lineup[i]->fileIO(true); ofs << *m_lineup[i] << endl; rowNo++; cout << rowNo << "- " << *m_lineup[i] << endl; delete m_lineup[i]; } } delete [] m_dataFilename; cout << "done!" << endl; } void PreTriage::run(void) { int selection; while (m_appMenu >> selection) { switch (selection) { case 0: return; case 1: reg(); break; case 2: admit(); break; } } } } <file_sep> /*Final Project Milestone FP Module: Patient Filename: Patient.cpp Version 1.0 Author <NAME> Revision History ----------------------------------------------------------- I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. -----------------------------------------------------------*/ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cstring> #include "Patient.h" #include "utils.h" using namespace std; namespace sdds { Patient::Patient(int ticketNumber, bool fileIOFlag): m_ticket(ticketNumber) { m_patientName = nullptr; m_ohipNumber = 0; m_fileIOFlag = fileIOFlag; } Patient::~Patient() { delete [] m_patientName; } bool Patient::fileIO() const { return m_fileIOFlag; } void Patient::fileIO(bool fileIOFlag) { m_fileIOFlag = fileIOFlag; } bool Patient::operator==(char c) const { return c == type(); } bool Patient::operator==(const Patient& p) const { return type() == p.type(); } void Patient::setArrivalTime() { m_ticket.resetTime(); } Patient::operator Time()const { return Time(m_ticket); } int Patient::number() const { return m_ticket.number(); } ostream& Patient::csvWrite(ostream& os) const { os << type(); os << ","; os << m_patientName; os << ","; os << m_ohipNumber; os << ","; m_ticket.csvWrite(os); return os; } istream& Patient::csvRead(istream& is) { char temp[51]; is.get(temp, 51, ','); delete [] m_patientName; m_patientName = new char[strlen(temp)+1]; strcpy(m_patientName, temp); is.ignore(2000, ','); is >> m_ohipNumber; is.ignore(); m_ticket.csvRead(is); return is; } ostream& Patient::write(ostream& os) const { os << m_ticket << endl; if (m_patientName[0] == '\n') { for (unsigned int i=1; i<strlen(m_patientName); i++) { m_patientName[i-1] = m_patientName[i]; } m_patientName[strlen(m_patientName)-1] = '\0'; } os << m_patientName; os << ", OHIP: "; os << m_ohipNumber; return os; } istream& Patient::read(istream& is) { cout << "Name: "; char temp[51]; is.get(temp, 51); delete [] m_patientName; m_patientName = new char[strlen(temp)+1]; strcpy(m_patientName, temp); is.ignore(2000, '\n'); cout << "OHIP: "; bool validate = true; do { validate = true; is >> m_ohipNumber; if (cin.fail()) { cin.clear(); cout << "Bad integer value, try again: "; cin.ignore(2000, '\n'); validate = false; } else if (m_ohipNumber < 100000000 || m_ohipNumber > 999999999) { cout << "Invalid value entered, retry[100000000 <= value <= 999999999]: "; validate = false; } } while(!validate); return is; } }
c97734aeb3e717a2d42db8e632014fc624e00b4b
[ "C++" ]
13
C++
thisway8788/OOP224-Final
fb61f885366e6ac8c846393b7a5a93d00bf4d8d0
7bf756c364bbcd2d17e6f1cf79919e29de7ebc95
refs/heads/master
<file_sep>package com.example.model.copy; class AnswerAnalysis { }
03dc5d51baa289727fd9a1ac4ac65d156348a3c0
[ "Java" ]
1
Java
Frankserve/Frankserve.github.io
44b88911f5350a0324d9da34f2a1ce06371a2878
61aee6a15e2d729856e09c1daf92d08dc6b72fc5
refs/heads/master
<file_sep>#include "filecreatedialog.h" #include <QLabel> #include <QHBoxLayout> #include <QVBoxLayout> #include <QString> #include <QPushButton> #include <QTextEdit> #include <QFileDialog> FileCreateDialog::FileCreateDialog(QWidget *parent) : QWidget(parent) { nameLabel = new QLabel("Имя"); dirLabel = new QLabel ("Расположение"); nameLabel -> setFixedWidth(110); dirLabel -> setFixedWidth(110); nameLabel -> setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); dirLabel -> setSizePolicy(QSizePolicy ::Fixed, QSizePolicy::Fixed); nameEdit = new QTextEdit(this); nameEdit -> setMaximumHeight(30); nameEdit -> setMinimumWidth(300); nameEdit -> setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed); dirEdit = new QTextEdit(this); dirEdit -> setMaximumHeight(30); dirEdit -> setMinimumWidth(300); dirEdit -> setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed); searchButton = new QPushButton ("Обзор"); searchButton -> setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); createButton = new QPushButton ("Создать"); createButton->setShortcut(Qt::Key_Enter); createButton -> setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); buttonLayout = new QHBoxLayout; buttonLayout -> addWidget(createButton); nameLayout = new QHBoxLayout; nameLayout -> setAlignment(Qt::AlignLeft); nameLayout -> setSpacing(4); nameLayout -> addWidget(nameLabel); nameLayout -> addWidget(nameEdit); dirLayout = new QHBoxLayout; dirLayout -> setAlignment(Qt::AlignLeft); dirLayout -> setSpacing(4); dirLayout -> addWidget(dirLabel); dirLayout -> addWidget(dirEdit); dirLayout -> addWidget(searchButton); inputLayout = new QVBoxLayout; inputLayout -> addLayout(nameLayout); inputLayout -> addLayout(dirLayout); mainLayout = new QVBoxLayout(this); mainLayout -> addLayout(inputLayout); //mainLayout -> addStretch(1); mainLayout -> addLayout(buttonLayout); //this ->setLayout(mainLayout); this-> setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Maximum); this -> setMaximumHeight(147); connect(searchButton, &QPushButton::clicked, this, &FileCreateDialog::setOnSearchDirClicked); connect(createButton, &QPushButton::clicked, this, &FileCreateDialog::setOnCreateButtonClicked); } void FileCreateDialog::setOnCreateButtonClicked(){ emit createFile(dirEdit->toPlainText(),nameEdit->toPlainText()); clean(); } void FileCreateDialog::setOnSearchDirClicked(){ dirEdit -> setPlainText( QFileDialog::getExistingDirectory (this, tr("Open Directory"), "/home", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks)); } void FileCreateDialog::clean(){ nameEdit -> setText(""); dirEdit -> setText(""); } <file_sep>#include "dictionary.h" #include <locale> #include <wchar.h> #include <ctype.h> #include <vector> #include <QTableView> #include <QModelIndex> #include <QStandardItemModel> Dictionary::Dictionary(){} void Dictionary::add(QString key){ if(dictionary.find(key)==dictionary.end()) dictionary[key] = 1; else increase(key); count++; } int Dictionary::getCount(){ return count; } void Dictionary::increase(QString key){ dictionary[key]+=1; } void Dictionary::clear(){ dictionary.clear(); } void Dictionary::createModel(QStandardItemModel * model){ QModelIndex index; model ->setColumnCount(2); model->setRowCount(dictionary.size()); model->setHeaderData(0,Qt::Horizontal, "Слово"); model->setHeaderData(1,Qt::Horizontal, "Кол-во\nвхождений"); //model->setS for(int col = 0; col< model->columnCount();col++){ auto iterator = dictionary.begin(); for(int row = 0;row < model->rowCount() && iterator!=dictionary.end();row++,iterator++){ index = model->index(row,col); if(col == 0) model->setData(index,iterator->first); if(col == 1) model->setData(index,iterator->second); } } } void Dictionary::show(QTextStream * stream, int fieldWidth){ stream->setFieldWidth(fieldWidth); stream->setFieldAlignment(QTextStream::AlignLeft); *stream<<"Word"; stream->setFieldWidth(1); *stream<<"|"; stream->setFieldWidth(fieldWidth); *stream<<"Count"; stream->setFieldWidth(1); *stream<<Qt::endl; for(auto pair:dictionary){ stream->setFieldWidth(fieldWidth); *stream<<pair.first; stream->setFieldWidth(1); *stream<<"|"; stream->setFieldWidth(fieldWidth); *stream<<pair.second; stream->setFieldWidth(1); *stream<<Qt::endl; } } void Dictionary::analyze(QString text){ QString withoutPunctuation = cleanPunctuation(text); QStringList words = withoutPunctuation.split(" ",Qt::SkipEmptyParts); for(QString word:words) this->add(word.toLower()); } int Dictionary::find(QString key){ std::map<QString,int>::iterator ptr = dictionary.find(key); if(ptr!=dictionary.end()) return ptr->second; else return 0; } QString Dictionary::cleanPunctuation(QString text){ QRegExp val("[-\t\n,.!»«—@#$%^&*-()_+?<>\\\\/;:'\"`|{}]"); QRegExp spaceSimb("[\t\n\v]"); text = text.replace(spaceSimb,QString(" ")); QString newStr = text.replace(val, QString("")); return newStr; } QString Dictionary::cleanWord(QString word){ wchar_t array [word.length()]; word.toWCharArray(array); std::vector<wchar_t> vect; for(int i=0;i<word.length();i++) vect.push_back(array[i]); // for(auto p = vect.begin(); p!=vect.end();p++){ // if (!isalphaRus(*p)) // vect.erase(p); // } wchar_t answer[vect.size()]; int i=0; for(auto p = vect.begin(); p!=vect.end();p++,i++) answer[i]=*p; return QString::fromWCharArray(answer); } <file_sep>#ifndef GREETING_H #define GREETING_H #include <QDialog> #include <QMainWindow> #include <QApplication> #include <QMenu> #include <QDialog> #include <QTextEdit> #include <QString> class QAction; class QLabel; class QCloseEvent; class Greeting : public QDialog { Q_OBJECT public: explicit Greeting(QWidget *parent = nullptr); signals: void sig_newSourse(); void sig_openSourse(); void sig_openDictList(); void indicateClosing(); void sig_template(); private slots: private: QPushButton *newSourcePushButton = nullptr; QPushButton *openSourcePushButton = nullptr; QPushButton *openDictPushButton = nullptr; QPushButton *templatePushButton = nullptr; QMainWindow *mainWindow = nullptr; void createButtonPanel(); void createConnections(); public slots: void closeEvent(QCloseEvent*); //void closeEvent(); protected: }; #endif // GREETING_H <file_sep>#ifndef FILECREATEDIALOG_H #define FILECREATEDIALOG_H #include <QWidget> class QHBoxLayout; class QVBoxLayout; class QString; class QLabel; class QTextEdit; class QPushButton; class FileCreateDialog : public QWidget { Q_OBJECT public: explicit FileCreateDialog(QWidget *parent = nullptr); signals: void createFile(QString dir, QString name); private: QHBoxLayout * dirLayout = nullptr; QHBoxLayout * nameLayout = nullptr; QHBoxLayout * buttonLayout = nullptr; QVBoxLayout * mainLayout = nullptr; QVBoxLayout * inputLayout = nullptr; QLabel * nameLabel = nullptr; QLabel * dirLabel = nullptr; QPushButton * searchButton = nullptr; QPushButton * createButton = nullptr; QTextEdit * nameEdit = nullptr; QTextEdit * dirEdit = nullptr; void clean(); private slots: void setOnSearchDirClicked(); void setOnCreateButtonClicked(); }; #endif // FILECREATEDIALOG_H <file_sep>#include "greeting.h" #include <QPushButton> #include <QAction> #include <QHBoxLayout> #include <QVBoxLayout> #include <QFileSystemModel> #include <QTreeView> #include <QFileDialog> #include <QDir> #include <QEvent> #include <QToolBar> #include <QIcon> #include <QAction> #include <QMenu> #include <QMenuBar> #include <QStatusBar> #include <QTextEdit> #include <QVBoxLayout> #include <QPixmap> #include <QCloseEvent> #include <QMessageBox> Greeting::Greeting(QWidget *parent) : QDialog(parent) { this -> setWindowTitle("Frequency Dictionary"); this->setWindowFlag(Qt::WindowCloseButtonHint, false); this->setWindowFlag(Qt::WindowContextHelpButtonHint, false); QIcon::setThemeName("mySet"); this->setWindowIcon(QIcon::fromTheme("windows10")); setSizeGripEnabled(false); this->setFixedSize(300,250); createButtonPanel(); createConnections(); } void Greeting::createConnections(){ // установка соединения сигнал - слот (создание нового текста) connect(newSourcePushButton, &QPushButton::clicked,this, &Greeting::sig_newSourse); // установка соединения сигнал - слот (открытие существующего текста) connect(openSourcePushButton, &QPushButton::clicked,this, &Greeting::sig_openSourse); // установка соединения сигнал - слот (открытие cписка существующих словарей) connect(openDictPushButton, &QPushButton::clicked,this, &Greeting::sig_openDictList); // установка соединения сигнал - слот (открытие шаблонного текста) connect(templatePushButton, &QPushButton::clicked, this, &Greeting::sig_template); } void Greeting::closeEvent(QCloseEvent *event) { emit indicateClosing(); event ->accept(); } void Greeting::createButtonPanel(){ QVBoxLayout *vbox = new QVBoxLayout(this); newSourcePushButton = new QPushButton(tr("&Cоздать исходный текст"), this); openSourcePushButton = new QPushButton(tr("&Открыть исходный текст"),this); openDictPushButton = new QPushButton(tr("Готовые &словари"),this); templatePushButton = new QPushButton(tr("Открыть &шаблон"),this); newSourcePushButton->setToolTip(tr("Новый текст для анализа")); openSourcePushButton->setToolTip(tr("Существующие тексты для анализа")); openDictPushButton->setToolTip(tr("Открыть сформированный частотный словарь")); templatePushButton -> setToolTip(tr("Открыть стихотворение В.Маяковского 'Послушайте'")); newSourcePushButton->setIcon(QIcon(QIcon::fromTheme("new1"))); openSourcePushButton->setIcon(QIcon(QIcon::fromTheme("open"))); openDictPushButton->setIcon(QIcon::fromTheme("book")); templatePushButton->setIcon(QIcon::fromTheme("template")); vbox->setSpacing(2); vbox->addStretch(1); vbox->addWidget(newSourcePushButton); vbox->addWidget(openSourcePushButton); vbox->addWidget(openDictPushButton); vbox->addWidget(templatePushButton); vbox->addStretch(1); } <file_sep>#ifndef Dictionary_H #define Dictionary_H #include <map> #include <string> #include <iomanip> #include <ostream> #include <QTextStream> #include <QString> class QStandardItemModel; class QTableView; class Dictionary { private: std::map <QString, int> dictionary; bool isalphaRus(wchar_t); QString cleanPunctuation(QString); int count = 0; public: Dictionary(); // создание пустого словаря void add(QString); // добавление элемента в словарь void increase(QString); // увеличение значения счетчика // слова в элементе словаря с заданным словом void show(QTextStream *, int); // вывести элементы словаря в алфавитном порядке void createModel(QStandardItemModel *); int find(QString); // поиск элемента словаря по слову void analyze(QString); // построить словарь по заданному тексту QString cleanWord(QString); // очистка слова от знаков препинаний и лишних символов int getCount(); void clear(); }; #endif // Dictionary_H <file_sep>#include "dictionarysnoopy.h" #include <QLabel> #include <QHBoxLayout> #include <QVBoxLayout> #include <QString> #include <QPushButton> #include <QTextEdit> #include <QFileDialog> DictionarySnoopy::DictionarySnoopy(QWidget *parent) : QWidget(parent) { requestLabel = new QLabel("Найти"); requestLabel -> setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); resultLabel = new QLabel ("Результат поиска - "); resultLabel -> setSizePolicy(QSizePolicy ::Fixed, QSizePolicy::Fixed); requestEdit = new QTextEdit(this); requestEdit -> setMaximumHeight(30); requestEdit -> setMinimumWidth(300); requestEdit -> setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed); answerLabel = new QLabel(this); answerLabel -> setMaximumHeight(30); answerLabel -> setMinimumWidth(300); answerLabel -> setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed); searchButton = new QPushButton ("Найти"); searchButton -> setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); clearButton = new QPushButton ("Очистить"); clearButton -> setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); buttonLayout = new QHBoxLayout; buttonLayout -> addWidget(searchButton); requestLayout = new QHBoxLayout; requestLayout -> setAlignment(Qt::AlignLeft); requestLayout -> setSpacing(4); requestLayout -> addWidget(requestLabel); requestLayout -> addWidget(requestEdit); resultLayout = new QHBoxLayout; resultLayout -> setAlignment(Qt::AlignLeft); resultLayout -> setSpacing(4); resultLayout -> addWidget(resultLabel); resultLayout -> addWidget(answerLabel); resultLayout -> addWidget(clearButton); inputLayout = new QVBoxLayout; inputLayout -> addLayout(requestLayout); inputLayout -> addLayout(resultLayout); mainLayout = new QVBoxLayout(this); mainLayout -> addLayout(inputLayout); mainLayout -> addLayout(buttonLayout); this-> setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Maximum); this -> setMaximumHeight(147); connect(searchButton, &QPushButton::clicked, this, &DictionarySnoopy::setOnSearchButtonClicked); connect(clearButton, &QPushButton::clicked, this, &DictionarySnoopy::setOnClearButtonClicked); } void DictionarySnoopy::setOnSearchButtonClicked(){ emit searchElem(requestEdit->toPlainText()); } void DictionarySnoopy::setOnClearButtonClicked(){ requestEdit -> setText(""); answerLabel -> setText(""); } void DictionarySnoopy::setResult(int count){ answerLabel->setText(QString::number(count)); } <file_sep>#include "mainwindow.h" #include "dictionarysnoopy.h" #include "dictionary.h" #include "greeting.h" #include <QMenu> #include <QMenuBar> #include <QIcon> #include <QDir> #include <QFileDialog> #include <QTextEdit> #include <QString> #include <QTextStream> #include <QFile> #include <QStatusBar> #include <QDebug> #include <QVBoxLayout> #include <QHBoxLayout> #include <QVBoxLayout> #include <QMdiArea> #include <QLabel> #include <QPushButton> #include <QTextCursor> #include <QByteArray> #include <QScreen> #include <QDesktopWidget> #include <QMessageBox> #include <QTableView> #include <QCloseEvent> #include <QStandardItemModel> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { this -> setWindowTitle("Frequency Dictionary"); this->setWindowIcon(QIcon::fromTheme("windows10")); snoopy = new DictionarySnoopy; greetForm = new Greeting(this); dictionary = new Dictionary(); this->setMinimumSize(800,500); createMenu(); createWorkArea(); createStatusBar(); setConnections(); turnOff(); greetForm->show(); } void MainWindow::turnOff(){ this->centralWidget()->setEnabled(false); this->menuBar()->setEnabled(false); } void MainWindow::turnOn(){ this->centralWidget()->setEnabled(true); this->menuBar()->setEnabled(true); } void MainWindow::moveToCenter(){ setGeometry((int)(QApplication::desktop()->width() - (QApplication::desktop()->width() - (QApplication::desktop()->width() / 2)) * 1.5) / 2, (int)(QApplication::desktop()->height() - (QApplication::desktop()->height() - (QApplication::desktop()->height() / 2)) * 1.5) / 2, (int)((QApplication::desktop()->width() - (QApplication::desktop()->width() / 2)) * 1.5), (int)((QApplication::desktop()->height() - (QApplication::desktop()->height() / 2)) * 1.5)); } void MainWindow::createWorkArea(){ moveToCenter(); QMdiArea *mdiArea = new QMdiArea(this); // оформление блока исходного текста sourceLayout = new QVBoxLayout(); sourceLabel = new QTextEdit(tr("Исходный текст")); sourceLabel->setEnabled(false); sourceLabel->setEnabled(false); sourceLabel -> setAlignment(Qt::AlignCenter); sourceLabel->setMaximumHeight(50); sourceLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::MinimumExpanding); sourceLayout -> setSpacing(10); sourceEdit = new QTextEdit(); //sourceEdit -> setMinimumSize(100,200); sourceEdit->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred); sourceLayout -> addWidget(sourceLabel); sourceLayout -> addWidget(sourceEdit); // оформление блока управляющих кнопок buttonLayout = new QVBoxLayout; createDictPushButton = new QPushButton(tr("Создать словарь")); createDictPushButton -> setMaximumSize(170,40); createDictPushButton -> setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); findPushButton = new QPushButton(tr("Найти в словаре")); findPushButton->setEnabled(false); findPushButton -> setMaximumSize(170,40); findPushButton -> setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); buttonLayout-> setSpacing(10); buttonLayout -> addStretch(1); buttonLayout -> addWidget(createDictPushButton); buttonLayout -> addWidget(findPushButton); buttonLayout -> addStretch(1); // оформление блока словаря table = new QTableView(this); table->setMinimumSize(400,200); table->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::MinimumExpanding); dictLayout = new QVBoxLayout(); dictLabel = new QTextEdit(tr("Словарь")); dictLabel ->setEnabled(false); dictLabel->setMaximumHeight(50); dictLabel->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::MinimumExpanding); dictLabel -> setAlignment(Qt::AlignCenter); dictLayout -> setSpacing(10); dictLayout -> addWidget(dictLabel); dictLayout -> setAlignment(table, Qt::AlignCenter); dictLayout->addWidget(table); // установка основгого менеджера компановки mainLayout = new QHBoxLayout(mdiArea); mainLayout -> addLayout(sourceLayout); mainLayout -> addLayout(buttonLayout); mainLayout -> addLayout(dictLayout); setCentralWidget(mdiArea); } void MainWindow::createStatusBar(){ statusBarLabel = new QLabel(); statusBar() -> addPermanentWidget(statusBarLabel); } void MainWindow::setStatusBarText(QString text){ statusBarLabel -> setText(text); } void MainWindow::createMenu(){ QIcon::setThemeName("mySet"); QMenu * sourceMenu = new QMenu("&Текст"); sourceMenu->addAction(QIcon::fromTheme("new1"),"Новый текст",this, SLOT(handleNewSource()),Qt::CTRL+Qt::Key_N); sourceMenu->addAction(QIcon::fromTheme("open"),"Открыть текст", this, SLOT(openNewSource()),Qt::CTRL+Qt::Key_O); sourceMenu->addAction(QIcon::fromTheme("save"),"Сохранить", this, SLOT(saveSource()),Qt::CTRL+Qt::Key_S); sourceMenu->addAction(QIcon::fromTheme("save-us"),"Сохранить как...", this, SLOT(saveSourceAs())); sourceMenu->addSeparator(); QMenu * dirMenu = new QMenu("Словарь"); dirMenu->addAction(QIcon::fromTheme("ink"),"Новый словарь",this, SLOT(handleNewDict()),Qt::ALT+Qt::Key_N); dirMenu->addAction(QIcon::fromTheme("book"),"Отркыть словарь",this,SLOT(openDict()),Qt::ALT+Qt::Key_O); dirMenu->addAction(QIcon::fromTheme("find1"),"&Поиск в словаре",this,SLOT(setOnFindClicked()),Qt::ALT+Qt::Key_F); dirMenu->addAction(QIcon::fromTheme("save"),"&Сохранить словарь",this,SLOT(saveDict()),Qt::ALT+Qt::Key_S); dirMenu->addAction(QIcon::fromTheme("save-us"),"&Сохранить словарь как...",this,SLOT(saveDictAs())); menuBar()->addMenu(sourceMenu); menuBar()->addMenu(dirMenu); } void MainWindow::setConnections(){ connect(greetForm,&Greeting::sig_newSourse, this, &MainWindow::handleNewSource); connect(greetForm, &Greeting::indicateClosing ,this,&MainWindow::setOnGreetingClosed); connect(greetForm, &Greeting::sig_openSourse, this, &MainWindow::openNewSource); connect(greetForm, &Greeting::sig_openDictList, this, &MainWindow::openDict); connect(greetForm, &Greeting::sig_template, this, &MainWindow::openTemplate); connect(findPushButton, &QPushButton::clicked, this, &MainWindow::setOnFindClicked); connect(createDictPushButton, &QPushButton::clicked, this, &MainWindow::setOnCreateDictClicked); connect(snoopy, &DictionarySnoopy::searchElem, this, &MainWindow::searchInDict); connect(this, &MainWindow::countOfFindingKeys, snoopy, &DictionarySnoopy::setResult); } void MainWindow::openTemplate(){ first = false; turnOn(); openSource(QApplication::applicationDirPath()+ tr("/blok.txt")); } void MainWindow::setOnGreetingClosed(){ turnOn(); } void MainWindow::setOnCreateDictClicked(){ dictionary->clear(); dictionary->analyze(sourceEdit->toPlainText()); if(model!= nullptr) delete model; model = new QStandardItemModel(table); dictionary->createModel(model); table ->setModel(model); findPushButton->setEnabled(true); saveSource(); } void MainWindow::setOnFindClicked(){ setOnCreateDictClicked(); snoopy->show(); } void MainWindow::handleNewSource(){ QString newName = QFileDialog::getSaveFileName( this,tr("New source"), QDir::currentPath(), tr("Text files (*.txt)")); newSource(newName); if (newName!="") first=false; } void MainWindow::handleNewDict(){ QString newName = QFileDialog::getSaveFileName( this,tr("New dictionary"), QDir::currentPath(), tr("Dictionary files (*.dict)")); newDict(newName); } void MainWindow::cleanDictArea(){ findPushButton->setEnabled(false); if (model!=nullptr) delete model; } void MainWindow::newSource(QString name){ //cleanDictArea(); delete sourceFile; sourceFile = new QFile(name); sourceFile->close(); if(greetForm!=nullptr&&name!="") greetForm -> close(); sourceEdit -> setText(""); sourceLabel->setText(tr("Исходный текст ") + sourceFile->fileName()); } void MainWindow::openNewSource(){ sourceFile = new QFile(fileOpenDialog("Text files (*.txt)")); openSource(sourceFile->fileName()); } void MainWindow::openSource(QString path){ findPushButton->setEnabled(false); delete sourceFile; sourceFile = new QFile(path); if(path!=""&&greetForm!=nullptr){ first=false; greetForm -> close(); } printFile(sourceFile,sourceEdit); sourceLabel->setText(tr("Исходный текст ") + sourceFile->fileName()); } void MainWindow::parseDictToTable(QFile *dictFile, QStandardItemModel * model){ if (!dictFile->open(QIODevice::ReadOnly)){ qDebug()<<"MainWindow::parseDictToTable: File "+dictFile->fileName()+" not open\n"; return; } model->setColumnCount(2); model->setRowCount(20); model->setHeaderData(0,Qt::Horizontal, "Слово"); model->setHeaderData(1,Qt::Horizontal, "Кол-во\nвхождений"); int row = 0; dictFile->readLine(); while(!dictFile->atEnd()){ QString line = QString::fromUtf8(dictFile->readLine()); line = line.simplified(); QStringList words = line.split("|",Qt::SkipEmptyParts); model->setData(model->index(row, 0),words.at(0)); model->setData(model->index(row, 1),words.at(1)); row++; } model->setRowCount(row); } void MainWindow::newDict(QString name){ delete dictFile; dictFile = new QFile(name); dictFile->close(); if(greetForm!=nullptr&&name!="") greetForm -> close(); delete model; model = new QStandardItemModel(table); table->setModel(model); dictLabel->setText(tr("Словарь") + dictFile->fileName()); setOnCreateDictClicked(); } void MainWindow::openDict(){ delete dictFile; delete model; dictFile = new QFile(fileOpenDialog("Dictionary (*.dict)")); if(openSuccessful){ greetForm->close(); model = new QStandardItemModel(table); parseDictToTable(dictFile, model); table->setModel(model); printFile(dictFile,dictEdit); findPushButton->setEnabled(true); first=false; } dictLabel->setText(tr("Словарь: ")+dictFile->fileName()); } void MainWindow::saveSource(){ if (sourceFile!=nullptr) saveFile(sourceFile,sourceEdit->toPlainText()); else saveSourceAs(); sourceLabel->setText(tr("Исходный текст ") + sourceFile->fileName()); } void MainWindow::saveDict(){ if (dictFile == nullptr || dictFile->fileName()==""){ handleNewDict(); return; } if(dictFile->exists()) dictFile->resize(0); if(dictFile->open(QIODevice::WriteOnly)){ QTextStream * stream = new QTextStream(dictFile); stream->setCodec("UTF-8"); dictionary->show(stream, fieldWidth); dictFile->close(); delete stream; } dictLabel->setText(tr("Словарь: ")+dictFile->fileName()); } void MainWindow::saveSourceAs(){ QString newName = QFileDialog::getSaveFileName( this,tr("Save a file"), QDir::currentPath(), tr("Text files (*.txt)")); if (newName!= ""){ delete sourceFile; sourceFile = new QFile(newName); saveFile(sourceFile,sourceEdit->toPlainText()); sourceLabel->setText(tr("Исходный текст ") + sourceFile->fileName()); } } void MainWindow::saveDictAs(){ QString newName = QFileDialog::getSaveFileName( this,tr("Save a file"), QDir::currentPath(), tr("Dictionary files (*.dict))")); if (newName!= ""){ delete dictFile; dictFile = new QFile(newName); if(dictFile->open(QIODevice::WriteOnly)){ QTextStream * stream = new QTextStream(dictFile); stream->setCodec("UTF-8"); dictionary->show(stream, fieldWidth); dictFile->close(); delete stream; } } dictLabel->setText(tr("Словарь: ")+dictFile->fileName()); } void MainWindow::printFile(QFile * file, QTextEdit * edit){ if(!file -> open(QIODevice::ReadOnly|QIODevice::Text)){ qDebug()<<"MainWindow::printFile: File "+file->fileName()+ " not open for reading"; return; } edit-> setPlainText(QString::fromUtf8(file->readAll())); file->close(); QTextCursor cursor(edit -> textCursor()); cursor.movePosition(QTextCursor::End); edit -> setTextCursor(cursor); } void MainWindow::saveFile(QFile* file, QString text){ if (!file->open(QIODevice::WriteOnly)){ qDebug()<<"MainWindow::printFile: File "+file->fileName()+ " not open for writing"; return; } file->write(text.toUtf8()); file->close(); } QString MainWindow::fileOpenDialog(QString mask){ openSuccessful = false; QString answer = QFileDialog::getOpenFileName (this, "Open a file", QDir::currentPath(), mask); if (answer != "") openSuccessful = true; return answer; } QString MainWindow::fileNewDialog(){ createSuccessful = false; QString answer = QFileDialog::getExistingDirectory (this, tr("Open Directory"), "/home", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if(answer!= "") createSuccessful = true; return answer; } QString MainWindow::dictOfThisFile(QString sourcePath){ QString dictPath = QString::fromStdString( sourcePath.toStdString().substr( 0,sourcePath.toStdString().find_last_of("/"))); std::string shortName = sourcePath.toStdString().substr(sourcePath.toStdString().find_last_of("/")); shortName = shortName.substr(0,shortName.find_last_of(".")); QDir().mkdir(QDir().currentPath()+"/Dictionaries"); dictPath = QDir().currentPath() + QString::fromStdString( "/Dictionaries"+shortName + "_dictionary.dict"); return dictPath; } void MainWindow::closeEvent(QCloseEvent *event) { QMessageBox::StandardButton ret; ret = QMessageBox::question( this, QApplication::applicationName(), tr("Завершить работу программы?"), QMessageBox::Yes | QMessageBox::No , QMessageBox::No); if (ret == QMessageBox::No){ turnOn(); event->ignore(); } if (ret == QMessageBox::Yes){ if(first){ event->accept(); return; } if(sourceFile!=nullptr) saveSource(); if(dictFile!=nullptr) saveDict(); if(!first && (sourceFile==nullptr || dictFile==nullptr || dictFile->fileName()=="" || sourceFile->fileName()=="") ) event->ignore(); } } void MainWindow::searchInDict(QString key){ emit countOfFindingKeys(dictionary->find(key)); } <file_sep>/**************************************************************************** ** Meta object code from reading C++ file 'mainwindow.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.15.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include <memory> #include "../../FinalVersion/mainwindow.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'mainwindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.15.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_MainWindow_t { QByteArrayData data[21]; char stringdata0[267]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = { { QT_MOC_LITERAL(0, 0, 10), // "MainWindow" QT_MOC_LITERAL(1, 11, 18), // "countOfFindingKeys" QT_MOC_LITERAL(2, 30, 0), // "" QT_MOC_LITERAL(3, 31, 15), // "handleNewSource" QT_MOC_LITERAL(4, 47, 9), // "newSource" QT_MOC_LITERAL(5, 57, 10), // "saveSource" QT_MOC_LITERAL(6, 68, 12), // "saveSourceAs" QT_MOC_LITERAL(7, 81, 13), // "openNewSource" QT_MOC_LITERAL(8, 95, 10), // "openSource" QT_MOC_LITERAL(9, 106, 13), // "handleNewDict" QT_MOC_LITERAL(10, 120, 7), // "newDict" QT_MOC_LITERAL(11, 128, 10), // "saveDictAs" QT_MOC_LITERAL(12, 139, 8), // "saveDict" QT_MOC_LITERAL(13, 148, 8), // "openDict" QT_MOC_LITERAL(14, 157, 12), // "openTemplate" QT_MOC_LITERAL(15, 170, 12), // "searchInDict" QT_MOC_LITERAL(16, 183, 10), // "closeEvent" QT_MOC_LITERAL(17, 194, 12), // "QCloseEvent*" QT_MOC_LITERAL(18, 207, 22), // "setOnCreateDictClicked" QT_MOC_LITERAL(19, 230, 19), // "setOnGreetingClosed" QT_MOC_LITERAL(20, 250, 16) // "setOnFindClicked" }, "MainWindow\0countOfFindingKeys\0\0" "handleNewSource\0newSource\0saveSource\0" "saveSourceAs\0openNewSource\0openSource\0" "handleNewDict\0newDict\0saveDictAs\0" "saveDict\0openDict\0openTemplate\0" "searchInDict\0closeEvent\0QCloseEvent*\0" "setOnCreateDictClicked\0setOnGreetingClosed\0" "setOnFindClicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_MainWindow[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 18, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 104, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 3, 0, 107, 2, 0x0a /* Public */, 4, 1, 108, 2, 0x0a /* Public */, 5, 0, 111, 2, 0x0a /* Public */, 6, 0, 112, 2, 0x0a /* Public */, 7, 0, 113, 2, 0x0a /* Public */, 8, 1, 114, 2, 0x0a /* Public */, 9, 0, 117, 2, 0x0a /* Public */, 10, 1, 118, 2, 0x0a /* Public */, 11, 0, 121, 2, 0x0a /* Public */, 12, 0, 122, 2, 0x0a /* Public */, 13, 0, 123, 2, 0x0a /* Public */, 14, 0, 124, 2, 0x0a /* Public */, 15, 1, 125, 2, 0x0a /* Public */, 16, 1, 128, 2, 0x0a /* Public */, 18, 0, 131, 2, 0x08 /* Private */, 19, 0, 132, 2, 0x08 /* Private */, 20, 0, 133, 2, 0x08 /* Private */, // signals: parameters QMetaType::Void, QMetaType::Int, 2, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::QString, 2, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::QString, 2, QMetaType::Void, QMetaType::Void, QMetaType::QString, 2, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::QString, 2, QMetaType::Void, 0x80000000 | 17, 2, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<MainWindow *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->countOfFindingKeys((*reinterpret_cast< int(*)>(_a[1]))); break; case 1: _t->handleNewSource(); break; case 2: _t->newSource((*reinterpret_cast< QString(*)>(_a[1]))); break; case 3: _t->saveSource(); break; case 4: _t->saveSourceAs(); break; case 5: _t->openNewSource(); break; case 6: _t->openSource((*reinterpret_cast< QString(*)>(_a[1]))); break; case 7: _t->handleNewDict(); break; case 8: _t->newDict((*reinterpret_cast< QString(*)>(_a[1]))); break; case 9: _t->saveDictAs(); break; case 10: _t->saveDict(); break; case 11: _t->openDict(); break; case 12: _t->openTemplate(); break; case 13: _t->searchInDict((*reinterpret_cast< QString(*)>(_a[1]))); break; case 14: _t->closeEvent((*reinterpret_cast< QCloseEvent*(*)>(_a[1]))); break; case 15: _t->setOnCreateDictClicked(); break; case 16: _t->setOnGreetingClosed(); break; case 17: _t->setOnFindClicked(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { using _t = void (MainWindow::*)(int ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&MainWindow::countOfFindingKeys)) { *result = 0; return; } } } } QT_INIT_METAOBJECT const QMetaObject MainWindow::staticMetaObject = { { QMetaObject::SuperData::link<QMainWindow::staticMetaObject>(), qt_meta_stringdata_MainWindow.data, qt_meta_data_MainWindow, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *MainWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *MainWindow::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0)) return static_cast<void*>(this); return QMainWindow::qt_metacast(_clname); } int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 18) qt_static_metacall(this, _c, _id, _a); _id -= 18; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 18) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 18; } return _id; } // SIGNAL 0 void MainWindow::countOfFindingKeys(int _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(std::addressof(_t1))) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } QT_WARNING_POP QT_END_MOC_NAMESPACE <file_sep>#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> //Qt classes class QString; class QMenu; class QHBoxLayout; class QVBoxLayout; class QAction; class QTextEdit; class QFile; class QTextStream; class QPushButton; class QLabel; class QTableView; class QStandardItemModel; // custom classes class Dictionary; // класс, реализующий функционал и внутреннее представление словаря class Greeting; // приветственная форма приложения class DictionarySnoopy; // класс, реализующий функционал поиска в словаря по ключу class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); public slots: // slots about SOURCE file void handleNewSource(); void newSource(QString ); // SAVING void saveSource(); void saveSourceAs(); // OPENING void openNewSource(); void openSource(QString); // slots about DICTIONARY file void handleNewDict(); void newDict(QString); // SAVING void saveDictAs(); void saveDict(); // OPENING void openDict(); void openTemplate(); // SEARCHING void searchInDict(QString); // saving procedure before closings void closeEvent(QCloseEvent *); private slots: // "setOn" slots (buttons and menubars action) void setOnCreateDictClicked(); void setOnGreetingClosed(); void setOnFindClicked(); signals: void countOfFindingKeys(int); private: bool first = true; const int fieldWidth = 20; bool openSuccessful = false; bool createSuccessful = false; Greeting * greetForm = nullptr; Dictionary * dictionary = nullptr; QMenu * sourceMenu = nullptr, * dirMenu = nullptr; QHBoxLayout * mainLayout = nullptr; QVBoxLayout * sourceLayout = nullptr, * dictLayout = nullptr, * buttonLayout = nullptr; DictionarySnoopy * snoopy = nullptr; QTableView * table = nullptr; QStandardItemModel * model = nullptr; QTextEdit * sourceEdit = nullptr, * dictEdit = nullptr; QFile * sourceFile = nullptr, * dictFile = nullptr; QTextStream * sourceStream = nullptr; QPushButton * createDictPushButton = nullptr; QPushButton * findPushButton = nullptr; QTextEdit * dictLabel = nullptr, * sourceLabel = nullptr; QLabel * statusBarLabel = nullptr; void createMenu(); void setConnections(); void moveToCenter(); void cleanDictArea(); void createWorkArea(); void createStatusBar(); void setStatusBarText(QString); void turnOn(); void turnOff(); void parseDictToTable(QFile *, QStandardItemModel *); void printFile(QFile*, QTextEdit*); void saveFile(QFile*, QString); QString dictOfThisFile(QString); QString fileOpenDialog(QString); QString fileNewDialog(); }; #endif // MAINWINDOW_H <file_sep>#ifndef DICTIONARY_SNOOPY #define DICTIONARY_SNOOPY #include <QWidget> class QHBoxLayout; class QVBoxLayout; class QString; class QLabel; class QTextEdit; class QPushButton; class MainWindow; class DictionarySnoopy : public QWidget { Q_OBJECT public: explicit DictionarySnoopy(QWidget *parent = nullptr); signals: void searchElem(QString key); private: QHBoxLayout * requestLayout = nullptr; QHBoxLayout * resultLayout = nullptr; QHBoxLayout * buttonLayout = nullptr; QVBoxLayout * mainLayout = nullptr; QVBoxLayout * inputLayout = nullptr; QLabel * requestLabel = nullptr; QLabel * resultLabel = nullptr; QLabel * answerLabel = nullptr; QPushButton * searchButton = nullptr; QPushButton * clearButton = nullptr; QTextEdit * requestEdit = nullptr; void clean(); private slots: void setOnSearchButtonClicked(); void setOnClearButtonClicked(); public slots: void setResult(int); }; #endif // DICTIONARY_SNOOPY
f048c2ab24b347aaf3652c44ca5f55c6b6b6f22e
[ "C++" ]
11
C++
denilai/CourseWorkAOOD2
a33ec83592cc251272905e4dcb9088dd1fe62686
72d262aa8e162a49022be29806fd3f9131bef2c4
refs/heads/master
<file_sep>package com.taskmanagement.dao; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.taskmanagement.model.Task; @Repository public class TaskDaoImpl implements TaskDao { /** Initialize the LOGGER object */ private static final Log logger = LogFactory.getLog(TaskDaoImpl.class); @Autowired private SessionFactory sessionFactory; @Override public Task addTask(Task task) { // TODO Auto-generated method stub logger.info("Inserting Task and Parent in database"); Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.save("task_table",task); tx.commit(); } catch (Exception ex) { if (tx != null) tx.rollback(); logger.error("Exception while inserting the task: " + ex); throw ex; } finally { session.close(); } logger.info("Task Added Successfully."); return task; } @Override public Task updateTask(Task task) { // TODO Auto-generated method stub logger.info("Updating Task and Parent"); Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.update(task); tx.commit(); } catch (Exception ex) { if (tx != null) tx.rollback(); logger.error("Exception while updating the task: " + ex); throw ex; } finally { session.close(); } logger.info("Task Updated Successfully."); return task; } @Override public List<Task> getTasks() { // TODO Auto-generated method stub logger.info("Getting List of Tasks From The Database"); Session session = sessionFactory.openSession(); Transaction tx = null; List<Task> taskList = new ArrayList<Task>(); try { tx = session.beginTransaction(); taskList = session.createQuery("from Task", Task.class).list(); tx.commit(); } catch (Exception ex) { if (tx != null) tx.rollback(); logger.error("Exception while retrieving the task list : " + ex); throw ex; } finally { session.close(); } logger.info("Tasks List Retrieved Successfully."); return taskList; } @Override public Task getTask(int id) { // TODO Auto-generated method stub logger.info("Getting a Task Based on The Key Passed"); Session session = sessionFactory.openSession(); Transaction tx = null; Task task = new Task(); try { tx = session.beginTransaction(); task = session.get(Task.class, new Long(id)); tx.commit(); } catch (Exception ex) { if (tx != null) tx.rollback(); logger.error("Exception while retrieving the task: " + ex); throw ex; } finally { session.close(); } logger.info("Task Retrieved Successfully from the Database"); return task; } }
640cf73b44954190ee5299c0d52087b4051dae58
[ "Java" ]
1
Java
vivek-kakumanu/TaskManagementService
d006396f05e527e69f1543e4a91dd9c5bd5b8d4c
622039a66ea7aa68c7c7e3de373da49df31bdc2c
refs/heads/master
<repo_name>dot-build/karma-fixture-loader<file_sep>/karma-fixture-loader.js (function(exports) { var fixturesPath = 'fixture/'; var loaded = false; var fixtures = { get: getFixture, getFirst: getFirst, getFiltered: getFilteredFixture, load: load, setPath: setPath, _cache: {} }; /** * Get a fixture from the preloaded cache of data fixtures * @param {String} name A fixture name, like "Content.json" */ function getFixture(name) { if (name in fixtures._cache === false || typeof fixtures._cache[name] !== 'object') { throw new Error('Missing fixture: ' + name); } return JSON.parse(JSON.stringify(fixtures._cache[name])); } /** * Returns the first item in the array of objects declared * in a fixture */ function getFirst(name) { var fixtures = getFixture(name); return Array.isArray(fixtures) ? fixtures[0] : fixtures; } /** * Gets a list of objects in a fixture, filtering the items with a * given function */ function getFilteredFixture(name, filterFn) { return getFixture(name).filter(filterFn); } function loadFixture(name, done) { if (!name) { throw new Error('Invalid fixture file!'); } var request = new XMLHttpRequest(); request.onload = function() { var json; try { json = JSON.parse(request.responseText); } catch (e) {} fixtures._cache[name] = json || null; done(); }; // karma base path + fixtures path + actual file name request.open('GET', 'base/' + fixturesPath + name); request.send(null); } /** * Loads all fixture files before tests */ function load(done) { if (loaded) { return done(); } var index = -1; // get fixture list from file list loaded by karma var fixtureFiles = Object.keys(window.__karma__.files).filter(function(file) { return file.slice(-5) === '.json' && file.indexOf(fixturesPath) !== -1; }); if (!fixtureFiles.length) { console.warn('No fixtures to load were found'); return done(); } fixtureFiles = fixtureFiles.map(function(file) { return file.split(fixturesPath)[1]; }); function next() { index++; if (index === fixtureFiles.length) { loaded = true; return done(); } var name = fixtureFiles[index]; loadFixture(name, next); } next(); } function setPath(path) { // remove leading slash if (path.charAt(0) === '/') { path = path.slice(1); } fixturesPath = path; // add trailing slash if (fixturesPath.slice(-1) !== '/') { fixturesPath += '/'; } } exports.fixtures = fixtures; })(typeof module !== 'undefined' && module.exports || this); <file_sep>/README.md # JSON Fixture loader for Karma In Unit Testing it's a common practice to have fixture files with a content that serves as replacement for real implementations (e.g a backend, a 3rd party API...). This little module loads your JSON files and provides a simple way to access them in your unit tests. ## Usage Create a folder in your project somewhere. A common place would be `test/fixture`. Now open your `karma.conf.js` (Karma configuration) and add the loader script and the fixture files to the file list: ``` // ... files: [ // ... require.resolve('karma-fixture-loader'), { // notice the fixture path here pattern: 'test/fixture/*.json', watched: true, served: true, included: false } ] ``` Your JSON fixtures are now available in your tests via Ajax. Now, add another file to your project that will configure the module and load your files: __Vanilla JS with Jasmine:__ ```js // path to your fixtures window.fixtures.setPath('text/fixture'); beforeAll(function(done) { fixtures.load(done); }); ``` __ES6 and Jasmine:__ ```js import { fixtures } from 'karma-fixture-loader'; // path to your fixtures fixtures.setPath('test/fixture'); beforeAll(done => fixtures.load(done)); export { fixtures } ``` ## API ### get('filename.json') => Object Returns an Object parsed from a file called "filename.json" in your fixture folder ``` var users = fixtures.get('users.json'); ``` ### getFirst('filename.json') => Object If the same fixture above is an array, returns the first item in this array. ``` var bob = fixtures.getFirst('users.json'); ```
cc115d7a037a4d32004c6f786389102d8eca0684
[ "JavaScript", "Markdown" ]
2
JavaScript
dot-build/karma-fixture-loader
e2d50b6a660a83ba3149756dc585d66745cd2a74
15f4be8b7bd5e8cbdf5d9808657ffcfaef888a2a
refs/heads/master
<file_sep>#include "vanG.h" // Boolean function which tells all edges have been visited or not. bool VisitAll(vector<Edge> edges) { for (size_t i=0; i<edges.size(); i++) { if (edges[i].visited==false) { return false; } } return true; } // Build a binary tree based on parsed information: root, sinks and edges // Recursive function void BuildTree(Node* node, vector<Edge> &edges, vector<Node> sinks) { bool visited = VisitAll(edges); // Base condition is that the node is sink node. if (node->label>0 && node->label <= num_sinks) { Node sink = sinks[node->label - 1]; node->left = NULL; node->right = NULL; node->solutions = sink.solutions; } if (!visited) { for (size_t i = 0; i < edges.size(); i++) { if (edges[i].upstream == node->label) { edges[i].visited = true; if (node->left != NULL&&node->right == NULL) { node->right = new Node; node->right->label = edges[i].downstream; node->right->left = NULL; node->right->right = NULL; node->right_length = edges[i].length; BuildTree(node->right, edges, sinks); } else if (node->right != NULL&&node->left == NULL) { node->left = new Node; node->left->label = edges[i].downstream; node->left->left = NULL; node->left->right = NULL; node->left_length = edges[i].length; BuildTree(node->left, edges, sinks); } else if (node->right == NULL&&node->left == NULL) { // insert to left child by default node->left = new Node; node->left->label = edges[i].downstream; node->left->left = NULL; node->left->right = NULL; node->left_length = edges[i].length; BuildTree(node->left, edges, sinks); } else { cout << "Error happened when build the binary tree!" << endl; exit(1); } } } } else return; } // Parser Node* Parser(char* file_name) { // Attemt to open the data file. ifstream inFile(file_name); if (inFile.fail()) { cerr << "Problem occurred with input file." << endl; inFile.close(); exit(1); } // Parse the number of sinks string line; getline(inFile, line); istringstream streaml (line, istringstream::in); streaml >> num_sinks; streaml.clear(); // Initialize the root of the binary tree Node* root = new Node; root->label = 0; root->left = NULL; root->right = NULL; // Store sinks into vector vector<Node> sinks; for (int i=1; i<=num_sinks; i++) { double capacitance = 0.0; double load = 0.0; Node node; getline(inFile, line); istringstream streamll (line, istringstream::in); streamll >> capacitance >> load; node.label = i; node.solutions.push_back(make_pair(capacitance, load)); sinks.push_back(node); streamll.clear(); } // Store edges into vector vector<Edge> edges; while(getline(inFile, line)) { Edge edge; int upstream = 0; int downstream = 0; double length = 0; istringstream streamlll (line, istringstream::in); streamlll >> upstream >> downstream >> length; edge.upstream = upstream; edge.downstream = downstream; edge.length = length; edge.visited = false; edges.push_back(edge); streamlll.clear(); } inFile.close(); // Build a binary tree BuildTree(root, edges, sinks); // Return the binary tree return root; } // Add wires from downstream node to upstream node // Update the upstream node candidates map, which keeps tracking the insertion list void AddWire(list<pair<double,double> > &candidates, double length, Node* upstream, Node* downstream) { if (!candidates.empty()) { for (list<pair<double,double> >::iterator it=candidates.begin(); it!=candidates.end(); ++it) { list<pair<int,int> > wire_insertion = downstream->candidates_map[*it]; it->second = it->second - CAPACITANCE * RESISTANCE * length * length /2 - RESISTANCE * it->first * length; it->first = it->first + CAPACITANCE * length; wire_insertion.push_back(make_pair(upstream->label, 0)); upstream->candidates_map[*it] = wire_insertion; } } else { return; } } bool CompareC(const pair<double,double> & lhs, const pair<double,double> & rhs) { return lhs.first < rhs.first; } // Prune the inferior solutions in the candidates list void Prune(list<pair<double,double> > &candidates) { candidates.sort(CompareC); list<pair<double,double> >::iterator it = candidates.begin(); list<pair<double,double> >::iterator new_it = it; ++new_it; while (new_it!=candidates.end()) { if (it->first<new_it->first) { if (it->second>=new_it->second) { new_it = candidates.erase(new_it); // prune inferior candidate } else { it = new_it; ++new_it; } } else if (it->first==new_it->first) { if (it->second<new_it->second) { it = candidates.erase(it); ++new_it; } else { new_it = candidates.erase(new_it); } } else { cout << "Sort is not working correctly!" <<endl; } } return; } // Add buffers at upstream node in the edge // Update the upstream node candidates map, which keeps tracking the insertion list void AddBuffer(list<pair<double,double> > &candidates, Node* upstream) { if (!candidates.empty()) { list<pair<double,double> > temp_candidates = candidates; for (list<pair<double,double> >::iterator it=temp_candidates.begin(); it!=temp_candidates.end(); ++it) { list<pair<int,int> > buffer_insertion = upstream->candidates_map[*it]; it->second = it->second - BUFFER_RESISTANCE * it->first - BUFFER_INTRINSIC_DELAY; it->first = BUFFER_CAPACITANCE; candidates.push_back(*it); buffer_insertion.push_back(make_pair(upstream->label, 1)); upstream->candidates_map[*it] = buffer_insertion; } } else { return; } } list<pair<int,int> > MergeList(list<pair<int,int> > lhs, list<pair<int,int> > rhs) { for (list<pair<int, int> >::iterator it = rhs.begin(); it != rhs.end(); ++it) { lhs.push_back(*it); } return lhs; } // Merge two candidates lists // Merge two candidates maps for upstream node, keep tracking the insertion list list<pair<double,double> > Merge(list<pair<double,double> > lhs, list<pair<double,double> > rhs, Node* upstream) { list<pair<double,double> > merged_candidates; list<pair<double,double> >::iterator it_l=lhs.begin(); list<pair<double,double> >::iterator it_r=rhs.begin(); while (it_l!=lhs.end()&&it_r!=rhs.end()) { list<pair<int,int> > left_insertion = upstream->candidates_map[*it_l]; list<pair<int,int> > right_insertion = upstream->candidates_map[*it_r]; list<pair<int,int> > merged_insertion = MergeList(left_insertion, right_insertion); if (it_l->second<it_r->second) { merged_candidates.push_back(make_pair(it_l->first+it_r->first, it_l->second)); upstream->candidates_map[make_pair(it_l->first + it_r->first, it_l->second)] = merged_insertion; ++it_l; } else { merged_candidates.push_back(make_pair(it_l->first+it_r->first, it_r->second)); upstream->candidates_map[make_pair(it_l->first + it_r->first, it_r->second)] = merged_insertion; ++it_r; } } return merged_candidates; } list<pair<double,double> > VanGin(Node* node) { // If it is sink, the base condition if (node->label>0&&node->label<=num_sinks) { list<pair<double,double> > candidates = node->solutions; // Initialize candidates_map list<pair<int,int> > buffer_candidates; for (list<pair<double,double> >::iterator it = candidates.begin(); it != candidates.end(); ++it) { buffer_candidates.push_back(make_pair(node->label, 0)); node->candidates_map[*it] = buffer_candidates; } return candidates; } else { list<pair<double,double> > left_candidates; list<pair<double,double> > right_candidates; if (node->left!=NULL) { left_candidates = VanGin(node->left); //Add wire for left_candidates AddWire(left_candidates, node->left_length, node, node->left); //Add buffer for left_candidates AddBuffer(left_candidates, node); //Prune candidates Prune(left_candidates); } if (node->right!=NULL) { right_candidates = VanGin(node->right); //right_candidates AddWire(right_candidates, node->right_length, node, node->right); AddBuffer(right_candidates, node); Prune(right_candidates); } if (node->left!=NULL&&node->right!=NULL) { //Merge subtree list<pair<double,double> > candidates = Merge(left_candidates,right_candidates, node); Prune(candidates); return candidates; } else if (node->left==NULL&&node->right!=NULL) { return right_candidates; } else if (node->left!=NULL&&node->right==NULL) { return left_candidates; } else { cout << "This node should be a sink" <<endl; exit(2); } } } // Add driver at the driver node // Update the candidate map for the final solution lists void AddDriver(list<pair<double,double> > &candidates, Node* node) { if (!candidates.empty()) { for (list<pair<double,double> >::iterator it = candidates.begin(); it != candidates.end(); ++it) { list<pair<int,int> > driver_insertion = node->candidates_map[*it]; it->second = it->second - DRIVER_RESISTANCE * it->first; node->candidates_map[*it] = driver_insertion; } } else { cout << "There is no candidate!" << endl; return; } } // Count the number of buffers inserted int CountBuffer(list<pair<int,int> > insertion_list) { int count = 0; for (list<pair<int,int> >::iterator it = insertion_list.begin(); it != insertion_list.end(); ++it) { if (it->second==1) { count++; } } return count; } // Find the places where bufferes are inserted list<pair<int,int> > FindBuffer(list<pair<int,int> > insertion_list) { list<pair<int, int> > buffer_list; for (list<pair<int, int> >::iterator it = insertion_list.begin(); it != insertion_list.end(); ++it) { if (it->second == 1) { buffer_list.push_back(*it); } } return buffer_list; } int main(int argc, char *argv[]){ char* file_name = argv[1]; Node* root = Parser(file_name); root->solutions = VanGin(root); AddDriver(root->solutions, root); Prune(root->solutions); pair<double,double> solution = root->solutions.back(); list<pair<int,int> > insertion_list = root->candidates_map[solution]; int buffer_number = CountBuffer(insertion_list); // total number of buffers inserted list<pair<int,int> > buffer_list = FindBuffer(insertion_list); double RAT = solution.second;// RAT at the driver node ofstream outfile; outfile.open ("output"); outfile << "Total number of buffers inserted is: " << buffer_number << endl; outfile << "The nodes where buffers are inserted are: " << endl; for (list<pair<int,int> >::iterator it = buffer_list.begin(); it != buffer_list.end(); ++it) { outfile << "Node " << it->first << ": " << "+1" << " buffer" << endl; } outfile << "RAT at the driver node is: " << RAT << endl; outfile.close(); return 0; } <file_sep># vanG van-Ginneken Algorithm Implementation in C++ <file_sep>#ifndef VGAN_H #define VGAN_H #include <string> #include <vector> #include <iostream> #include <cmath> #include <cstdlib> #include <stdio.h> #include <fstream> #include <sstream> #include <algorithm> #include <list> #include <map> using namespace std; const int RESISTANCE = 1; //resistance per unit length const int CAPACITANCE = 1; //capacitance per unit length const int BUFFER_RESISTANCE = 1; const int BUFFER_CAPACITANCE = 1; const int BUFFER_INTRINSIC_DELAY = 1; const int DRIVER_RESISTANCE = 1; int num_sinks=0; struct Node { int label; Node* left; Node* right; double left_length, right_length; list<pair<double,double> > solutions; // solution pair composed with capacitance and RAT map<pair<double,double>, list<pair<int,int> > > candidates_map; // solution pair points to the backtrack insertion lists }; struct Edge { int upstream; int downstream; double length; bool visited; }; #endif
3757625f21716c98355cb6c9290c8738f4f85f42
[ "Markdown", "C++" ]
3
C++
lizix7/vanG
6b7e468d393d60154a7e430896f1fb6446c03bb0
580f7090b79b44ffc3ae93ea4fc12906d00eff4f
refs/heads/main
<file_sep>var helicopter,box,ground; var himg,boximg,boxBody; const Engine = Matter.Engine; const World = Matter.World; const Bodies = Matter.Bodies; const Body = Matter.Body; var engine,world; function preload() { himg = loadImage("helicopter.png"); boximg = loadImage("package.png"); } function setup() { createCanvas(800,700); rectMode(CENTER); box = createSprite(width/2,80,10,10); box.addImage(boximg); box.scale = 0.2; helicopter = createSprite(width/2,200,10,10); helicopter.addImage(himg); helicopter.scale = 0.6; ground = createSprite(width/2,height-35,width,10); ground.shapeColor = color(255); box1 = createSprite(500,610,20,100); box1.shapeColor = color("black"); box2 = createSprite(300,610, 20,100); box2.shapeColor=color("black"); box3 = createSprite(400,650, 200,20); box3.shapeColor=color("black"); engine = Engine.create(); world = engine.world; boxBody = Bodies.circle(width/2,200,5,{restitution:0.8}); Matter.Body.setStatic(boxBody,true); World.add(world,boxBody); var ground_options = { isStatic: true } ground = Bodies.rectangle(width/2,650,width,10,{isStatic:true}); World.add(world,ground); box1 = Bodies.rectangle(width/2,650,width,10,{isStatic:true}); World.add(world,box1); box2 = Bodies.rectangle(width/2, 650, width, 10 , {isStatic:true} ); World.add(world, box2); box3 = Bodies.rectangle(width/2, 650, width, 10 , {isStatic:true} ); World.add(world, box3); //console.log(ground); Engine.run(engine); } function draw() { //helicopter.x = box.x //=-()*&^%%$box.x = helicopter.x // helicopter.x = packageSprite.x rectMode(CENTER); background("red"); //Engine.update(engine); box.x = boxBody.position.x box.y = boxBody.position.y box.x = helicopter.x if(keyDown("left")){ helicopter.x = helicopter.x-5 //box.x = box.x-5 // boxBody.position.x = boxBody.position.x-1 } if(keyDown("right")){ helicopter.x = helicopter.x+5 // boxBody.position.x = boxBody.position.x+1 } // =-()boxBody.x = helicopter.x drawSprites(); keyPressed(); } function keyPressed() { if (keyCode == DOWN_ARROW) { console.log("down"); Matter.Body.setStatic(boxBody,false); } box.x = boxBody.position.x // box.x != helicopter.x } // var helicopterIMG, helicopterSprite, packageSprite,packageIMG; // var packageBody,ground,package1,ground1 // const Engine = Matter.Engine; // const World = Matter.World; // const Bodies = Matter.Bodies; // const Body = Matter.Body; // function preload() // { // helicopterIMG=loadImage("helicopter.png") // packageIMG=loadImage("package.png") // } // function setup() { // createCanvas(800, 700); // engine = Engine.create(); // world = engine.world; // rectMode(CENTER); // // ground1 = new Ground(400,690,800,20) // packageSprite=createSprite(width/2, 200, 10,10); // packageSprite.addImage(packageIMG) // packageSprite.scale=0.2 // helicopterSprite=createSprite(width/2, 200, 10,10); // helicopterSprite.addImage(helicopterIMG) // helicopterSprite.scale=0.6 // groundSprite=createSprite(width/2, height-35, width,10); // groundSprite.shapeColor=color(255) // boxPosition=width/2-100 // boxY=610; // boxleftSprite=createSprite(boxPosition, boxY, 20,100); // boxleftSprite.shapeColor=color(255,0,0); // boxBase=createSprite(boxPosition+100, boxY+40, 200,20); // boxBase.shapeColor=color(255,0,0); // boxrightSprite=createSprite(boxPosition+200 , boxY, 20,100); // boxrightSprite.shapeColor=color(255,0,0); // //////////////////////////////////////////// // engine = Engine.create(); // world = engine.world; // /////////////////////////////////////////// // packageBody = Bodies.circle(width/2 , 200 , 5 , {restitution:0.4, isStatic:true}); // World.add(world, packageBody); // //Create a Ground // ground = Bodies.rectangle(width/2, 650, width, 10 , {isStatic:true} ); // World.add(world, ground); // boxLeftBody = Bodies.rectangle(boxPosition+20, boxY, 20,100 , {isStatic:true} ); // World.add(world, boxLeftBody); // /////////////// // boxBottomBody = Bodies.rectangle(boxPosition+100, boxY+45-20, 200,20 , {isStatic:true} ); // World.add(world, boxBottomBody); // boxRightBody = Bodies.rectangle(boxPosition+200-20 , boxY, 20,100 , {isStatic:true} ); // World.add(world, boxRightBody); // //package1 = new Package(100,100,30,30) // Engine.run(engine); // } // function draw() { // rectMode(CENTER); // background(0); // packageSprite.x = helicopterSprite.x // // //packageSprite.x= packageBody.position.x // // //packageSprite.y= packageBody.position.y // // //packageSprite.x = helicopterSprite.x // // //package1.display() // // if(keyDown("left")){ // // helicopterSprite.x = helicopterSprite.x - 10 // // //packageSprite.x = helicopterSprite.x // // } // // if(keyDown("right")){ // // helicopterSprite.x = helicopterSprite.x + 10 // // //packageSprite.x = helicopterSprite.x // // } // // //if(keyDown("down")){ // // //packageSprite.x= packageBody.position.x // // //packageSprite.y= packageBody.position.y // // //packageSprite.velocityY = 10 // // //}// // // // ground1.display() // drawSprites(); // keyPressed() // } // function keyPressed(){ // if(keyCode == DOWN_ARROW ){ // console.log("hlo") // Matter.Body.setStatic(packageBody , false);} // }
bab6faa2b362d19416f0ea39dfd368cc15725d98
[ "JavaScript" ]
1
JavaScript
Kartikeya-coder1/Supplier-Commando
09fb4bb8a97558a538ddc34a111fb9934a8cfbd4
32c60aa1c6bf81d8b71f4c1458c3e94959e6784f
refs/heads/master
<file_sep> SLITHER The game utilizes pygame module. The position of apple is randomized. The gameloop has implementations of functions-snake,randapple. Snake function displays a list of elements which is basically the body of the snake,length of body is incremented by appending elements to it if the head or the last element of list ==position of apple. The snake can be controlled by arrow keys. If the element of list other than head matches the head co-ordinates which is if the snake touches itself,the game is over. The score is increased if head co-ordinates match the co-ordinates of apple which is randomly generated and after this is done the apple is generated elsewhere. Developed by codErrors <file_sep>import pygame import time import random # initialising pygame.init() # defining the colors white=(255,255,255) red=(255,0,0) black=(0,0,0) gray=(211,211,211) green=(0,255,0) # dimensions block=20 width=800 height=600 # creating a display Display=pygame.display.set_mode([width,height]) # creating a caption or title pygame.display.set_caption('Slither') # declaring a global variable "direction" global direction # importing clock feature of time library(for no of frames per second) clock=pygame.time.Clock() # fonts font=pygame.font.SysFont(None,40) font1=pygame.font.SysFont(None,25) # geting images head=pygame.image.load('head.png') tail=pygame.image.load('tail.png') background=pygame.image.load('grass.png') apple=pygame.image.load('apple.png') body=pygame.image.load('body.png') # geting sounds eat=pygame.mixer.Sound("eat_apple.wav") # defining function to display text on screen def text_on_screen(text,color,x=400,y=100): message_shown=font.render(text,True,color) Display.blit(message_shown,[x,y]) # defining function to get score def score_on_screen(text,color,x=200,y=300): message_shown=font1.render(text,True,color) Display.blit(message_shown,[x,y]) # adding introduction to the game def gameintro(): intro = True while intro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_c: intro = False if event.key == pygame.K_q: pygame.quit() quit() Display.fill(black) text_on_screen("SLITHER", white,200,200) text_on_screen("press c to play or q to quit!", white,200,400) pygame.display.update() clock.tick(5) # defining the main game loop def gameloop(): exit=False over=False # seting the x and y coordinates lead_x=width/2 lead_y=height/2 # initialising the change in coordinates lead_x_change=0 lead_y_change=0 # generating apples randomly applex=random.randrange(0,width-block) appley=random.randrange(0,height-block) sum1=1 # initialising the no of frames per second to 10 FPS=10 # defining a list snakelist=[] # initialising the snake direction="right" # defining the snake taking the snakelist as an attribute def snake(snakelist): #setting angle of rotation and coordinates of the snake head if direction=="right": snake_head=pygame.transform.rotate(head,270) Display.blit(snake_head,[snakelist[-1][0],snakelist[-1][1]]) if direction=="left": snake_head=pygame.transform.rotate(head,90) Display.blit(snake_head,[snakelist[-1][0],snakelist[-1][1]]) if direction=="up": snake_head=pygame.transform.rotate(head,0) Display.blit(snake_head,[snakelist[-1][0],snakelist[-1][1]]) if direction=="down": snake_head=pygame.transform.rotate(head,180) Display.blit(snake_head,[snakelist[-1][0],snakelist[-1][1]]) for locate in snakelist[:-1]: Display.blit(body,[locate[0],locate[1]]) q=snakelist[::-1] if sum1>5: # location and angle of rotation of the tail if (q[len(snakelist)-1][0]-q[len(snakelist)-2][0]<0): qtail=pygame.transform.rotate(tail,270) Display.blit(qtail,[(q[len(snakelist)-1][0]),(q[len(snakelist)-1][1])]) if (q[len(snakelist)-1][0]-q[len(snakelist)-2][0]>0): qtail=pygame.transform.rotate(tail,90) Display.blit(qtail,[(q[len(snakelist)-1][0]),(q[len(snakelist)-1][1])]) if (q[len(snakelist)-1][1]-q[len(snakelist)-2][1]>0): qtail=pygame.transform.rotate(tail,0) Display.blit(qtail,[(q[len(snakelist)-1][0]),(q[len(snakelist)-1][1])]) if (q[len(snakelist)-1][1]-q[len(snakelist)-2][1]<0): qtail=pygame.transform.rotate(tail,180) Display.blit(qtail,[(q[len(snakelist)-1][0]),(q[len(snakelist)-1][1])]) while exit==False: while over==True: # adding menu if to play again or quit Display.blit(background,[0,0]) pygame.draw.rect(Display,black,[0,100,800,100]) text_on_screen("Press C to retry or Q to quit",red) pygame.display.update() for event in pygame.event.get(): # options to either quit or retry if event.type==pygame.QUIT: pygame.quit() quit() if event.type==pygame.KEYDOWN: if event.key==pygame.K_q: exit=True over=False if event.key==pygame.K_c: text_on_screen(str(sum1-1),black,300,100) pygame.display.update() time.sleep(1) gameloop() # movement of the snake for event in pygame.event.get(): if event.type==pygame.QUIT: exit=True if (event.type==pygame.KEYDOWN): if ((event.key==pygame.K_LEFT) and (lead_x_change<=0)) : direction="left" lead_x_change=-20 lead_y_change=0 if ((event.key==pygame.K_RIGHT) and (lead_x_change>=0)): direction="right" lead_x_change=20 lead_y_change=0 if ((event.key==pygame.K_UP) and (lead_y_change<=0)): direction="up" lead_y_change=-20 lead_x_change=0 if ((event.key==pygame.K_DOWN) and (lead_y_change>=0)): direction="down" lead_y_change=20 lead_x_change=0 # change in the coordinates lead_x+=lead_x_change lead_y+=lead_y_change # appending the snakehead snakehead=[] if lead_x>800: lead_x=lead_x-800 if lead_x<0: lead_x=lead_x+800 snakehead.append(lead_x) if lead_y>600: lead_y=lead_y-600 if lead_y<0: lead_y=lead_y+600 snakehead.append(lead_y) # appending snakelist with snakehead snakelist.append(snakehead) pygame.display.update() Display.blit(background,[0,0]) Display.blit(apple,[applex,appley]) score_on_screen("SCORE:"+str(sum1-1),black,710,5) if len(snakelist)>sum1: del snakelist[0] snake(snakelist) for i in snakelist[:-1]: if snakehead==i: Display.fill(red,rect=[i[0],i[1],20,20]) time.sleep(2) over= True # sounds when snake eats a apple if(((applex +block >=lead_x>=applex)and(appley +block >=lead_y>=appley))or((applex +block >=lead_x+20>=applex)and(appley +block >=lead_y+20>=appley))): pygame.mixer.Sound.play(eat) sum1+=5 applex=random.randrange(20,780) appley=random.randrange(30,height-block) if [applex,appley] in snakelist: applex=random.randrange(20,780) appley=random.randrange(30,height-block) # increasing the speed of snake using no of frames per second pygame.display.update() if(11<=sum1<=31): FPS=13 if(31<sum1<=51): FPS=16 if(51<sum1<=71): FPS=19 if(sum1>71): FPS=25 clock.tick(FPS) pygame.quit() quit() gameintro() # calling the gameinto function gameloop() # calling the gameloop function
9f7f248318522447b5efdea8fff70fcf87253eab
[ "Python", "Text" ]
2
Text
VaishnaviDhulipalla2902/SlitherGame
b0e0ff74b4eee040d0cca872da4f88817fa43dc4
ac3fd98f421b0822be698b74265d606d4c8e2338
refs/heads/dev
<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Layouts { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using NLog.Config; using NLog.Filters; using NLog.LayoutRenderers; using NLog.LayoutRenderers.Wrappers; using NLog.Layouts; using NLog.Targets; using Xunit; public class SimpleLayoutParserTests : NLogTestBase { [Fact] public void SimpleTest() { SimpleLayout l = "${message}"; Assert.Single(l.Renderers); Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]); } [Fact] public void UnclosedTest() { var l = new SimpleLayout("${message"); Assert.Single(l.Renderers); } [Fact] public void UnknownLayoutRenderer() { Assert.Throws<NLogConfigurationException>(() => new SimpleLayout("'${{unknown-type}}'")); } [Fact] public void UnknownLayoutRendererProperty() { Assert.Throws<NLogConfigurationException>(() => new SimpleLayout("${message:unknown_item=${unknown-value}}")); } [Fact] public void UnknownConditionLayoutRenderer() { Assert.Throws<NLogConfigurationException>(() => new SimpleLayout("${when:when=Levl==LogLevel.Info:inner=Unknown}")); } [Fact] public void UnknownLayoutRendererPropertyValue() { Assert.Throws<NLogConfigurationException>(() => new SimpleLayout("'${message:withexception=${unknown-value}}'")); } [Fact] public void SingleParamTest() { SimpleLayout l = "${event-property:item=AAA}"; Assert.Single(l.Renderers); var eventPropertyLayout = l.Renderers[0] as EventPropertiesLayoutRenderer; Assert.NotNull(eventPropertyLayout); Assert.Equal("AAA", eventPropertyLayout.Item); } [Fact] public void ValueWithColonTest() { SimpleLayout l = "${event-property:item=AAA\\:}"; Assert.Single(l.Renderers); var eventPropertyLayout = l.Renderers[0] as EventPropertiesLayoutRenderer; Assert.NotNull(eventPropertyLayout); Assert.Equal("AAA:", eventPropertyLayout.Item); } [Fact] public void ValueWithBracketTest() { SimpleLayout l = "${event-property:item=AAA\\}\\:}"; Assert.Equal("${event-property:item=AAA\\}\\:}", l.Text); Assert.Single(l.Renderers); var eventPropertyLayout = l.Renderers[0] as EventPropertiesLayoutRenderer; Assert.NotNull(eventPropertyLayout); Assert.Equal("AAA}:", eventPropertyLayout.Item); } [Fact] public void DefaultValueTest() { SimpleLayout l = "${event-property:BBB}"; Assert.Single(l.Renderers); var eventPropertyLayout = l.Renderers[0] as EventPropertiesLayoutRenderer; Assert.NotNull(eventPropertyLayout); Assert.Equal("BBB", eventPropertyLayout.Item); } [Fact] public void DefaultValueWithBracketTest() { SimpleLayout l = "${event-property:AAA\\}\\:}"; Assert.Equal("${event-property:AAA\\}\\:}", l.Text); Assert.Single(l.Renderers); var eventPropertyLayout = l.Renderers[0] as EventPropertiesLayoutRenderer; Assert.NotNull(eventPropertyLayout); Assert.Equal("AAA}:", eventPropertyLayout.Item); } [Fact] public void DefaultValueWithOtherParametersTest() { SimpleLayout l = "${exception:message,type:separator=x}"; Assert.Single(l.Renderers); ExceptionLayoutRenderer elr = l.Renderers[0] as ExceptionLayoutRenderer; Assert.NotNull(elr); Assert.Equal("message,type", elr.Format); Assert.Equal("x", elr.Separator); } [Fact] public void EmptyValueTest() { SimpleLayout l = "${event-property:item=}"; Assert.Single(l.Renderers); var eventPropertyLayout = l.Renderers[0] as EventPropertiesLayoutRenderer; Assert.NotNull(eventPropertyLayout); Assert.Equal("", eventPropertyLayout.Item); } [Fact] public void NestedLayoutTest() { SimpleLayout l = "${rot13:inner=${scopenested:topFrames=3:separator=x}}"; Assert.Single(l.Renderers); var lr = l.Renderers[0] as Rot13LayoutRendererWrapper; Assert.NotNull(lr); var nestedLayout = lr.Inner as SimpleLayout; Assert.NotNull(nestedLayout); Assert.Equal("${scopenested:topFrames=3:separator=x}", nestedLayout.Text); Assert.Single(nestedLayout.Renderers); var nestedLayoutRenderer = nestedLayout.Renderers[0] as ScopeContextNestedStatesLayoutRenderer; Assert.NotNull(nestedLayoutRenderer); Assert.Equal(3, nestedLayoutRenderer.TopFrames); Assert.Equal("x", nestedLayoutRenderer.Separator.ToString()); } [Fact] public void DoubleNestedLayoutTest() { SimpleLayout l = "${rot13:inner=${rot13:inner=${scopenested:topFrames=3:separator=x}}}"; Assert.Single(l.Renderers); var lr = l.Renderers[0] as Rot13LayoutRendererWrapper; Assert.NotNull(lr); var nestedLayout0 = lr.Inner as SimpleLayout; Assert.NotNull(nestedLayout0); Assert.Equal("${rot13:inner=${scopenested:topFrames=3:separator=x}}", nestedLayout0.Text); var innerRot13 = nestedLayout0.Renderers[0] as Rot13LayoutRendererWrapper; var nestedLayout = innerRot13.Inner as SimpleLayout; Assert.NotNull(nestedLayout); Assert.Equal("${scopenested:topFrames=3:separator=x}", nestedLayout.Text); Assert.Single(nestedLayout.Renderers); var nestedLayoutRenderer = nestedLayout.Renderers[0] as ScopeContextNestedStatesLayoutRenderer; Assert.NotNull(nestedLayoutRenderer); Assert.Equal(3, nestedLayoutRenderer.TopFrames); Assert.Equal("x", nestedLayoutRenderer.Separator.ToString()); } [Fact] public void DoubleNestedLayoutWithDefaultLayoutParametersTest() { SimpleLayout l = "${rot13:${rot13:${scopenested:topFrames=3:separator=x}}}"; Assert.Single(l.Renderers); var lr = l.Renderers[0] as Rot13LayoutRendererWrapper; Assert.NotNull(lr); var nestedLayout0 = lr.Inner as SimpleLayout; Assert.NotNull(nestedLayout0); Assert.Equal("${rot13:${scopenested:topFrames=3:separator=x}}", nestedLayout0.Text); var innerRot13 = nestedLayout0.Renderers[0] as Rot13LayoutRendererWrapper; var nestedLayout = innerRot13.Inner as SimpleLayout; Assert.NotNull(nestedLayout); Assert.Equal("${scopenested:topFrames=3:separator=x}", nestedLayout.Text); Assert.Single(nestedLayout.Renderers); var nestedLayoutRenderer = nestedLayout.Renderers[0] as ScopeContextNestedStatesLayoutRenderer; Assert.NotNull(nestedLayoutRenderer); Assert.Equal(3, nestedLayoutRenderer.TopFrames); Assert.Equal("x", nestedLayoutRenderer.Separator.ToString()); } [Fact] public void AmbientPropertyTest() { SimpleLayout l = "${message:padding=10}"; Assert.Single(l.Renderers); var pad = l.Renderers[0] as PaddingLayoutRendererWrapper; Assert.NotNull(pad); var message = ((SimpleLayout)pad.Inner).Renderers[0] as MessageLayoutRenderer; Assert.NotNull(message); } [Fact] public void MissingLayoutRendererTest() { LogManager.ThrowConfigExceptions = true; Assert.Throws<NLogConfigurationException>(() => { SimpleLayout l = "${rot13:${foobar}}"; }); } [Fact] public void DoubleAmbientPropertyTest() { SimpleLayout l = "${message:uppercase=true:padding=10}"; Assert.Single(l.Renderers); var upperCase = l.Renderers[0] as UppercaseLayoutRendererWrapper; Assert.NotNull(upperCase); var pad = ((SimpleLayout)upperCase.Inner).Renderers[0] as PaddingLayoutRendererWrapper; Assert.NotNull(pad); var message = ((SimpleLayout)pad.Inner).Renderers[0] as MessageLayoutRenderer; Assert.NotNull(message); } [Fact] public void ReverseDoubleAmbientPropertyTest() { SimpleLayout l = "${message:padding=10:uppercase=true}"; Assert.Single(l.Renderers); var pad = ((SimpleLayout)l).Renderers[0] as PaddingLayoutRendererWrapper; Assert.NotNull(pad); var upperCase = ((SimpleLayout)pad.Inner).Renderers[0] as UppercaseLayoutRendererWrapper; Assert.NotNull(upperCase); var message = ((SimpleLayout)upperCase.Inner).Renderers[0] as MessageLayoutRenderer; Assert.NotNull(message); } [Fact] public void EscapeTest() { AssertEscapeRoundTrips(string.Empty); AssertEscapeRoundTrips("hello ${${}} world!"); AssertEscapeRoundTrips("hello $"); AssertEscapeRoundTrips("hello ${"); AssertEscapeRoundTrips("hello $${{"); AssertEscapeRoundTrips("hello ${message}"); AssertEscapeRoundTrips("hello ${${level}}"); AssertEscapeRoundTrips("hello ${${level}${message}}"); } [Fact] public void EvaluateTest() { var logEventInfo = LogEventInfo.CreateNullEvent(); logEventInfo.Level = LogLevel.Warn; Assert.Equal("Warn", SimpleLayout.Evaluate("${level}", logEventInfo)); } [Fact] public void EvaluateTest2() { Assert.Equal("Off", SimpleLayout.Evaluate("${level}")); Assert.Equal(string.Empty, SimpleLayout.Evaluate("${message}")); Assert.Equal(string.Empty, SimpleLayout.Evaluate("${logger}")); } private static void AssertEscapeRoundTrips(string originalString) { string escapedString = SimpleLayout.Escape(originalString); SimpleLayout l = escapedString; string renderedString = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal(originalString, renderedString); } [Fact] public void LayoutParserEscapeCodesForRegExTestV1() { ScopeContext.Clear(); var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <variable name=""searchExp"" value=""(?&lt;!\\d[ -]*)(?\u003a(?&lt;digits&gt;\\d)[ -]*)\u007b8,16\u007d(?=(\\d[ -]*)\u007b3\u007d(\\d)(?![ -]\\d))"" /> <variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=\u003a\u003a:regex=true:ignorecase=true}"" /> <targets> <target name=""d1"" type=""Debug"" layout=""${message1}"" /> </targets> <rules> <logger name=""*"" minlevel=""Trace"" writeTo=""d1"" /> </rules> </nlog>"); var d1 = configuration.FindTargetByName("d1") as DebugTarget; Assert.NotNull(d1); var layout = d1.Layout as SimpleLayout; Assert.NotNull(layout); var c = layout.Renderers.Count; Assert.Equal(1, c); var l1 = layout.Renderers[0] as ReplaceLayoutRendererWrapper; Assert.NotNull(l1); Assert.True(l1.Regex); Assert.True(l1.IgnoreCase); Assert.Equal(@"::", l1.ReplaceWith); Assert.Equal(@"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]\d))", l1.SearchFor); } [Fact] public void LayoutParserEscapeCodesForRegExTestV2() { ScopeContext.Clear(); var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <variable name=""searchExp"" value=""(?&lt;!\\d[ -]*)(?\:(?&lt;digits&gt;\\d)[ -]*)\{8,16\}(?=(\\d[ -]*)\{3\}(\\d)(?![ -]\\d))"" /> <variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=\u003a\u003a:regex=true:ignorecase=true}"" /> <targets> <target name=""d1"" type=""Debug"" layout=""${message1}"" /> </targets> <rules> <logger name=""*"" minlevel=""Trace"" writeTo=""d1"" /> </rules> </nlog>"); var d1 = configuration.FindTargetByName("d1") as DebugTarget; Assert.NotNull(d1); var layout = d1.Layout as SimpleLayout; Assert.NotNull(layout); var c = layout.Renderers.Count; Assert.Equal(1, c); var l1 = layout.Renderers[0] as ReplaceLayoutRendererWrapper; Assert.NotNull(l1); Assert.True(l1.Regex); Assert.True(l1.IgnoreCase); Assert.Equal(@"::", l1.ReplaceWith); Assert.Equal(@"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]\d))", l1.SearchFor); } [Fact] public void InnerLayoutWithColonTest_with_workaround() { SimpleLayout l = @"${when:when=1 == 1:Inner=Test${literal:text=\:} Hello}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("Test: Hello", l.Render(le)); } [Fact] public void InnerLayoutWithColonTest() { SimpleLayout l = @"${when:when=1 == 1:Inner=Test\: Hello}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("Test: Hello", l.Render(le)); } [Fact] public void InnerLayoutWithSlashSingleTest() { SimpleLayout l = @"${when:when=1 == 1:Inner=Test\Hello}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("Test\\Hello", l.Render(le)); } [Fact] public void InnerLayoutWithSlashTest() { SimpleLayout l = @"${when:when=1 == 1:Inner=Test\Hello}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("Test\\Hello", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest() { SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello\}}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("Test{Hello}", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest2() { SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello\\}}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal(@"Test{Hello\}", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest_reverse() { SimpleLayout l = @"${when:Inner=Test{Hello\}:when=1 == 1}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("Test{Hello}", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest_no_escape() { SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello}}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("Test{Hello}", l.Render(le)); } [Fact] public void InnerLayoutWithHashTest() { SimpleLayout l = @"${when:when=1 == 1:inner=Log_{#\}.log}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("Log_{#}.log", l.Render(le)); } [Fact] public void InnerLayoutWithHashTest_need_escape() { SimpleLayout l = @"${when:when=1 == 1:inner=L\}.log}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("L}.log", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest_needEscape() { SimpleLayout l = @"${when:when=1 == 1:inner=\}{.log}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("}{.log", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest_needEscape2() { SimpleLayout l = @"${when:when=1 == 1:inner={\}\}{.log}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("{}}{.log", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest_needEscape3() { SimpleLayout l = @"${when:when=1 == 1:inner={\}\}\}.log}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("{}}}.log", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest_needEscape4() { SimpleLayout l = @"${when:when=1 == 1:inner={\}\}\}.log}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("{}}}.log", l.Render(le)); } [Fact] public void InnerLayoutWithBracketsTest_needEscape5() { SimpleLayout l = @"${when:when=1 == 1:inner=\}{a\}.log}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("}{a}.log", l.Render(le)); } [Fact] public void InnerLayoutWithHashTest_and_layoutrender() { SimpleLayout l = @"${when:when=1 == 1:inner=${counter}/Log_{#\}.log}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("1/Log_{#}.log", l.Render(le)); } [Fact] public void InvalidLayoutWillParsePartly() { using (new NoThrowNLogExceptions()) { SimpleLayout l = @"aaa ${iDontExist} bbb"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("aaa bbb", l.Render(le)); } } [Fact] public void InvalidLayoutWillThrowIfExceptionThrowingIsOn() { LogManager.ThrowConfigExceptions = true; Assert.Throws<NLogConfigurationException>(() => { SimpleLayout l = @"aaa ${iDontExist} bbb"; }); } [Fact] public void InvalidLayoutWithExistingRenderer_WillThrowIfExceptionThrowingIsOn() { ConfigurationItemFactory.Default.LayoutRendererFactory.RegisterType<LayoutRendererWithListParam>("layoutrenderer-with-list"); LogManager.ThrowConfigExceptions = true; Assert.Throws<NLogConfigurationException>(() => { SimpleLayout l = @"${layoutrenderer-with-list:}"; }); } [Fact] public void UnknownPropertyInLayout_WillThrowIfExceptionThrowingIsOn() { ConfigurationItemFactory.Default.LayoutRendererFactory.RegisterType<LayoutRendererWithListParam>("layoutrenderer-with-list"); LogManager.ThrowConfigExceptions = true; Assert.Throws<NLogConfigurationException>(() => { SimpleLayout l = @"${layoutrenderer-with-list:iDontExist=1}"; }); } /// <summary> /// /// Test layout with Generic List type. - is the separator /// /// /// </summary> /// <remarks> /// comma escape is backtick (cannot use backslash due to layout parse) /// </remarks> /// <param name="input"></param> /// <param name="propname"></param> /// <param name="expected"></param> [Theory] [InlineData("2,3,4", "numbers", "2-3-4")] [InlineData("a,b,c", "Strings", "a-b-c")] [InlineData("a,b,c", "Objects", "a-b-c")] [InlineData("a,,b,c", "Strings", "a--b-c")] [InlineData("a`b,c", "Strings", "a`b-c")] [InlineData("a\'b,c", "Strings", "a'b-c")] [InlineData("'a,b',c", "Strings", "a,b-c")] [InlineData("2.0,3.0,4.0", "doubles", "2-3-4")] [InlineData("2.1,3.2,4.3", "doubles", "2.1-3.2-4.3")] [InlineData("Ignore,Neutral,Ignore", "enums", "Ignore-Neutral-Ignore")] [InlineData("ASCII,ISO-8859-1, UTF-8", "encodings", "us-ascii-iso-8859-1-utf-8")] [InlineData("ASCII,ISO-8859-1,UTF-8", "encodings", "us-ascii-iso-8859-1-utf-8")] [InlineData("Value1,Value3,Value2", "FlagEnums", "Value1-Value3-Value2")] [InlineData("2,3,4", "IEnumerableNumber", "2-3-4")] [InlineData("2,3,4", "IListNumber", "2-3-4")] [InlineData("2,3,4", "HashsetNumber", "2-3-4")] #if !NET35 [InlineData("2,3,4", "ISetNumber", "2-3-4")] #endif [InlineData("a,b,c", "IEnumerableString", "a-b-c")] [InlineData("a,b,c", "IListString", "a-b-c")] [InlineData("a,b,c", "HashSetString", "a-b-c")] #if !NET35 [InlineData("a,b,c", "ISetString", "a-b-c")] #endif public void LayoutWithListParamTest(string input, string propname, string expected) { ConfigurationItemFactory.Default.LayoutRendererFactory.RegisterType<LayoutRendererWithListParam>("layoutrenderer-with-list"); SimpleLayout l = $@"${{layoutrenderer-with-list:{propname}={input}}}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); var actual = l.Render(le); Assert.Equal(expected, actual); } [Theory] [InlineData("2,,3,4", "numbers")] [InlineData("a,bc", "numbers")] [InlineData("value1,value10", "FlagEnums")] public void LayoutWithListParamTest_incorrect(string input, string propname) { //note flags enum already supported //can;t convert empty to int ConfigurationItemFactory.Default.LayoutRendererFactory.RegisterType<LayoutRendererWithListParam>("layoutrenderer-with-list"); Assert.Throws<NLogConfigurationException>(() => { SimpleLayout l = $@"${{layoutrenderer-with-list:{propname}={input}}}"; }); } [Theory] [InlineData(@" ${literal:text={0\} {1\}}")] [InlineData(@" ${cached:${literal:text={0\} {1\}}}")] [InlineData(@" ${cached:${cached:${literal:text={0\} {1\}}}}")] [InlineData(@" ${cached:${cached:${cached:${literal:text={0\} {1\}}}}}")] [InlineData(@"${cached:${cached:${cached:${cached:${literal:text={0\} {1\}}}}}}")] public void Render_EscapedBrackets_ShouldRenderAllBrackets(string input) { SimpleLayout simple = input.Trim(); var result = simple.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("{0} {1}", result); } [Fact] public void FuncLayoutRendererRegisterTest1() { var theAnswer = "42"; var logFactory = new LogFactory().Setup().SetupExtensions(ext => ext.RegisterLayoutRenderer("the-answer", (evt) => theAnswer)) .LoadConfiguration(builder => builder.ForLogger().WriteTo(new DebugTarget() { Name = "Debug", Layout = "${the-answer}" })).LogFactory; logFactory.GetCurrentClassLogger().Info("Hello World"); AssertDebugLastMessage("Debug", theAnswer, logFactory); } [Fact] [Obsolete("Instead override type-creation by calling NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public void FuncLayoutRendererRegisterTest1_Legacy() { LayoutRenderer.Register("the-answer", (info) => "42"); Layout l = "${the-answer}"; var result = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("42", result); } [Fact] public void FuncLayoutRendererFluentMethod_ThreadAgnostic_Test() { // Arrange var layout = Layout.FromMethod(l => "42", LayoutRenderOptions.ThreadAgnostic); // Act var result = layout.Render(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal("42", result); Assert.True(layout.ThreadAgnostic); } [Fact] public void FuncLayoutRendererFluentMethod_Test() { // Arrange var layout = Layout.FromMethod(l => "42", LayoutRenderOptions.None); // Act var result = layout.Render(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal("42", result); Assert.False(layout.ThreadAgnostic); } [Fact] public void FuncLayoutRendererFluentMethod_NullThrows_Test() { // Arrange Assert.Throws<ArgumentNullException>(() => Layout.FromMethod(null)); } [Fact] public void FuncLayoutRendererRegisterTest1WithXML() { var logFactory = new LogFactory().Setup().SetupExtensions(ext => ext.RegisterLayoutRenderer("the-answer", (evt) => 42)) .LoadConfigurationFromXml( @"<nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout= 'TheAnswer=${the-answer:Format=D3}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; logFactory.GetCurrentClassLogger().Info("test1"); AssertDebugLastMessage("debug", "TheAnswer=042", logFactory); } [Fact] [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public void FuncLayoutRendererRegisterTest1WithXML_Legacy() { LayoutRenderer.Register("the-answer", (info) => 42); LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout= 'TheAnswer=${the-answer:Format=D3}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); var logger = LogManager.GetCurrentClassLogger(); logger.Debug("test1"); AssertDebugLastMessage("debug", "TheAnswer=042"); } [Fact] public void FuncLayoutRendererRegisterTest2() { var logFactory = new LogFactory().Setup().SetupExtensions(ext => ext.RegisterLayoutRenderer("message-length", (evt) => evt.Message.Length)) .LoadConfiguration(builder => builder.ForLogger().WriteTo(new DebugTarget() { Name = "Debug", Layout = "${message-length" })).LogFactory; logFactory.GetCurrentClassLogger().Info("1234567890"); AssertDebugLastMessage("Debug", "10", logFactory); } [Fact] [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public void FuncLayoutRendererRegisterTest2_Legacy() { LayoutRenderer.Register("message-length", (info) => info.Message.Length); Layout l = "${message-length}"; var result = l.Render(LogEventInfo.Create(LogLevel.Error, "logger-adhoc", "1234567890")); Assert.Equal("10", result); } [Fact] public void SimpleLayout_FromString_ThrowConfigExceptions() { Assert.Throws<NLogConfigurationException>(() => Layout.FromString("${evil}", true)); } [Fact] public void SimpleLayout_FromString_NoThrowConfigExceptions() { Assert.NotNull(Layout.FromString("${evil}", false)); } [Theory] [InlineData("", true)] [InlineData(null, true)] [InlineData("'a'", true)] [InlineData("${gdc:a}", false)] [InlineData("${threadname}", false)] public void FromString_isFixedText(string input, bool expected) { // Act var layout = (SimpleLayout)Layout.FromString(input); layout.Initialize(null); // Assert Assert.Equal(expected, layout.IsFixedText); } [Theory] [InlineData("", true)] [InlineData(null, true)] [InlineData("'a'", true)] [InlineData("${gdc:a}", true)] [InlineData("${threadname}", false)] public void FromString_isThreadAgnostic(string input, bool expected) { // Act var layout = (SimpleLayout)Layout.FromString(input); layout.Initialize(null); // Assert Assert.Equal(expected, layout.ThreadAgnostic); } [Theory] [InlineData("", "")] [InlineData(null, "")] [InlineData("'a'", "'a'")] [InlineData("${gdc:a}", "")] public void Render(string input, string expected) { var layout = (SimpleLayout)Layout.FromString(input); // Act var result = layout.Render(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal(expected, result); } [Fact] public void Parse_AppDomainFixedOutput_ConvertToLiteral() { // Arrange var input = "${newline}"; // Act var layout = (SimpleLayout)Layout.FromString(input); // Assert var single = Assert.Single(layout.Renderers); Assert.IsType<LiteralLayoutRenderer>(single); } [Fact] public void Parse_MultipleAppDomainFixedOutput_ConvertSingleToLiteral() { // Arrange var input = "${newline}${machinename}"; // Act var layout = (SimpleLayout)Layout.FromString(input); // Assert var single = Assert.Single(layout.Renderers); Assert.IsType<LiteralLayoutRenderer>(single); } [Fact] public void Parse_AppDomainFixedOutputWithRawValue_ConvertSingleToLiteralAndKeepRawValue() { // Arrange var input = "${processid}"; // Act var layout = (SimpleLayout)Layout.FromString(input); // Assert Assert.True(layout.IsFixedText); var single = Assert.Single(layout.Renderers); Assert.IsType<LiteralWithRawValueLayoutRenderer>(single); var succeeded = layout.TryGetRawValue(LogEventInfo.CreateNullEvent(), out var rawValue); var rawValueInt = Assert.IsType<int>(rawValue); Assert.True(succeeded); Assert.True(rawValueInt > 0); } /// <summary> /// Combined literals should not support rawValue /// </summary> [Theory] [InlineData("${newline}${processid}")] [InlineData("${processid}${processid}")] [InlineData("${processid}${processname}")] [InlineData("${processname}${processid}")] [InlineData("${processname}-${processid}")] public void Parse_Multiple_ConvertSingleToLiteralWithoutRaw(string input) { // Act var layout = (SimpleLayout)Layout.FromString(input); // Assert var single = Assert.Single(layout.Renderers); Assert.IsType<LiteralLayoutRenderer>(single); } private class LayoutRendererWithListParam : LayoutRenderer { public List<double> Doubles { get; set; } public List<FilterResult> Enums { get; set; } public List<Config.TargetConfigurationTests.MyFlagsEnum> FlagEnums { get; set; } public List<int> Numbers { get; set; } public List<string> Strings { get; set; } public List<object> Objects { get; set; } public List<Encoding> Encodings { get; set; } public IEnumerable<string> IEnumerableString { get; set; } public IEnumerable<int> IEnumerableNumber { get; set; } public IList<string> IListString { get; set; } public IList<int> IListNumber { get; set; } #if !NET35 public ISet<string> ISetString { get; set; } public ISet<int> ISetNumber { get; set; } #endif public HashSet<int> HashSetNumber { get; set; } public HashSet<string> HashSetString { get; set; } /// <summary> /// Renders the specified environmental information and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { Append(builder, Strings); AppendFormattable(builder, Numbers); AppendFormattable(builder, Enums); AppendFormattable(builder, FlagEnums); AppendFormattable(builder, Doubles); Append(builder, Encodings?.Select(e => e.BodyName).ToList()); Append(builder, Objects); Append(builder, IEnumerableString); AppendFormattable(builder, IEnumerableNumber); Append(builder, IListString); AppendFormattable(builder, IListNumber); #if !NET35 Append(builder, ISetString); AppendFormattable(builder, ISetNumber); #endif Append(builder, HashSetString); AppendFormattable(builder, HashSetNumber); } private static void Append<T>(StringBuilder builder, IEnumerable<T> items) { if (items != null) builder.Append(string.Join("-", items.ToArray())); } private static void AppendFormattable<T>(StringBuilder builder, IEnumerable<T> items) where T : IFormattable { if (items != null) builder.Append(string.Join("-", items.Select(it => it.ToString(null, CultureInfo.InvariantCulture)).ToArray())); } } } } <file_sep>Package | Build status | NuGet -------- | :------------ | :------------ NLog | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog/master.svg)](https://ci.appveyor.com/project/nlog/nlog/branch/master) | [![NuGet](https://img.shields.io/nuget/vpre/nlog.svg)](https://www.nuget.org/packages/NLog) [NLog.Extensions.Logging](https://github.com/NLog/NLog.Extensions.Logging) | [![Build status](https://img.shields.io/appveyor/ci/nlog/nlog-framework-logging/master.svg)](https://ci.appveyor.com/project/nlog/nlog-framework-logging/branch/master) | [![NuGet Pre Release](https://img.shields.io/nuget/vpre/NLog.Extensions.Logging.svg)](https://www.nuget.org/packages/NLog.Extensions.Logging) NLog.Config | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog/master.svg)](https://ci.appveyor.com/project/nlog/nlog/branch/master) | [![NuGet package](https://img.shields.io/nuget/v/NLog.Config.svg)](https://www.nuget.org/packages/NLog.Config) [NLog.Contrib.ActiveMQ](https://github.com/NLog/NLog.Contrib.ActiveMQ) | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog-contrib-activemq/master.svg)](https://ci.appveyor.com/project/nlog/nlog-contrib-activemq/branch/master) | [![NuGet package](https://img.shields.io/nuget/v/NLog.Contrib.ActiveMQ.svg)](https://www.nuget.org/packages/NLog.Contrib.ActiveMQ) NLog.Database | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog/master.svg)](https://ci.appveyor.com/project/nlog/nlog/branch/master) | [![NuGet](https://img.shields.io/nuget/vpre/NLog.Database.svg)](https://www.nuget.org/packages/NLog.Database) [NLog.Elmah](https://github.com/NLog/NLog.Elmah) | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog-Elmah/master.svg)](https://ci.appveyor.com/project/nlog/nlog-Elmah/branch/master) | [![NuGet package](https://img.shields.io/nuget/v/NLog.Elmah.svg)](https://www.nuget.org/packages/NLog.Elmah) [NLog.Etw](https://github.com/NLog/NLog.Etw) | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog-etw/master.svg)](https://ci.appveyor.com/project/nlog/nlog-etw/branch/master) | [![NuGet package](https://img.shields.io/nuget/v/NLog.Etw.svg)](https://www.nuget.org/packages/NLog.Etw) [NLog.DiagnosticSource](https://github.com/NLog/NLog.DiagnosticSource) | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/NLog-DiagnosticSource/master.svg)](https://ci.appveyor.com/project/nlog/NLog-DiagnosticSource/branch/master) | [![NuGet package](https://img.shields.io/nuget/v/NLog.DiagnosticSource.svg)](https://www.nuget.org/packages/NLog.DiagnosticSource) [NLog.InstallNLogConfig](https://github.com/NLog/NLog.InstallNLogConfig) | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog-InstallNLogConfig/master.svg)](https://ci.appveyor.com/project/nlog/nlog-InstallNLogConfig/branch/master) | [![NuGet package](https://img.shields.io/nuget/v/NLog.InstallNLogConfig.svg)](https://www.nuget.org/packages/NLog.InstallNLogConfig) [NLog.MailKit](https://github.com/NLog/NLog.MailKit) | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog-mailkit/master.svg)](https://ci.appveyor.com/project/nlog/nlog-mailkit/branch/master) | [![NuGet package](https://img.shields.io/nuget/v/NLog.MailKit.svg)](https://www.nuget.org/packages/NLog.MailKit) [NLog.ManualFlush](https://github.com/NLog/NLog.ManualFlush) | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog-ManualFlush/master.svg)](https://ci.appveyor.com/project/nlog/nlog-ManualFlush/branch/master) | [![NuGet package](https://img.shields.io/nuget/v/NLog.ManualFlush.svg)](https://www.nuget.org/packages/NLog.ManualFlush) NLog.MSMQ | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog/master.svg)](https://ci.appveyor.com/project/nlog/nlog/branch/master) | [![NuGet](https://img.shields.io/nuget/vpre/NLog.MSMQ.svg)](https://www.nuget.org/packages/NLog.MSMQ) NLog.OutputDebugString | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog/master.svg)](https://ci.appveyor.com/project/nlog/nlog/branch/master) | [![NuGet](https://img.shields.io/nuget/vpre/NLog.OutputDebugString.svg)](https://www.nuget.org/packages/NLog.OutputDebugString) NLog.PerformanceCounter | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog/master.svg)](https://ci.appveyor.com/project/nlog/nlog/branch/master) | [![NuGet](https://img.shields.io/nuget/vpre/NLog.PerformanceCounter.svg)](https://www.nuget.org/packages/NLog.PerformanceCounter) NLog.Schema | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog/master.svg)](https://ci.appveyor.com/project/nlog/nlog/branch/master) | [![NuGet package](https://img.shields.io/nuget/vpre/NLog.Schema.svg)](https://www.nuget.org/packages/NLog.Schema) [NLog.Targets.AppCenter](https://github.com/NLog/NLog.AzureAppCenter) | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog-azureappcenter/master.svg)](https://ci.appveyor.com/project/nlog/nlog-azureappcenter/branch/master) | [![NuGet package](https://img.shields.io/nuget/v/NLog.Targets.AppCenter.svg)](https://www.nuget.org/packages/NLog.Targets.AppCenter) NLog.Wcf | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog/master.svg)](https://ci.appveyor.com/project/nlog/nlog/branch/master) | [![NuGet](https://img.shields.io/nuget/vpre/NLog.Wcf.svg)](https://www.nuget.org/packages/NLog.Wcf) [NLog.Web](https://github.com/NLog/NLog.Web) | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog-web/master.svg)](https://ci.appveyor.com/project/nlog/nlog-web/branch/master) | [![NuGet package](https://img.shields.io/nuget/vpre/NLog.Web.svg)](https://www.nuget.org/packages/NLog.Web) [NLog.Web for ASP.NET Core](https://github.com/NLog/NLog.Web) | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog-web/master.svg)](https://ci.appveyor.com/project/nlog/nlog-web/branch/master) | [![NuGet package](https://img.shields.io/nuget/vpre/NLog.Web.AspNetCore.svg)](https://www.nuget.org/packages/NLog.Web.AspNetCore) NLog.WindowsEventLog | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog/master.svg)](https://ci.appveyor.com/project/nlog/nlog/branch/master) | [![NuGet](https://img.shields.io/nuget/vpre/NLog.WindowsEventLog.svg)](https://www.nuget.org/packages/NLog.WindowsEventLog) NLog.WindowsIdentity | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog/master.svg)](https://ci.appveyor.com/project/nlog/nlog/branch/master) | [![NuGet](https://img.shields.io/nuget/vpre/NLog.WindowsIdentity.svg)](https://www.nuget.org/packages/NLog.WindowsIdentity) NLog.WindowsRegistry | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog/master.svg)](https://ci.appveyor.com/project/nlog/nlog/branch/master) | [![NuGet](https://img.shields.io/nuget/vpre/NLog.WindowsRegistry.svg)](https://www.nuget.org/packages/NLog.WindowsRegistry) [NLog.Windows.Forms](https://github.com/NLog/NLog.Windows.Forms) | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog-windows-forms/master.svg)](https://ci.appveyor.com/project/nlog/nlog-windows-forms/branch/master) | [![NuGet package](https://img.shields.io/nuget/v/NLog.Windows.Forms.svg)](https://www.nuget.org/packages/NLog.Windows.Forms) [NLog.Owin.Logging](https://github.com/NLog/NLog.Owin.Logging) | [![AppVeyor](https://img.shields.io/appveyor/ci/nlog/nlog-owin-logging/master.svg)](https://ci.appveyor.com/project/nlog/nlog-owin-logging/branch/master) | [![NuGet package](https://img.shields.io/nuget/v/NLog.Owin.Logging.svg)](https://www.nuget.org/packages/NLog.Owin.Logging) <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Diagnostics; using NLog; using NLog.Config; namespace LoaderTestPublic { public sealed class NLogPackageLoader { public static void Preload() { // Nothing to do } } } namespace LoaderTestInternal { /// <summary> /// private /// </summary> internal sealed class NLogPackageLoader { public static void Preload() { // Nothing to do } } } namespace LoaderTestPrivateNested { internal class SomeType { private sealed class NLogPackageLoader { public static void Preload(ConfigurationItemFactory fact) { if (fact is null) { throw new ArgumentNullException(nameof(fact)); } } } } } namespace LoaderTestPrivateNestedStatic { internal sealed class SomeType { private static class NLogPackageLoader { public static void Preload() { // Nothing to do } } } } namespace LoaderTestWrong1 { public sealed class NLogPackageLoader { [DebuggerStepThrough] public static void Preload() { throw new NLogRuntimeException("ow noos"); } } } namespace LoaderTestWrong2 { public sealed class NLogPackageLoader { public void Preload() { //im not static } } } namespace LoaderTestWrong3 { public sealed class NLogPackageLoader { public static void Preload(int arg1, int arg2) { //I have args } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using NLog.Config; using NLog.Internal; /// <summary> /// A specialized layout that renders CSV-formatted events. /// </summary> /// <remarks> /// <para> /// If <see cref="LayoutWithHeaderAndFooter.Header"/> is set, then the header generation with column names will be disabled. /// </para> /// <a href="https://github.com/NLog/NLog/wiki/JsonLayout">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/NLog/NLog/wiki/JsonLayout">Documentation on NLog Wiki</seealso> [Layout("CsvLayout")] [ThreadAgnostic] [AppDomainFixedOutput] public class CsvLayout : LayoutWithHeaderAndFooter { private string _actualColumnDelimiter; private string _doubleQuoteChar; private char[] _quotableCharacters; private Layout[] _precalculateLayouts = null; /// <summary> /// Initializes a new instance of the <see cref="CsvLayout"/> class. /// </summary> public CsvLayout() { Layout = this; Header = new CsvHeaderLayout(this); Footer = null; } /// <summary> /// Gets the array of parameters to be passed. /// </summary> /// <docgen category='Layout Options' order='10' /> [ArrayParameter(typeof(CsvColumn), "column")] public IList<CsvColumn> Columns { get; } = new List<CsvColumn>(); /// <summary> /// Gets or sets a value indicating whether CVS should include header. /// </summary> /// <value>A value of <c>true</c> if CVS should include header; otherwise, <c>false</c>.</value> /// <docgen category='Layout Options' order='10' /> public bool WithHeader { get; set; } = true; /// <summary> /// Gets or sets the column delimiter. /// </summary> /// <docgen category='Layout Options' order='10' /> public CsvColumnDelimiterMode Delimiter { get; set; } = CsvColumnDelimiterMode.Auto; /// <summary> /// Gets or sets the quoting mode. /// </summary> /// <docgen category='Layout Options' order='10' /> public CsvQuotingMode Quoting { get; set; } = CsvQuotingMode.Auto; /// <summary> /// Gets or sets the quote Character. /// </summary> /// <docgen category='Layout Options' order='10' /> public string QuoteChar { get; set; } = "\""; /// <summary> /// Gets or sets the custom column delimiter value (valid when ColumnDelimiter is set to 'Custom'). /// </summary> /// <docgen category='Layout Options' order='10' /> public string CustomColumnDelimiter { get; set; } /// <inheritdoc/> protected override void InitializeLayout() { if (!WithHeader) { Header = null; } base.InitializeLayout(); switch (Delimiter) { case CsvColumnDelimiterMode.Auto: _actualColumnDelimiter = CultureInfo.CurrentCulture.TextInfo.ListSeparator; break; case CsvColumnDelimiterMode.Comma: _actualColumnDelimiter = ","; break; case CsvColumnDelimiterMode.Semicolon: _actualColumnDelimiter = ";"; break; case CsvColumnDelimiterMode.Pipe: _actualColumnDelimiter = "|"; break; case CsvColumnDelimiterMode.Tab: _actualColumnDelimiter = "\t"; break; case CsvColumnDelimiterMode.Space: _actualColumnDelimiter = " "; break; case CsvColumnDelimiterMode.Custom: _actualColumnDelimiter = CustomColumnDelimiter; break; } _quotableCharacters = (QuoteChar + "\r\n" + _actualColumnDelimiter).ToCharArray(); _doubleQuoteChar = QuoteChar + QuoteChar; _precalculateLayouts = ResolveLayoutPrecalculation(Columns.Select(cln => cln.Layout)); } /// <inheritdoc/> protected override void CloseLayout() { _precalculateLayouts = null; base.CloseLayout(); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { PrecalculateBuilderInternal(logEvent, target, _precalculateLayouts); } /// <inheritdoc/> protected override string GetFormattedMessage(LogEventInfo logEvent) { return RenderAllocateBuilder(logEvent); } /// <inheritdoc/> protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < Columns.Count; i++) { Layout columnLayout = Columns[i].Layout; RenderColumnLayout(logEvent, columnLayout, Columns[i]._quoting ?? Quoting, target, i); } } private void RenderColumnLayout(LogEventInfo logEvent, Layout columnLayout, CsvQuotingMode quoting, StringBuilder target, int i) { if (i != 0) { target.Append(_actualColumnDelimiter); } if (quoting == CsvQuotingMode.All) { target.Append(QuoteChar); } int orgLength = target.Length; columnLayout.Render(logEvent, target); if (orgLength != target.Length && ColumnValueRequiresQuotes(quoting, target, orgLength)) { string columnValue = target.ToString(orgLength, target.Length - orgLength); target.Length = orgLength; if (quoting != CsvQuotingMode.All) { target.Append(QuoteChar); } target.Append(columnValue.Replace(QuoteChar, _doubleQuoteChar)); target.Append(QuoteChar); } else { if (quoting == CsvQuotingMode.All) { target.Append(QuoteChar); } } } /// <summary> /// Get the headers with the column names. /// </summary> /// <returns></returns> private void RenderHeader(StringBuilder sb) { LogEventInfo logEvent = LogEventInfo.CreateNullEvent(); //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < Columns.Count; i++) { CsvColumn col = Columns[i]; var columnLayout = new SimpleLayout(new LayoutRenderers.LayoutRenderer[] { new LayoutRenderers.LiteralLayoutRenderer(col.Name) }, col.Name, ConfigurationItemFactory.Default); columnLayout.Initialize(LoggingConfiguration); RenderColumnLayout(logEvent, columnLayout, col._quoting ?? Quoting, sb, i); } } private bool ColumnValueRequiresQuotes(CsvQuotingMode quoting, StringBuilder sb, int startPosition) { switch (quoting) { case CsvQuotingMode.Nothing: return false; case CsvQuotingMode.All: if (QuoteChar.Length == 1) return sb.IndexOf(QuoteChar[0], startPosition) >= 0; else return sb.IndexOfAny(_quotableCharacters, startPosition) >= 0; case CsvQuotingMode.Auto: default: return sb.IndexOfAny(_quotableCharacters, startPosition) >= 0; } } /// <summary> /// Header with column names for CSV layout. /// </summary> [ThreadAgnostic] [AppDomainFixedOutput] internal sealed class CsvHeaderLayout : Layout { private readonly CsvLayout _parent; private string _headerOutput; /// <summary> /// Initializes a new instance of the <see cref="CsvHeaderLayout"/> class. /// </summary> /// <param name="parent">The parent.</param> public CsvHeaderLayout(CsvLayout parent) { _parent = parent; } /// <inheritdoc/> protected override void InitializeLayout() { _headerOutput = null; base.InitializeLayout(); } private string GetHeaderOutput() { return _headerOutput ?? (_headerOutput = BuilderHeaderOutput()); } private string BuilderHeaderOutput() { StringBuilder sb = new StringBuilder(); _parent.RenderHeader(sb); return sb.ToString(); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { // Precalculation and caching is not needed } /// <inheritdoc/> protected override string GetFormattedMessage(LogEventInfo logEvent) { return GetHeaderOutput(); } /// <inheritdoc/> protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { target.Append(GetHeaderOutput()); } } /// <inheritdoc/> public override string ToString() { return ToStringWithNestedItems(Columns, c => c.Name); } } }<file_sep>using System; using NLog; using NLog.Targets; using NLog.Win32.Targets; class Example { static void Main(string[] args) { OutputDebugStringTarget target = new OutputDebugStringTarget(); target.Layout = "${message}"; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http.Headers; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using System.Xml.Serialization; #if !NETSTANDARD using System.Web.Http; using System.Web.Http.Dependencies; using Microsoft.Owin.Hosting; using Owin; #endif using NLog.Internal; using NLog.Targets; using Xunit; public class WebServiceTargetTests : NLogTestBase { public WebServiceTargetTests() { LogManager.ThrowExceptions = true; } [Fact] public void WebServiceWithEmptyUrl() { var logFactory = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(new WebServiceTarget() { Url = "" }); builder.ForLogger().WriteTo(new WebServiceTarget() { Url = "${eventproperty:Url}" }); }).LogFactory; logFactory.GetCurrentClassLogger().WithProperty("Url", "").Info("Test"); Assert.NotNull(logFactory.Configuration); } [Fact] public void WebServiceWithInvalidUrl() { var logFactory = new LogFactory().Setup().LoadConfiguration(builder => { var configException = Assert.Throws<NLogConfigurationException>(() => builder.ForLogger().WriteTo(new WebServiceTarget() { Url = "!!!" })); Assert.Contains("!!!", configException.Message); builder.ForLogger().WriteTo(new WebServiceTarget() { Url = "${eventproperty:Url}" }); }).LogFactory; logFactory.GetCurrentClassLogger().WithProperty("Url", "!!!").Info("Test"); logFactory.ThrowExceptions = true; Assert.Throws<NLogRuntimeException>(() => logFactory.GetCurrentClassLogger().WithProperty("Url", "!!!").Info("Test")); } [Fact] public void WebserviceTest_httppost_utf8_default_no_bom() { WebserviceTest_httppost_utf8("", false); } [Fact] public void WebserviceTest_httppost_utf8_with_bom() { WebserviceTest_httppost_utf8("includeBOM='true'", true); } [Fact] public void WebserviceTest_httppost_utf8_no_boml() { WebserviceTest_httppost_utf8("includeBOM='false'", false); } private static void WebserviceTest_httppost_utf8(string bomAttr, bool includeBom) { var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterAssembly(typeof(WebServiceTarget).Assembly)) .LoadConfigurationFromXml(@" <nlog> <targets> <target type='WebService' name='webservice' url='http://localhost:57953/Home/Foo2' protocol='HttpPost' " + bomAttr + @" encoding='UTF-8' methodName='Foo'> <parameter name='empty' type='System.String' layout=''/> <!-- work around so the guid is decoded properly --> <parameter name='guid' type='System.String' layout='${guid}'/> <parameter name='m' type='System.String' layout='${message}'/> <parameter name='date' type='System.String' layout='${longdate}'/> <parameter name='logger' type='System.String' layout='${logger}'/> <parameter name='level' type='System.String' layout='${level}'/> </target> </targets> </nlog>").LogFactory; var target = logFactory.Configuration.FindTargetByName("webservice") as WebServiceTarget; Assert.NotNull(target); Assert.Equal(6, target.Parameters.Count); Assert.Equal("utf-8", target.Encoding.WebName); //async call with mockup stream #pragma warning disable SYSLIB0014 // Type or member is obsolete var webRequest = System.Net.WebRequest.Create("http://www.test.com"); #pragma warning restore SYSLIB0014 // Type or member is obsolete var httpWebRequest = (HttpWebRequest)webRequest; var streamMock = new StreamMock(); //event for async testing var counterEvent = new ManualResetEvent(false); var parameterValues = new object[] { "", "336cec87129942eeabab3d8babceead7", "Debg", "2014-06-26 23:15:14.6348", "TestClient.Program", "Debug" }; target.DoInvoke(parameterValues, c => counterEvent.Set(), httpWebRequest, (request,callback) => { var t = new Task(() => { }); callback(t); return t; }, (request,result) => streamMock); counterEvent.WaitOne(10000); var bytes = streamMock.bytes; var url = streamMock.stringed; const string expectedUrl = "empty=&guid=336cec87129942eeabab3d8babceead7&m=Debg&date=2014-06-26+23%3a15%3a14.6348&logger=TestClient.Program&level=Debug"; Assert.Equal(expectedUrl, url); Assert.True(bytes.Length > 3); //not bom var possbleBomBytes = bytes.Take(3).ToArray(); if (includeBom) { Assert.Equal(possbleBomBytes, System.Text.Encoding.UTF8.GetPreamble()); } else { Assert.NotEqual(possbleBomBytes, System.Text.Encoding.UTF8.GetPreamble()); } Assert.Equal(bytes.Length, includeBom ? 126 : 123); } /// <summary> /// Mock the stream /// </summary> private class StreamMock : MemoryStream { public byte[] bytes; public string stringed; /// <summary> /// Releases the unmanaged resources used by the <see cref="T:System.IO.MemoryStream"/> class and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { //save stuff before dispose Flush(); bytes = ToArray(); stringed = StreamToString(this); base.Dispose(disposing); } private static string StreamToString(Stream s) { s.Position = 0; var sr = new StreamReader(s); return sr.ReadToEnd(); } } #if !NETSTANDARD private static string getNewWsAddress() { string WsAddress = "http://localhost:9000/"; return WsAddress.Substring(0, WsAddress.Length - 5) + (9000 + System.Threading.Interlocked.Increment(ref _portOffset)).ToString() + "/"; } private static int _portOffset; /// <summary> /// Test the Webservice with REST api - <see cref="WebServiceProtocol.HttpPost"/> (only checking for no exception) /// </summary> [Fact] public void WebserviceTest_restapi_httppost() { string wsAddress = getNewWsAddress(); var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterAssembly(typeof(WebServiceTarget).Assembly)) .LoadConfigurationFromXml($@" <nlog throwExceptions='true'> <targets> <target type='WebService' name='ws' url='{wsAddress}{"api/logme"}' protocol='HttpPost' encoding='UTF-8' > <parameter name='param1' type='System.String' layout='${{message}}'/> <parameter name='param2' type='System.String' layout='${{level}}'/> </target> </targets> <rules> <logger name='*' writeTo='ws' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetCurrentClassLogger(); var context = new LogMeController.TestContext(); context.ResetState(2); var message1 = "message 1 with a post"; var message2 = "a b c é k è ï ?"; StartOwinTest(wsAddress, context, () => { logger.Info(message1); logger.Info(message2); }); Assert.Equal(0, context.CountdownEvent.CurrentCount); Assert.Equal(2, context.ReceivedLogsPostParam1.Count); CheckQueueMessage(message1, context.ReceivedLogsPostParam1); CheckQueueMessage(message2, context.ReceivedLogsPostParam1); } /// <summary> /// Test the Webservice with REST api - <see cref="WebServiceProtocol.HttpGet"/> (only checking for no exception) /// </summary> [Fact] public void WebserviceTest_restapi_httpget() { string wsAddress = getNewWsAddress(); var logger = SetUpHttpGetWebservice(wsAddress, "api/logme").GetCurrentClassLogger(); var context = new LogMeController.TestContext(); context.ResetState(2); var message1 = "message 1 with a post"; var message2 = "a b c é k è ï ?"; StartOwinTest(wsAddress, context, () => { logger.Info(message1); logger.Info(message2); }); Assert.Equal(0, context.CountdownEvent.CurrentCount); Assert.Equal(2, context.ReceivedLogsGetParam1.Count); CheckQueueMessage(message1, context.ReceivedLogsGetParam1); CheckQueueMessage(message2, context.ReceivedLogsGetParam1); } /// <summary> /// Test the Webservice with REST api - <see cref="WebServiceProtocol.HttpGet"/> (only checking for no exception) /// </summary> [Fact] public void WebserviceTest_restapi_httpget_flush() { string wsAddress = getNewWsAddress(); var logFactory = SetUpHttpGetWebservice(wsAddress, "api/logme"); var logger = logFactory.GetCurrentClassLogger(); var context = new LogMeController.TestContext(); context.ResetState(0); var message1 = "message with a post"; StartOwinTest(wsAddress, context, () => { for (int i = 0; i < 100; ++i) logger.Info(message1); // Make triple-flush to fully exercise the async flushing logic try { LogManager.Flush(0); } catch (NLogRuntimeException) { } logFactory.Flush(); // Waits for flush (Scheduled on top of the previous flush) logFactory.Flush(); // Nothing to flush }); Assert.Equal(100, context.ReceivedLogsGetParam1.Count); } [Fact] public void WebServiceTest_restapi_httpget_querystring() { string wsAddress = getNewWsAddress(); var logger = SetUpHttpGetWebservice(wsAddress, "api/logme?paramFromConfig=valueFromConfig").GetCurrentClassLogger(); var context = new LogMeController.TestContext(); context.ResetState(1); StartOwinTest(wsAddress, context, () => { logger.Info("another message"); }); Assert.Equal(0, context.CountdownEvent.CurrentCount); Assert.Single(context.ReceivedLogsGetParam1); CheckQueueMessage("another message", context.ReceivedLogsGetParam1); } private static LogFactory SetUpHttpGetWebservice(string wsAddress, string relativeUrl) { var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterAssembly(typeof(WebServiceTarget).Assembly)) .LoadConfigurationFromXml($@" <nlog throwExceptions='true' > <targets> <target type='WebService' name='ws' url='{wsAddress}{relativeUrl}' protocol='HttpGet' encoding='UTF-8' > <parameter name='param1' type='System.String' layout='${{message}}'/> <parameter name='param2' type='System.String' layout='${{level}}'/> </target> </targets> <rules> <logger name='*' writeTo='ws' /> </rules> </nlog>").LogFactory; return logFactory; } private static void CheckQueueMessage(string message1, ConcurrentBag<string> receivedLogsGetParam1) { var success = receivedLogsGetParam1.Contains(message1); Assert.True(success, $"message '{message1}' not found"); } /// <summary> /// Timeout for <see cref="WebserviceTest_restapi_httppost_checkingLost"/>. /// /// in miliseconds. 20000 = 20 sec /// </summary> const int webserviceCheckTimeoutMs = 20000; /// <summary> /// Test the Webservice with REST api - <see cref="WebServiceProtocol.HttpPost"/> (only checking for no exception) /// /// repeats for checking 'lost messages' /// </summary> [Fact] public void WebserviceTest_restapi_httppost_checkingLost() { RetryingIntegrationTest(3, () => { string wsAddress = getNewWsAddress(); var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterAssembly(typeof(WebServiceTarget).Assembly)) .LoadConfigurationFromXml($@" <nlog throwExceptions='true'> <targets> <target type='WebService' name='ws' url='{wsAddress}{"api/logme"}' protocol='HttpPost' encoding='UTF-8' > <parameter name='param1' type='System.String' layout='${{message}}'/> <parameter name='param2' type='System.String' layout='${{level}}'/> </target> </targets> <rules> <logger name='*' writeTo='ws' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetCurrentClassLogger(); const int messageCount = 1000; var createdMessages = new List<string>(messageCount); for (int i = 0; i < messageCount; i++) { var message = "message " + i; createdMessages.Add(message); } //reset var context = new LogMeController.TestContext(); context.ResetState(messageCount); StartOwinTest(wsAddress, context, () => { foreach (var createdMessage in createdMessages) { logger.Info(createdMessage); } }); Assert.Equal(0, context.CountdownEvent.CurrentCount); Assert.Equal(createdMessages.Count, context.ReceivedLogsPostParam1.Count); }); } /// <summary> /// Test the Webservice with REST api - <see cref="WebServiceProtocol.JsonPost"/> /// </summary> [Fact] public void WebserviceTest_restapi_json() { string wsAddress = getNewWsAddress(); var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterAssembly(typeof(WebServiceTarget).Assembly)) .LoadConfigurationFromXml($@" <nlog throwExceptions='true'> <targets> <target type='WebService' name='ws' url='{wsAddress}{"api/logdoc/json"}' protocol='JsonPost' encoding='UTF-8' > <UserAgent>SecretAgent</UserAgent> <header name='Authorization' layout='OpenBackDoor' /> <parameter name='param1' ParameterType='System.String' layout='${{message}}'/> <parameter name='param2' ParameterType='System.String' layout='${{level}}'/> <parameter name='param3' ParameterType='System.Boolean' layout='True'/> <parameter name='param4' ParameterType='System.DateTime' layout='${{date:universalTime=true:format=o}}'/> </target> </targets> <rules> <logger name='*' writeTo='ws' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetCurrentClassLogger(); var txt = "message 1 with a JSON POST<hello><again\\>\"\b"; // Lets tease the JSON serializer and see it can handle valid and invalid xml chars var count = 101; var context = new LogDocController.TestContext(count, false, new Dictionary<string, string>() { { "Authorization", "OpenBackDoor" }, { "User-Agent", "SecretAgent" } }, txt, "info", true, DateTime.UtcNow); StartOwinDocTest(wsAddress, context, () => { for (int i = 0; i < count; i++) logger.Info(txt); }); Assert.Equal<int>(0, context.CountdownEvent.CurrentCount); } /// <summary> /// Test the Webservice with REST api - <see cref="WebServiceProtocol.XmlPost"/> /// </summary> [Fact] public void WebserviceTest_restapi_xml() { string wsAddress = getNewWsAddress(); var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterAssembly(typeof(WebServiceTarget).Assembly)) .LoadConfigurationFromXml($@" <nlog throwExceptions='true'> <targets> <target type='WebService' name='ws' url='{wsAddress}{"api/logdoc/xml"}' protocol='XmlPost' XmlRoot='ComplexType' encoding='UTF-8' > <parameter name='param1' ParameterType='System.String' layout='${{message}}'/> <parameter name='param2' ParameterType='System.String' layout='${{level}}'/> <parameter name='param3' ParameterType='System.Boolean' layout='True'/> <parameter name='param4' ParameterType='System.DateTime' layout='${{date:universalTime=true:format=o}}'/> </target> </targets> <rules> <logger name='*' writeTo='ws' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetCurrentClassLogger(); var txt = "message 1 with a XML POST<hello><again\\>\""; // Lets tease the Xml-Serializer, and see it can handle xml-tags var count = 101; var context = new LogDocController.TestContext(count, true, null, txt, "info", true, DateTime.UtcNow); StartOwinDocTest(wsAddress, context, () => { for (int i = 0; i < count; i++) logger.Info(txt); }); Assert.Equal<int>(0, context.CountdownEvent.CurrentCount); } /// <summary> /// Test the Webservice with Soap11 api - <see cref="WebServiceProtocol.Soap11"/> /// </summary> [Fact] public void WebserviceTest_soap11_default_soapaction() { string wsAddress = getNewWsAddress(); var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterAssembly(typeof(WebServiceTarget).Assembly)) .LoadConfigurationFromXml($@" <nlog throwExceptions='true'> <targets> <target type='WebService' name='ws' url='{wsAddress}{"api/logdoc/soap11"}' protocol='Soap11' namespace='http://tempuri.org/' methodName ='Ping' preAuthenticate='false' encoding ='UTF-8' > <parameter name='param1' ParameterType='System.String' layout='${{message}}'/> <parameter name='param2' ParameterType='System.String' layout='${{level}}'/> </target> </targets> <rules> <logger name='*' writeTo='ws' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetCurrentClassLogger(); var txt = "test.message"; // Lets tease the Xml-Serializer, and see it can handle xml-tags var count = 1; var expectedHeaders = new Dictionary<string, string> { {"SOAPAction", "http://tempuri.org/Ping" } }; var context = new LogDocController.TestContext(count, true, expectedHeaders, null, null, true, DateTime.UtcNow); StartOwinDocTest(wsAddress, context, () => { logger.Info(txt); }); Assert.Equal<int>(0, context.CountdownEvent.CurrentCount); } /// <summary> /// Test the Webservice with Soap11 api - <see cref="WebServiceProtocol.Soap11"/> /// </summary> [Fact] public void WebserviceTest_soap11_custom_soapaction() { string wsAddress = getNewWsAddress(); var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterAssembly(typeof(WebServiceTarget).Assembly)) .LoadConfigurationFromXml($@" <nlog throwExceptions='true'> <targets> <target type='WebService' name='ws' url='{wsAddress}{"api/logdoc/soap11"}' protocol='Soap11' namespace='http://tempuri.org/' methodName ='Ping' preAuthenticate='false' encoding ='UTF-8' > <header name='SOAPAction' layout='http://tempuri.org/custom-namespace/Ping'/> <parameter name='param1' ParameterType='System.String' layout='${{message}}'/> <parameter name='param2' ParameterType='System.String' layout='${{level}}'/> </target> </targets> <rules> <logger name='*' writeTo='ws' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetCurrentClassLogger(); var txt = "test.message"; // Lets tease the Xml-Serializer, and see it can handle xml-tags var count = 1; var expectedHeaders = new Dictionary<string, string> { {"SOAPAction", "http://tempuri.org/custom-namespace/Ping" } }; var context = new LogDocController.TestContext(count, true, expectedHeaders, null, null, true, DateTime.UtcNow); StartOwinDocTest(wsAddress, context, () => { logger.Info(txt); }); Assert.Equal<int>(0, context.CountdownEvent.CurrentCount); } /// <summary> /// Test the Webservice with Soap11 api - <see cref="WebServiceProtocol.Soap11"/> /// </summary> [Fact] public void WebserviceTest_soap12_default_soapaction() { string wsAddress = getNewWsAddress(); var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterAssembly(typeof(WebServiceTarget).Assembly)) .LoadConfigurationFromXml($@" <nlog throwExceptions='true'> <targets> <target type='WebService' name='ws' url='{wsAddress}{"api/logdoc/soap12"}' protocol='Soap12' namespace='http://tempuri.org/' methodName ='Ping' preAuthenticate='false' encoding ='UTF-8' > <parameter name='param1' ParameterType='System.String' layout='${{message}}'/> <parameter name='param2' ParameterType='System.String' layout='${{level}}'/> </target> </targets> <rules> <logger name='*' writeTo='ws' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetCurrentClassLogger(); var txt = "test.message"; // Lets tease the Xml-Serializer, and see it can handle xml-tags var count = 1; var contentType = MediaTypeHeaderValue.Parse("application/soap+xml;charset=utf-8;action=\"http://tempuri.org/Ping\""); var context = new LogDocController.TestContext(count, true, null, null, null, true, DateTime.UtcNow, contentType); StartOwinDocTest(wsAddress, context, () => { logger.Info(txt); }); Assert.Equal<int>(0, context.CountdownEvent.CurrentCount); } ///<remarks>Must be public </remarks> public class LogMeController : ApiController { public TestContext Context { get; set; } = new TestContext(); /// <summary> /// We need a complex type for modelbinding because of content-type: "application/x-www-form-urlencoded" in <see cref="WebServiceTarget"/> /// </summary> [DataContract(Namespace = "")] [XmlRoot(ElementName = "ComplexType", Namespace = "")] public class ComplexType { [DataMember(Name = "param1")] [XmlElement("param1")] public string Param1 { get; set; } [DataMember(Name = "param2")] [XmlElement("param2")] public string Param2 { get; set; } [DataMember(Name = "param3")] [XmlElement("param3")] public bool Param3 { get; set; } [DataMember(Name = "param4")] [XmlElement("param4")] public DateTime Param4 { get; set; } } /// <summary> /// Get /// </summary> public string Get(int id) { return "value"; } // GET api/values public IEnumerable<string> Get(string param1 = "", string param2 = "") { Context.ReceivedLogsGetParam1.Add(param1); if (Context.CountdownEvent != null) { Context.CountdownEvent.Signal(); } return new string[] { "value1", "value2" }; } /// <summary> /// Post /// </summary> public void Post([FromBody] ComplexType complexType) { //this is working. Guard.ThrowIfNull(complexType); Context.ReceivedLogsPostParam1.Add(complexType.Param1); if (Context.CountdownEvent != null) { Context.CountdownEvent.Signal(); } } /// <summary> /// Put /// </summary> public void Put(int id, [FromBody]string value) { } /// <summary> /// Delete /// </summary> public void Delete(int id) { } public class TestContext { /// <summary> /// Countdown event for keeping WS alive. /// </summary> public CountdownEvent CountdownEvent; /// <summary> /// Received param1 values (get) /// </summary> public ConcurrentBag<string> ReceivedLogsGetParam1 = new ConcurrentBag<string>(); /// <summary> /// Received param1 values(post) /// </summary> public ConcurrentBag<string> ReceivedLogsPostParam1 = new ConcurrentBag<string>(); /// <summary> /// Reset the state for unit testing /// </summary> /// <param name="expectedMessages"></param> public void ResetState(int expectedMessages) { ReceivedLogsPostParam1 = new ConcurrentBag<string>(); ReceivedLogsGetParam1 = new ConcurrentBag<string>(); if (expectedMessages > 0) CountdownEvent = new CountdownEvent(expectedMessages); else CountdownEvent = null; } } } internal static void StartOwinTest(string url, LogMeController.TestContext testContext, Action testsFunc) { // HttpSelfHostConfiguration. So info: http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api // Start webservice using (WebApp.Start(url, (appBuilder) => { // Configure Web API for self-host. HttpConfiguration config = new HttpConfiguration(); config.DependencyResolver = new ControllerResolver<LogMeController>(() => new LogMeController() { Context = testContext }); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); appBuilder.UseWebApi(config); })) { testsFunc(); //wait for all received message, or timeout. There is no exception on timeout, so we have to check carefully in the unit test. if (testContext.CountdownEvent != null) { testContext.CountdownEvent.Wait(webserviceCheckTimeoutMs); //we need some extra time for completion Thread.Sleep(1000); } } } internal static void StartOwinDocTest(string url, LogDocController.TestContext testContext, Action testsFunc) { using (WebApp.Start(url, (appBuilder) => { // Configure Web API for self-host. HttpConfiguration config = new HttpConfiguration(); config.DependencyResolver = new ControllerResolver<LogDocController>(() => new LogDocController() { Context = testContext }); config.Routes.MapHttpRoute( name: "ApiWithAction", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); if (testContext.XmlInsteadOfJson) { // Default Xml Formatter uses DataContractSerializer, changing it to XmlSerializer config.Formatters.XmlFormatter.UseXmlSerializer = true; } else { // Use ISO 8601 / RFC 3339 Date-Format (2012-07-27T18:51:45.53403Z), instead of Microsoft JSON date format ("\/Date(ticks)\/") config.Formatters.JsonFormatter.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat; config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false; // JSON.NET serializer instead of the ancient DataContractJsonSerializer } appBuilder.UseWebApi(config); })) { testsFunc(); if (testContext.CountdownEvent != null) { testContext.CountdownEvent.Wait(webserviceCheckTimeoutMs); Thread.Sleep(1000); } } } private sealed class ControllerResolver<T> : IDependencyResolver { private readonly Func<T> _factory; public ControllerResolver(Func<T> factory) { _factory = factory; } public IDependencyScope BeginScope() { return this; } public void Dispose() { } public object GetService(Type serviceType) { if (serviceType == typeof(T)) { return _factory.Invoke(); } else { return null; } } public IEnumerable<object> GetServices(Type serviceType) { if (serviceType == typeof(T)) { return new object[] { GetService(serviceType) }; } else { return ArrayHelper.Empty<object>(); } } } ///<remarks>Must be public </remarks> public class LogDocController : ApiController { public TestContext Context { get; set; } [HttpPost] public void Json(LogMeController.ComplexType complexType) { Guard.ThrowIfNull(complexType); processRequest(complexType); } private void processRequest(LogMeController.ComplexType complexType) { if (Context != null) { if (string.Equals(Context.ExpectedParam2, complexType.Param2, StringComparison.OrdinalIgnoreCase) && Context.ExpectedParam1 == complexType.Param1 && Context.ExpectedParam3 == complexType.Param3 && Context.ExpectedParam4.Date == complexType.Param4.Date) { if (!ValidateHeaders()) { return; } Context.CountdownEvent.Signal(); } } } [HttpPost] public void Xml(LogMeController.ComplexType complexType) { Guard.ThrowIfNull(complexType); processRequest(complexType); } [HttpPost] public void Soap11() { if (Context != null) { if (ValidateHeaders()) { Context.CountdownEvent.Signal(); } } } [HttpPost] public void Soap12() { if (Context?.ExpectedContentType != null && Context.ExpectedContentType.Equals(Request.Content.Headers.ContentType)) { Context.CountdownEvent.Signal(); } } private bool ValidateHeaders() { if (Context.ExpectedHeaders?.Count > 0) { foreach (var expectedHeader in Context.ExpectedHeaders) { if (Request.Headers.GetValues(expectedHeader.Key).First() != expectedHeader.Value) return false; } } return true; } public class TestContext { public CountdownEvent CountdownEvent { get; } public bool XmlInsteadOfJson { get; } public Dictionary<string, string> ExpectedHeaders { get; } public string ExpectedParam1 { get; } public string ExpectedParam2 { get; } public bool ExpectedParam3 { get; } public DateTime ExpectedParam4 { get; } public MediaTypeHeaderValue ExpectedContentType { get; } public TestContext(int expectedMessages, bool xmlInsteadOfJson, Dictionary<string, string> expectedHeaders, string expected1, string expected2, bool expected3, DateTime expected4, MediaTypeHeaderValue expectedContentType = null) { CountdownEvent = new CountdownEvent(expectedMessages); XmlInsteadOfJson = xmlInsteadOfJson; ExpectedHeaders = expectedHeaders; ExpectedParam1 = expected1; ExpectedParam2 = expected2; ExpectedParam3 = expected3; ExpectedParam4 = expected4; ExpectedContentType = expectedContentType; } } } #endif } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.IO; namespace NLog.Targets.FileArchiveModes { /// <summary> /// Archives the log-files using a rolling style numbering (the most recent is always #0 then /// #1, ..., #N. /// /// When the number of archive files exceed <see cref="FileTarget.MaxArchiveFiles"/> the obsolete archives /// are deleted. /// </summary> internal sealed class FileArchiveModeRolling : IFileArchiveMode { public bool IsArchiveCleanupEnabled => true; // Always to roll public bool AttemptCleanupOnInitializeFile(string archiveFilePath, int maxArchiveFiles, int maxArchiveDays) { return false; // For historic reasons, then cleanup of rolling archives are not done on startup } public string GenerateFileNameMask(string archiveFilePath) { return new FileArchiveModeBase.FileNameTemplate(Path.GetFileName(archiveFilePath)).ReplacePattern("*"); } public List<DateAndSequenceArchive> GetExistingArchiveFiles(string archiveFilePath) { List<DateAndSequenceArchive> existingArchiveFiles = new List<DateAndSequenceArchive>(); for (int archiveNumber = 0; archiveNumber < int.MaxValue; archiveNumber++) { string existingFileName = ReplaceNumberPattern(archiveFilePath, archiveNumber); FileInfo existingFileInfo = new FileInfo(existingFileName); if (!existingFileInfo.Exists) break; existingArchiveFiles.Add(new DateAndSequenceArchive(existingFileInfo.FullName, DateTime.MinValue, string.Empty, archiveNumber)); } return existingArchiveFiles; } /// <summary> /// Replaces the numeric pattern i.e. {#} in a file name with the <paramref name="value"/> parameter value. /// </summary> /// <param name="pattern">File name which contains the numeric pattern.</param> /// <param name="value">Value which will replace the numeric pattern.</param> /// <returns>File name with the value of <paramref name="value"/> in the position of the numeric pattern.</returns> private static string ReplaceNumberPattern(string pattern, int value) { int firstPart = pattern.IndexOf("{#", StringComparison.Ordinal); int lastPart = pattern.IndexOf("#}", StringComparison.Ordinal) + 2; int numDigits = lastPart - firstPart - 2; return pattern.Substring(0, firstPart) + Convert.ToString(value, 10).PadLeft(numDigits, '0') + pattern.Substring(lastPart); } public DateAndSequenceArchive GenerateArchiveFileName(string archiveFilePath, DateTime archiveDate, List<DateAndSequenceArchive> existingArchiveFiles) { if (existingArchiveFiles.Count > 0) { // We are about to perform roll, so we add an artificial file to cache the next rollFileName int rollSequenceNo = existingArchiveFiles[existingArchiveFiles.Count - 1].Sequence + 1; string rollFileName = ReplaceNumberPattern(archiveFilePath, rollSequenceNo); existingArchiveFiles.Add(new DateAndSequenceArchive(rollFileName, DateTime.MinValue, string.Empty, int.MaxValue)); } string newFileName = ReplaceNumberPattern(archiveFilePath, 0); newFileName = Path.GetFullPath(newFileName); // Rebuild to fix non-standard path-format return new DateAndSequenceArchive(newFileName, DateTime.MinValue, string.Empty, int.MinValue); } public IEnumerable<DateAndSequenceArchive> CheckArchiveCleanup(string archiveFilePath, List<DateAndSequenceArchive> existingArchiveFiles, int maxArchiveFiles, int maxArchiveDays) { if (existingArchiveFiles.Count <= 1) yield break; existingArchiveFiles.Sort((x, y) => x.Sequence.CompareTo(y.Sequence)); if (maxArchiveFiles > 0 && existingArchiveFiles.Count > maxArchiveFiles) { for (int i = 0; i < existingArchiveFiles.Count; i++) { if (existingArchiveFiles[i].Sequence == int.MinValue || existingArchiveFiles[i].Sequence == int.MaxValue) continue; if (i >= maxArchiveFiles) { yield return existingArchiveFiles[i]; } } } // After deleting the last/oldest, then roll the others forward if (existingArchiveFiles.Count > 1 && existingArchiveFiles[0].Sequence == int.MinValue) { string newFileName = string.Empty; int maxFileCount = existingArchiveFiles.Count - 1; if (maxArchiveFiles > 0 && maxFileCount > maxArchiveFiles) maxFileCount = maxArchiveFiles; for (int i = maxFileCount; i >= 1; --i) { string fileName = existingArchiveFiles[i].FileName; if (!string.IsNullOrEmpty(newFileName)) { Common.InternalLogger.Info("Roll archive {0} to {1}", fileName, newFileName); File.Move(fileName, newFileName); } newFileName = fileName; } } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Globalization; using System.IO; namespace NLog.Targets.FileArchiveModes { /// <summary> /// Archives the log-files using a date style numbering. Archives will be stamped with the /// prior period (Year, Month, Day, Hour, Minute) datetime. /// /// When the number of archive files exceed <see cref="FileTarget.MaxArchiveFiles"/> the obsolete archives are deleted. /// When the age of archive files exceed <see cref="FileTarget.MaxArchiveDays"/> the obsolete archives are deleted. /// </summary> internal sealed class FileArchiveModeDate : FileArchiveModeBase { private readonly string _archiveDateFormat; public FileArchiveModeDate(string archiveDateFormat, bool isArchiveCleanupEnabled) :base(isArchiveCleanupEnabled) { _archiveDateFormat = archiveDateFormat; } public override List<DateAndSequenceArchive> GetExistingArchiveFiles(string archiveFilePath) { if (IsArchiveCleanupEnabled) return base.GetExistingArchiveFiles(archiveFilePath); else return new List<DateAndSequenceArchive>(); } protected override DateAndSequenceArchive GenerateArchiveFileInfo(FileInfo archiveFile, FileNameTemplate fileTemplate) { string archiveFileName = Path.GetFileName(archiveFile.FullName) ?? ""; string fileNameMask = fileTemplate.ReplacePattern("*"); int lastIndexOfStar = fileNameMask.LastIndexOf('*'); if (lastIndexOfStar + _archiveDateFormat.Length <= archiveFileName.Length) { string datePart = archiveFileName.Substring(lastIndexOfStar, _archiveDateFormat.Length); DateTime fileDate; if (DateTime.TryParseExact(datePart, _archiveDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out fileDate)) { fileDate = DateTime.SpecifyKind(fileDate, NLog.Time.TimeSource.Current.Time.Kind); return new DateAndSequenceArchive(archiveFile.FullName, fileDate, _archiveDateFormat, -1); } } return null; } public override DateAndSequenceArchive GenerateArchiveFileName(string archiveFilePath, DateTime archiveDate, List<DateAndSequenceArchive> existingArchiveFiles) { FileNameTemplate archiveFileNameTemplate = GenerateFileNameTemplate(archiveFilePath); string dirName = Path.GetDirectoryName(archiveFilePath); archiveFilePath = Path.Combine(dirName, archiveFileNameTemplate.ReplacePattern("*").Replace("*", archiveDate.ToString(_archiveDateFormat))); archiveFilePath = Path.GetFullPath(archiveFilePath); // Rebuild to fix non-standard path-format return new DateAndSequenceArchive(archiveFilePath, archiveDate, _archiveDateFormat, 0); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Text; using NLog.Common; using NLog.Conditions; using NLog.Config; using NLog.Internal; using NLog.LayoutRenderers; using NLog.LayoutRenderers.Wrappers; /// <summary> /// Parses layout strings. /// </summary> internal static class LayoutParser { private static readonly char[] SpecialTokens = new char[] { '$', '\\', '}', ':' }; internal static LayoutRenderer[] CompileLayout(string value, ConfigurationItemFactory configurationItemFactory, bool? throwConfigExceptions, out string text) { if (value is null) { text = string.Empty; return ArrayHelper.Empty<LayoutRenderer>(); } else if (value.Length < 128 && value.IndexOfAny(SpecialTokens) < 0) { text = value; return new LayoutRenderer[] { new LiteralLayoutRenderer(value) }; } else { return CompileLayout(configurationItemFactory, new SimpleStringReader(value), throwConfigExceptions, false, out text); } } internal static LayoutRenderer[] CompileLayout(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr, bool? throwConfigExceptions, bool isNested, out string text) { var result = new List<LayoutRenderer>(); var literalBuf = new StringBuilder(); int ch; int p0 = sr.Position; while ((ch = sr.Peek()) != -1) { if (isNested) { //possible escape char `\` if (ch == '\\') { sr.Read(); var nextChar = sr.Peek(); //escape chars if (EndOfLayout(nextChar)) { //read next char and append sr.Read(); literalBuf.Append((char)nextChar); } else { //don't treat \ as escape char and just read it literalBuf.Append('\\'); } continue; } if (EndOfLayout(ch)) { //end of inner layout. // `}` is when double nested inner layout. // `:` when single nested layout break; } } sr.Read(); //detect `${` (new layout-renderer) if (ch == '$' && sr.Peek() == '{') { //stash already found layout-renderer. AddLiteral(literalBuf, result); LayoutRenderer newLayoutRenderer = ParseLayoutRenderer(configurationItemFactory, sr, throwConfigExceptions); result.Add(newLayoutRenderer); } else { literalBuf.Append((char)ch); } } AddLiteral(literalBuf, result); int p1 = sr.Position; MergeLiterals(result); text = sr.Substring(p0, p1); return result.ToArray(); } /// <summary> /// Add <see cref="LiteralLayoutRenderer"/> to <paramref name="result"/> /// </summary> /// <param name="literalBuf"></param> /// <param name="result"></param> private static void AddLiteral(StringBuilder literalBuf, List<LayoutRenderer> result) { if (literalBuf.Length > 0) { result.Add(new LiteralLayoutRenderer(literalBuf.ToString())); literalBuf.Length = 0; } } private static bool EndOfLayout(int ch) { return ch == '}' || ch == ':'; } private static string ParseLayoutRendererTypeName(SimpleStringReader sr) { return sr.ReadUntilMatch(ch => EndOfLayout(ch)); } private static string ParseParameterNameOrValue(SimpleStringReader sr) { var parameterName = sr.ReadUntilMatch(chr => EndOfLayout(chr) || chr == '=' || chr == '$' || chr == '\\'); if (sr.Peek() != '$' && sr.Peek() != '\\') { return parameterName; } var parameterValue = new StringBuilder(parameterName); ParseLayoutParameterValue(sr, parameterValue, chr => EndOfLayout(chr) || chr == '='); return parameterValue.ToString(); } private static string ParseParameterStringValue(SimpleStringReader sr) { var parameterName = sr.ReadUntilMatch(chr => EndOfLayout(chr) || chr == '$' || chr == '\\'); if (sr.Peek() != '$' && sr.Peek() != '\\') { return parameterName; } var parameterValue = new StringBuilder(parameterName); bool containsUnicodeEscape = ParseLayoutParameterValue(sr, parameterValue, chr => EndOfLayout(chr)); if (!containsUnicodeEscape) return parameterValue.ToString(); var unescapedValue = parameterValue.ToString(); parameterValue.ClearBuilder(); return EscapeUnicodeStringValue(unescapedValue, parameterValue); } private static bool ParseLayoutParameterValue(SimpleStringReader sr, StringBuilder parameterValue, Func<int, bool> endOfLayout) { bool containsUnicodeEscape = false; int ch; int nestLevel = 0; while ((ch = sr.Peek()) != -1) { if (endOfLayout(ch) && nestLevel == 0) { break; } if (ch == '$') { sr.Read(); parameterValue.Append('$'); if (sr.Peek() == '{') { parameterValue.Append('{'); nestLevel++; sr.Read(); } continue; } if (ch == '}') { nestLevel--; } if (ch == '\\') { sr.Read(); ch = sr.Peek(); if (nestLevel == 0 && (endOfLayout(ch) || ch == '$' || ch == '=')) { parameterValue.Append((char)sr.Read()); } else if (ch != -1) { containsUnicodeEscape = true; parameterValue.Append('\\'); parameterValue.Append((char)sr.Read()); } continue; } parameterValue.Append((char)ch); sr.Read(); } return containsUnicodeEscape; } private static string ParseParameterValue(SimpleStringReader sr) { var value = sr.ReadUntilMatch(ch => EndOfLayout(ch) || ch == '\\'); if (sr.Peek() == '\\') { bool containsUnicodeEscape = false; var nameBuf = new StringBuilder(value); int ch; while ((ch = sr.Peek()) != -1) { if (EndOfLayout(ch)) break; if (ch == '\\') { sr.Read(); ch = sr.Peek(); if (EndOfLayout(ch)) { nameBuf.Append((char)sr.Read()); } else if (ch != -1) { containsUnicodeEscape = true; nameBuf.Append('\\'); nameBuf.Append((char)sr.Read()); } } else { nameBuf.Append((char)ch); sr.Read(); } } value = nameBuf.ToString(); if (containsUnicodeEscape) { nameBuf.Length = 0; value = EscapeUnicodeStringValue(value, nameBuf); } } return value; } private static string EscapeUnicodeStringValue(string value, StringBuilder nameBuf = null) { bool escapeNext = false; nameBuf = nameBuf ?? new StringBuilder(value.Length); char ch; for (int i = 0; i < value.Length; ++i) { ch = value[i]; // Code in this condition was replaced // to support escape codes e.g. '\r' '\n' '\u003a', // which can not be used directly as they are used as tokens by the parser // All escape codes listed in the following link were included // in addition to "\{", "\}", "\:" which are NLog specific: // https://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/what-character-escape-sequences-are-available.aspx if (escapeNext) { escapeNext = false; switch (ch) { case ':': case '{': case '}': case '\'': case '"': case '\\': nameBuf.Append(ch); break; case '0': nameBuf.Append('\0'); break; case 'a': nameBuf.Append('\a'); break; case 'b': nameBuf.Append('\b'); break; case 'f': nameBuf.Append('\f'); break; case 'n': nameBuf.Append('\n'); break; case 'r': nameBuf.Append('\r'); break; case 't': nameBuf.Append('\t'); break; case 'u': { var uChar = GetUnicode(value, 4, ref i); // 4 digits nameBuf.Append(uChar); break; } case 'U': { var uChar = GetUnicode(value, 8, ref i); // 8 digits nameBuf.Append(uChar); break; } case 'x': { var xChar = GetUnicode(value, 4, ref i); // 1-4 digits nameBuf.Append(xChar); break; } case 'v': nameBuf.Append('\v'); break; default: nameBuf.Append(ch); break; } } else if (ch == '\\') { escapeNext = true; } else { nameBuf.Append(ch); } } if (escapeNext) nameBuf.Append('\\'); return nameBuf.ToString(); } private static char GetUnicode(string value, int maxDigits, ref int currentIndex) { int code = 0; maxDigits = Math.Min(value.Length - 1, currentIndex + maxDigits); for ( ; currentIndex < maxDigits; ++currentIndex) { int digitCode = value[currentIndex + 1]; if (digitCode >= (int)'0' && digitCode <= (int)'9') digitCode = digitCode - (int)'0'; else if (digitCode >= (int)'a' && digitCode <= (int)'f') digitCode = digitCode - (int)'a' + 10; else if (digitCode >= (int)'A' && digitCode <= (int)'F') digitCode = digitCode - (int)'A' + 10; else break; code = code * 16 + digitCode; } return (char)code; } private static LayoutRenderer ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, SimpleStringReader stringReader, bool? throwConfigExceptions) { int ch = stringReader.Read(); Debug.Assert(ch == '{', "'{' expected in layout specification"); string typeName = ParseLayoutRendererTypeName(stringReader); var layoutRenderer = GetLayoutRenderer(typeName, configurationItemFactory, throwConfigExceptions); Dictionary<Type, LayoutRenderer> wrappers = null; List<LayoutRenderer> orderedWrappers = null; string previousParameterName = null; ch = stringReader.Read(); while (ch != -1 && ch != '}') { string parameterName = ParseParameterNameOrValue(stringReader); if (stringReader.Peek() == '=') { stringReader.Read(); // skip the '=' parameterName = parameterName.Trim(); LayoutRenderer parameterTarget = layoutRenderer; if (!PropertyHelper.TryGetPropertyInfo(configurationItemFactory, layoutRenderer, parameterName, out var propertyInfo)) { parameterTarget = LookupAmbientProperty(parameterName, configurationItemFactory, ref wrappers, ref orderedWrappers); if (parameterTarget is null || !PropertyHelper.TryGetPropertyInfo(configurationItemFactory, parameterTarget, parameterName, out propertyInfo)) { parameterTarget = layoutRenderer; propertyInfo = null; } } if (propertyInfo is null) { var value = ParseParameterValue(stringReader); if (!string.IsNullOrEmpty(parameterName) || !StringHelpers.IsNullOrWhiteSpace(value)) { var configException = new NLogConfigurationException($"${{{typeName}}} cannot assign unknown property '{parameterName}='"); if (throwConfigExceptions ?? configException.MustBeRethrown()) { throw configException; } } } else { var propertyValue = ParseLayoutRendererPropertyValue(configurationItemFactory, stringReader, throwConfigExceptions, typeName, propertyInfo); if (propertyValue is string propertyStringValue) { PropertyHelper.SetPropertyFromString(parameterTarget, propertyInfo, propertyStringValue, configurationItemFactory); } else if (propertyValue != null) { PropertyHelper.SetPropertyValueForObject(parameterTarget, propertyValue, propertyInfo); } } } else { parameterName = SetDefaultPropertyValue(parameterName, layoutRenderer, configurationItemFactory, throwConfigExceptions); } previousParameterName = ValidatePreviousParameterName(previousParameterName, parameterName, layoutRenderer, throwConfigExceptions); ch = stringReader.Read(); } return BuildCompleteLayoutRenderer(configurationItemFactory, layoutRenderer, orderedWrappers); } private static LayoutRenderer BuildCompleteLayoutRenderer(ConfigurationItemFactory configurationItemFactory, LayoutRenderer layoutRenderer, List<LayoutRenderer> orderedWrappers = null) { if (orderedWrappers != null) { layoutRenderer = ApplyWrappers(configurationItemFactory, layoutRenderer, orderedWrappers); } if (CanBeConvertedToLiteral(configurationItemFactory, layoutRenderer)) { layoutRenderer = ConvertToLiteral(layoutRenderer); } return layoutRenderer; } private static object ParseLayoutRendererPropertyValue(ConfigurationItemFactory configurationItemFactory, SimpleStringReader stringReader, bool? throwConfigExceptions, string targetTypeName, PropertyInfo propertyInfo) { if (typeof(Layout).IsAssignableFrom(propertyInfo.PropertyType)) { LayoutRenderer[] renderers = CompileLayout(configurationItemFactory, stringReader, throwConfigExceptions, true, out var txt); Layout nestedLayout = new SimpleLayout(renderers, txt, configurationItemFactory); if (propertyInfo.PropertyType.IsGenericType() && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Layout<>)) { var concreteType = typeof(Layout<>).MakeGenericType(propertyInfo.PropertyType.GetGenericArguments()); nestedLayout = (Layout)Activator.CreateInstance(concreteType, BindingFlags.Instance | BindingFlags.Public, null, new object[] { nestedLayout }, null); } return nestedLayout; } else if (typeof(ConditionExpression).IsAssignableFrom(propertyInfo.PropertyType)) { try { return ConditionParser.ParseExpression(stringReader, configurationItemFactory); } catch (ConditionParseException ex) { var configException = new NLogConfigurationException($"${{{targetTypeName}}} cannot parse ConditionExpression for property '{propertyInfo.Name}='. Error: {ex.Message}", ex); if (throwConfigExceptions ?? configException.MustBeRethrown()) { throw configException; } return null; } } else if (typeof(string).IsAssignableFrom(propertyInfo.PropertyType)) { return ParseParameterStringValue(stringReader); } else { return ParseParameterValue(stringReader); } } private static string ValidatePreviousParameterName(string previousParameterName, string parameterName, LayoutRenderer layoutRenderer, bool? throwConfigExceptions) { if (parameterName?.Equals(previousParameterName, StringComparison.OrdinalIgnoreCase) == true) { var configException = new NLogConfigurationException($"'{layoutRenderer?.GetType()?.Name}' has same property '{parameterName}=' assigned twice"); if (throwConfigExceptions ?? configException.MustBeRethrown()) { throw configException; } } else { previousParameterName = parameterName ?? previousParameterName; } return previousParameterName; } private static LayoutRenderer LookupAmbientProperty(string propertyName, ConfigurationItemFactory configurationItemFactory, ref Dictionary<Type, LayoutRenderer> wrappers, ref List<LayoutRenderer> orderedWrappers) { if (configurationItemFactory.AmbientRendererFactory.TryCreateInstance(propertyName, out var wrapperInstance)) { wrappers = wrappers ?? new Dictionary<Type, LayoutRenderer>(); orderedWrappers = orderedWrappers ?? new List<LayoutRenderer>(); var wrapperType = wrapperInstance.GetType(); if (!wrappers.TryGetValue(wrapperType, out var wrapperRenderer)) { wrappers[wrapperType] = wrapperInstance; orderedWrappers.Add(wrapperInstance); wrapperRenderer = wrapperInstance; } return wrapperRenderer; } return null; } private static LayoutRenderer GetLayoutRenderer(string typeName, ConfigurationItemFactory configurationItemFactory, bool? throwConfigExceptions) { LayoutRenderer layoutRenderer; try { layoutRenderer = configurationItemFactory.LayoutRendererFactory.CreateInstance(typeName); } catch (Exception ex) { var configException = new NLogConfigurationException($"Failed to parse layout containing type: {typeName} - {ex.Message}", ex); if (throwConfigExceptions ?? configException.MustBeRethrown()) { throw configException; } // replace with empty values layoutRenderer = new LiteralLayoutRenderer(string.Empty); } return layoutRenderer; } private static string SetDefaultPropertyValue(string value, LayoutRenderer layoutRenderer, ConfigurationItemFactory configurationItemFactory, bool? throwConfigExceptions) { // what we've just read is not a parameterName, but a value // assign it to a default property (denoted by empty string) if (PropertyHelper.TryGetPropertyInfo(configurationItemFactory, layoutRenderer, string.Empty, out var propertyInfo)) { if (!typeof(Layout).IsAssignableFrom(propertyInfo.PropertyType) && value.IndexOf('\\') >= 0) { value = EscapeUnicodeStringValue(value); } PropertyHelper.SetPropertyFromString(layoutRenderer, propertyInfo, value, configurationItemFactory); return propertyInfo.Name; } else { var configException = new NLogConfigurationException($"'{layoutRenderer?.GetType()?.Name}' has no default property to assign value {value}"); if (throwConfigExceptions ?? configException.MustBeRethrown()) { throw configException; } return null; } } private static LayoutRenderer ApplyWrappers(ConfigurationItemFactory configurationItemFactory, LayoutRenderer lr, List<LayoutRenderer> orderedWrappers) { for (int i = orderedWrappers.Count - 1; i >= 0; --i) { var newRenderer = (WrapperLayoutRendererBase)orderedWrappers[i]; InternalLogger.Trace("Wrapping {0} with {1}", lr.GetType(), newRenderer.GetType()); if (CanBeConvertedToLiteral(configurationItemFactory, lr)) { lr = ConvertToLiteral(lr); } newRenderer.Inner = new SimpleLayout(new[] { lr }, string.Empty, configurationItemFactory); lr = newRenderer; } return lr; } private static bool CanBeConvertedToLiteral(ConfigurationItemFactory configurationItemFactory, LayoutRenderer lr) { foreach (IRenderable renderable in ObjectGraphScanner.FindReachableObjects<IRenderable>(configurationItemFactory, true, lr)) { var renderType = renderable.GetType(); if (renderType == typeof(SimpleLayout)) { continue; } if (!renderType.IsDefined(typeof(AppDomainFixedOutputAttribute), false)) { return false; } } return true; } private static void MergeLiterals(IList<LayoutRenderer> list) { for (int i = 0; i + 1 < list.Count;) { if (list[i] is LiteralLayoutRenderer lr1 && list[i + 1] is LiteralLayoutRenderer lr2) { lr1.Text += lr2.Text; // Combined literals don't support rawValue if (lr1 is LiteralWithRawValueLayoutRenderer lr1WithRaw) { list[i] = new LiteralLayoutRenderer(lr1WithRaw.Text); } list.RemoveAt(i + 1); } else { i++; } } } private static LayoutRenderer ConvertToLiteral(LayoutRenderer renderer) { var logEventInfo = LogEventInfo.CreateNullEvent(); var text = renderer.Render(logEventInfo); if (renderer is IRawValue rawValueRender) { var success = rawValueRender.TryGetRawValue(logEventInfo, out var rawValue); return new LiteralWithRawValueLayoutRenderer(text, success, rawValue); } return new LiteralLayoutRenderer(text); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Threading; using JetBrains.Annotations; using NLog.Common; using NLog.Internal; using NLog.Layouts; using NLog.MessageTemplates; using NLog.Time; /// <summary> /// Represents the logging event. /// </summary> public class LogEventInfo { /// <summary> /// Gets the date of the first log event created. /// </summary> public static readonly DateTime ZeroDate = DateTime.UtcNow; private static int globalSequenceId; /// <summary> /// The formatted log message. /// </summary> private string _formattedMessage; /// <summary> /// The log message including any parameter placeholders /// </summary> private string _message; private object[] _parameters; private IFormatProvider _formatProvider; private LogMessageFormatter _messageFormatter; private IDictionary<Layout, object> _layoutCache; private PropertiesDictionary _properties; private int _sequenceId; /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> public LogEventInfo() { TimeStamp = TimeSource.Current.Time; } /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="message">Log message including parameter placeholders.</param> public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message) : this(level, loggerName, null, message, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="message">Log message including parameter placeholders.</param> /// <param name="messageTemplateParameters">Already parsed message template parameters.</param> public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message, IList<MessageTemplateParameter> messageTemplateParameters) : this(level, loggerName, null, message, null, null) { if (messageTemplateParameters != null) { var messagePropertyCount = messageTemplateParameters.Count; if (messagePropertyCount > 0) { var messageProperties = new MessageTemplateParameter[messagePropertyCount]; for (int i = 0; i < messagePropertyCount; ++i) messageProperties[i] = messageTemplateParameters[i]; _properties = new PropertiesDictionary(messageProperties); } } } /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="formattedMessage">Pre-formatted log message for ${message}.</param> /// <param name="messageTemplate">Log message-template including parameter placeholders for ${message:raw=true}.</param> /// <param name="messageTemplateParameters">Already parsed message template parameters.</param> public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string formattedMessage, [Localizable(false)] string messageTemplate, IList<MessageTemplateParameter> messageTemplateParameters) : this(level, loggerName, messageTemplate, messageTemplateParameters) { _formattedMessage = formattedMessage; _messageFormatter = (l) => l._formattedMessage ?? l.Message ?? string.Empty; } #if !NET35 /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="message">Log message.</param> /// <param name="eventProperties">List of event-properties</param> public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message, IReadOnlyList<KeyValuePair<object, object>> eventProperties) : this(level, loggerName, null, message, null, null) { if (eventProperties?.Count > 0) { _properties = new PropertiesDictionary(eventProperties); } } #endif /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">Log message including parameter placeholders.</param> /// <param name="parameters">Parameter array.</param> public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters) : this(level, loggerName, formatProvider, message, parameters, null) { } /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">Log message including parameter placeholders.</param> /// <param name="parameters">Parameter array.</param> /// <param name="exception">Exception information.</param> public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters, Exception exception) : this() { Level = level; LoggerName = loggerName; _formatProvider = formatProvider; _message = message; Parameters = parameters; Exception = exception; } /// <summary> /// Gets the unique identifier of log event which is automatically generated /// and monotonously increasing. /// </summary> // ReSharper disable once InconsistentNaming public int SequenceID { get { if (_sequenceId == 0) Interlocked.CompareExchange(ref _sequenceId, Interlocked.Increment(ref globalSequenceId), 0); return _sequenceId; } } /// <summary> /// Gets or sets the timestamp of the logging event. /// </summary> public DateTime TimeStamp { get; set; } /// <summary> /// Gets or sets the level of the logging event. /// </summary> public LogLevel Level { get; set; } [CanBeNull] internal CallSiteInformation CallSiteInformation { get; private set; } [NotNull] internal CallSiteInformation GetCallSiteInformationInternal() { return CallSiteInformation ?? (CallSiteInformation = new CallSiteInformation()); } /// <summary> /// Gets a value indicating whether stack trace has been set for this event. /// </summary> public bool HasStackTrace => CallSiteInformation?.StackTrace != null; /// <summary> /// Gets the stack frame of the method that did the logging. /// </summary> public StackFrame UserStackFrame => CallSiteInformation?.UserStackFrame; /// <summary> /// Gets the number index of the stack frame that represents the user /// code (not the NLog code). /// </summary> public int UserStackFrameNumber => CallSiteInformation?.UserStackFrameNumberLegacy ?? CallSiteInformation?.UserStackFrameNumber ?? 0; /// <summary> /// Gets the entire stack trace. /// </summary> public StackTrace StackTrace => CallSiteInformation?.StackTrace; /// <summary> /// Gets the callsite class name /// </summary> public string CallerClassName => CallSiteInformation?.GetCallerClassName(null, true, true, true); /// <summary> /// Gets the callsite member function name /// </summary> public string CallerMemberName => CallSiteInformation?.GetCallerMethodName(null, false, true, true); /// <summary> /// Gets the callsite source file path /// </summary> public string CallerFilePath => CallSiteInformation?.GetCallerFilePath(0); /// <summary> /// Gets the callsite source file line number /// </summary> public int CallerLineNumber => CallSiteInformation?.GetCallerLineNumber(0) ?? 0; /// <summary> /// Gets or sets the exception information. /// </summary> [CanBeNull] public Exception Exception { get; set; } /// <summary> /// Gets or sets the logger name. /// </summary> [CanBeNull] public string LoggerName { get; set; } /// <summary> /// Gets or sets the log message including any parameter placeholders. /// </summary> public string Message { get => _message; set { bool rebuildMessageTemplateParameters = ResetMessageTemplateParameters(); _message = value; ResetFormattedMessage(rebuildMessageTemplateParameters); } } /// <summary> /// Gets or sets the parameter values or null if no parameters have been specified. /// </summary> public object[] Parameters { get => _parameters; set { bool rebuildMessageTemplateParameters = ResetMessageTemplateParameters(); _parameters = value; ResetFormattedMessage(rebuildMessageTemplateParameters); } } /// <summary> /// Gets or sets the format provider that was provided while logging or <see langword="null" /> /// when no formatProvider was specified. /// </summary> public IFormatProvider FormatProvider { get => _formatProvider; set { if (!ReferenceEquals(_formatProvider, value)) { _formatProvider = value; ResetFormattedMessage(false); } } } /// <summary> /// Gets or sets the message formatter for generating <see cref="LogEventInfo.FormattedMessage"/> /// Uses string.Format(...) when nothing else has been configured. /// </summary> public LogMessageFormatter MessageFormatter { get => _messageFormatter ?? LogManager.LogFactory.ActiveMessageFormatter; set { var messageFormatter = value ?? LogMessageStringFormatter.Default.MessageFormatter; if (!ReferenceEquals(_messageFormatter, messageFormatter)) { _messageFormatter = messageFormatter; _formattedMessage = null; ResetFormattedMessage(false); } } } /// <summary> /// Gets the formatted message. /// </summary> public string FormattedMessage { get { if (_formattedMessage is null) { CalcFormattedMessage(); } return _formattedMessage; } } /// <summary> /// Checks if any per-event properties (Without allocation) /// </summary> public bool HasProperties { get { if (_properties != null) { return _properties.Count > 0; } else { return CreateOrUpdatePropertiesInternal(false)?.Count > 0; } } } /// <summary> /// Gets the dictionary of per-event context properties. /// </summary> public IDictionary<object, object> Properties => CreateOrUpdatePropertiesInternal(); /// <summary> /// Gets the dictionary of per-event context properties. /// Internal helper for the PropertiesDictionary type. /// </summary> /// <param name="forceCreate">Create the event-properties dictionary, even if no initial template parameters</param> /// <param name="templateParameters">Provided when having parsed the message template and capture template parameters (else null)</param> /// <returns></returns> internal PropertiesDictionary CreateOrUpdatePropertiesInternal(bool forceCreate = true, IList<MessageTemplateParameter> templateParameters = null) { var properties = _properties; if (properties is null) { if (forceCreate || templateParameters?.Count > 0 || (templateParameters is null && HasMessageTemplateParameters)) { properties = new PropertiesDictionary(templateParameters); Interlocked.CompareExchange(ref _properties, properties, null); if (templateParameters is null && (!forceCreate || HasMessageTemplateParameters)) { // Trigger capture of MessageTemplateParameters from logevent-message CalcFormattedMessage(); } } } else if (templateParameters != null) { properties.MessageProperties = templateParameters; } return _properties; } private bool HasMessageTemplateParameters { get { // Have not yet parsed/rendered the FormattedMessage, so check with ILogMessageFormatter if (_formattedMessage is null && _parameters?.Length > 0) { var logMessageFormatter = MessageFormatter.Target as ILogMessageFormatter; return logMessageFormatter?.HasProperties(this) ?? false; } return false; } } /// <summary> /// Gets the named parameters extracted from parsing <see cref="Message"/> as MessageTemplate /// </summary> public MessageTemplateParameters MessageTemplateParameters { get { if (_properties != null && _properties.MessageProperties.Count > 0) { return new MessageTemplateParameters(_properties.MessageProperties, _message, _parameters); } else if (_parameters?.Length > 0) { return new MessageTemplateParameters(_message, _parameters); } else { return MessageTemplateParameters.Empty; // No parameters, means nothing to parse } } } /// <summary> /// Creates the null event. /// </summary> /// <returns>Null log event.</returns> public static LogEventInfo CreateNullEvent() { return new LogEventInfo(LogLevel.Off, string.Empty, null, string.Empty, null, null); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="message">The message.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message) { return new LogEventInfo(logLevel, loggerName, null, message, null, null); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="formatProvider">The format provider.</param> /// <param name="message">The message.</param> /// <param name="parameters">The parameters.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> [MessageTemplateFormatMethod("message")] public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object[] parameters) { return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters, null); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="formatProvider">The format provider.</param> /// <param name="message">The message.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, object message) { Exception exception = message as Exception; if (exception is null && message is LogEventInfo logEvent) { logEvent.LoggerName = loggerName; logEvent.Level = logLevel; logEvent.FormatProvider = formatProvider ?? logEvent.FormatProvider; return logEvent; } formatProvider = formatProvider ?? (exception != null ? ExceptionMessageFormatProvider.Instance : null); return new LogEventInfo(logLevel, loggerName, formatProvider, "{0}", new[] { message }, exception); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="exception">The exception.</param> /// <param name="formatProvider">The format provider.</param> /// <param name="message">The message.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message) { return new LogEventInfo(logLevel, loggerName, formatProvider, message, null, exception); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param> /// <param name="exception">The exception.</param> /// <param name="formatProvider">The format provider.</param> /// <param name="message">The message.</param> /// <param name="parameters">The parameters.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> [MessageTemplateFormatMethod("message")] public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object[] parameters) { return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters, exception); } /// <summary> /// Creates <see cref="AsyncLogEventInfo"/> from this <see cref="LogEventInfo"/> by attaching the specified asynchronous continuation. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <returns>Instance of <see cref="AsyncLogEventInfo"/> with attached continuation.</returns> public AsyncLogEventInfo WithContinuation(AsyncContinuation asyncContinuation) { return new AsyncLogEventInfo(this, asyncContinuation); } /// <summary> /// Returns a string representation of this log event. /// </summary> /// <returns>String representation of the log event.</returns> public override string ToString() { return $"Log Event: Logger='{LoggerName}' Level={Level} Message='{FormattedMessage}'"; } /// <summary> /// Sets the stack trace for the event info. /// </summary> /// <param name="stackTrace">The stack trace.</param> /// <param name="userStackFrame">Index of the first user stack frame within the stack trace (Negative means NLog should skip stackframes from System-assemblies).</param> public void SetStackTrace(StackTrace stackTrace, int userStackFrame) { GetCallSiteInformationInternal().SetStackTrace(stackTrace, userStackFrame >= 0 ? userStackFrame : (int?)null); } /// <summary> /// Sets the details retrieved from the Caller Information Attributes /// </summary> /// <param name="callerClassName"></param> /// <param name="callerMemberName"></param> /// <param name="callerFilePath"></param> /// <param name="callerLineNumber"></param> public void SetCallerInfo(string callerClassName, string callerMemberName, string callerFilePath, int callerLineNumber) { GetCallSiteInformationInternal().SetCallerInfo(callerClassName, callerMemberName, callerFilePath, callerLineNumber); } internal void AddCachedLayoutValue(Layout layout, object value) { if (_layoutCache is null) { var dictionary = new Dictionary<Layout, object>(); dictionary[layout] = value; // Faster than collection initializer if (Interlocked.CompareExchange(ref _layoutCache, dictionary, null) is null) { return; // No need to use lock } } lock (_layoutCache) { _layoutCache[layout] = value; } } internal bool TryGetCachedLayoutValue(Layout layout, out object value) { if (_layoutCache is null) { // We don't need lock to see if dictionary has been created value = null; return false; } lock (_layoutCache) { // dictionary is always non-empty when created return _layoutCache.TryGetValue(layout, out value); } } private static bool NeedToPreformatMessage(object[] parameters) { // we need to preformat message if it contains any parameters which could possibly // do logging in their ToString() if (parameters is null || parameters.Length == 0) { return false; } if (parameters.Length > 5) { // too many parameters, too costly to check return true; } for (int i = 0; i < parameters.Length; ++i) { if (!IsSafeToDeferFormatting(parameters[i])) return true; } return false; } private static bool IsSafeToDeferFormatting(object value) { return Convert.GetTypeCode(value) != TypeCode.Object; } internal bool IsLogEventMutableSafe() { if (Exception != null || _formattedMessage != null) return false; var properties = CreateOrUpdatePropertiesInternal(false); if (properties is null || properties.Count == 0) return true; // No mutable state, no need to precalculate if (properties.Count > 5) return false; // too many properties, too costly to check if (properties.Count == _parameters?.Length && properties.Count == properties.MessageProperties.Count) return true; // Already checked formatted message, no need to do it twice return HasImmutableProperties(properties); } private static bool HasImmutableProperties(PropertiesDictionary properties) { if (properties.Count == properties.MessageProperties.Count) { // Skip enumerator allocation when all properties comes from the message-template for (int i = 0; i < properties.MessageProperties.Count; ++i) { var property = properties.MessageProperties[i]; if (!IsSafeToDeferFormatting(property.Value)) return false; } } else { // Already spent the time on allocating a Dictionary, also have time for an enumerator foreach (var property in properties) { if (!IsSafeToDeferFormatting(property.Value)) return false; } } return true; } internal void SetMessageFormatter([NotNull] LogMessageFormatter messageFormatter, [CanBeNull] LogMessageFormatter singleTargetMessageFormatter) { bool hasCustomMessageFormatter = _messageFormatter != null; if (!hasCustomMessageFormatter) { _messageFormatter = messageFormatter; } if (hasCustomMessageFormatter || NeedToPreformatMessage(_parameters)) { CalcFormattedMessage(); } else { if (singleTargetMessageFormatter != null && _parameters?.Length > 0 && _message?.Length < 256) { // Change MessageFormatter so it writes directly to StringBuilder without string-allocation _messageFormatter = singleTargetMessageFormatter; } } } private void CalcFormattedMessage() { try { _formattedMessage = MessageFormatter(this); } catch (Exception exception) { _formattedMessage = Message ?? string.Empty; InternalLogger.Warn(exception, "Error when formatting a message."); if (exception.MustBeRethrown()) { throw; } } } internal void AppendFormattedMessage(ILogMessageFormatter messageFormatter, System.Text.StringBuilder builder) { if (_formattedMessage != null) { builder.Append(_formattedMessage); } else if (_parameters?.Length > 0 && !string.IsNullOrEmpty(_message)) { int originalLength = builder.Length; try { messageFormatter.AppendFormattedMessage(this, builder); } catch (Exception ex) { builder.Length = originalLength; builder.Append(_message); InternalLogger.Warn(ex, "Error when formatting a message."); if (ex.MustBeRethrown()) { throw; } } } else { builder.Append(FormattedMessage); } } private void ResetFormattedMessage(bool rebuildMessageTemplateParameters) { if (_messageFormatter is null || _messageFormatter.Target is ILogMessageFormatter) { _formattedMessage = null; } if (rebuildMessageTemplateParameters && HasMessageTemplateParameters) { CalcFormattedMessage(); } } private bool ResetMessageTemplateParameters() { if (_properties != null) { if (HasMessageTemplateParameters) _properties.MessageProperties = null; return _properties.MessageProperties.Count == 0; } return false; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using NLog.Internal; using System; using System.Collections.Generic; using System.ComponentModel; /// <summary> /// Defines available log levels. /// </summary> /// <remarks> /// Log levels ordered by severity:<br/> /// - <see cref="LogLevel.Trace"/> (Ordinal = 0) : Most verbose level. Used for development and seldom enabled in production.<br/> /// - <see cref="LogLevel.Debug"/> (Ordinal = 1) : Debugging the application behavior from internal events of interest.<br/> /// - <see cref="LogLevel.Info"/> (Ordinal = 2) : Information that highlights progress or application lifetime events.<br/> /// - <see cref="LogLevel.Warn"/> (Ordinal = 3) : Warnings about validation issues or temporary failures that can be recovered.<br/> /// - <see cref="LogLevel.Error"/> (Ordinal = 4) : Errors where functionality has failed or <see cref="System.Exception"/> have been caught.<br/> /// - <see cref="LogLevel.Fatal"/> (Ordinal = 5) : Most critical level. Application is about to abort.<br/> /// </remarks> [TypeConverter(typeof(Attributes.LogLevelTypeConverter))] public sealed class LogLevel : IComparable<LogLevel>, IComparable, IEquatable<LogLevel>, IFormattable { /// <summary> /// Trace log level (Ordinal = 0) /// </summary> /// <remarks> /// Most verbose level. Used for development and seldom enabled in production. /// </remarks> public static readonly LogLevel Trace = new LogLevel("Trace", 0); /// <summary> /// Debug log level (Ordinal = 1) /// </summary> /// <remarks> /// Debugging the application behavior from internal events of interest. /// </remarks> public static readonly LogLevel Debug = new LogLevel("Debug", 1); /// <summary> /// Info log level (Ordinal = 2) /// </summary> /// <remarks> /// Information that highlights progress or application lifetime events. /// </remarks> public static readonly LogLevel Info = new LogLevel("Info", 2); /// <summary> /// Warn log level (Ordinal = 3) /// </summary> /// <remarks> /// Warnings about validation issues or temporary failures that can be recovered. /// </remarks> public static readonly LogLevel Warn = new LogLevel("Warn", 3); /// <summary> /// Error log level (Ordinal = 4) /// </summary> /// <remarks> /// Errors where functionality has failed or <see cref="System.Exception"/> have been caught. /// </remarks> public static readonly LogLevel Error = new LogLevel("Error", 4); /// <summary> /// Fatal log level (Ordinal = 5) /// </summary> /// <remarks> /// Most critical level. Application is about to abort. /// </remarks> public static readonly LogLevel Fatal = new LogLevel("Fatal", 5); /// <summary> /// Off log level (Ordinal = 6) /// </summary> public static readonly LogLevel Off = new LogLevel("Off", 6); private static readonly IList<LogLevel> allLevels = new List<LogLevel> { Trace, Debug, Info, Warn, Error, Fatal, Off }.AsReadOnly(); private static readonly IList<LogLevel> allLoggingLevels = new List<LogLevel> { Trace, Debug, Info, Warn, Error, Fatal }.AsReadOnly(); /// <summary> /// Gets all the available log levels (Trace, Debug, Info, Warn, Error, Fatal, Off). /// </summary> public static IEnumerable<LogLevel> AllLevels => allLevels; /// <summary> /// Gets all the log levels that can be used to log events (Trace, Debug, Info, Warn, Error, Fatal) /// i.e <c>LogLevel.Off</c> is excluded. /// </summary> public static IEnumerable<LogLevel> AllLoggingLevels => allLoggingLevels; internal static LogLevel MaxLevel => Fatal; internal static LogLevel MinLevel => Trace; private readonly int _ordinal; private readonly string _name; /// <summary> /// Initializes a new instance of <see cref="LogLevel"/>. /// </summary> /// <param name="name">The log level name.</param> /// <param name="ordinal">The log level ordinal number.</param> private LogLevel(string name, int ordinal) { _name = name; _ordinal = ordinal; } /// <summary> /// Gets the name of the log level. /// </summary> public string Name => _name; /// <summary> /// Gets the ordinal of the log level. /// </summary> public int Ordinal => _ordinal; /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is equal to the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal == level2.Ordinal</c>.</returns> public static bool operator ==(LogLevel level1, LogLevel level2) { if (ReferenceEquals(level1, level2)) return true; else return (level1 ?? LogLevel.Off).Equals(level2); } /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is not equal to the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal != level2.Ordinal</c>.</returns> public static bool operator !=(LogLevel level1, LogLevel level2) { if (ReferenceEquals(level1, level2)) return false; else return !(level1 ?? LogLevel.Off).Equals(level2); } /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is greater than the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal &gt; level2.Ordinal</c>.</returns> public static bool operator >(LogLevel level1, LogLevel level2) { if (ReferenceEquals(level1, level2)) return false; else return (level1 ?? LogLevel.Off).CompareTo(level2) > 0; } /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is greater than or equal to the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal &gt;= level2.Ordinal</c>.</returns> public static bool operator >=(LogLevel level1, LogLevel level2) { if (ReferenceEquals(level1, level2)) return true; else return (level1 ?? LogLevel.Off).CompareTo(level2) >= 0; } /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is less than the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal &lt; level2.Ordinal</c>.</returns> public static bool operator <(LogLevel level1, LogLevel level2) { if (ReferenceEquals(level1, level2)) return false; else return (level1 ?? LogLevel.Off).CompareTo(level2) < 0; } /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is less than or equal to the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal &lt;= level2.Ordinal</c>.</returns> public static bool operator <=(LogLevel level1, LogLevel level2) { if (ReferenceEquals(level1, level2)) return true; else return (level1 ?? LogLevel.Off).CompareTo(level2) <= 0; } /// <summary> /// Gets the <see cref="LogLevel"/> that corresponds to the specified ordinal. /// </summary> /// <param name="ordinal">The ordinal.</param> /// <returns>The <see cref="LogLevel"/> instance. For 0 it returns <see cref="LogLevel.Trace"/>, 1 gives <see cref="LogLevel.Debug"/> and so on.</returns> public static LogLevel FromOrdinal(int ordinal) { switch (ordinal) { case 0: return Trace; case 1: return Debug; case 2: return Info; case 3: return Warn; case 4: return Error; case 5: return Fatal; case 6: return Off; default: throw new ArgumentException($"Unknown loglevel: {ordinal.ToString()}.", nameof(ordinal)); } } /// <summary> /// Returns the <see cref="NLog.LogLevel"/> that corresponds to the supplied <see langword="string" />. /// </summary> /// <param name="levelName">The textual representation of the log level.</param> /// <returns>The enumeration value.</returns> public static LogLevel FromString(string levelName) { Guard.ThrowIfNull(levelName); if (levelName.Equals("Trace", StringComparison.OrdinalIgnoreCase)) { return Trace; } if (levelName.Equals("Debug", StringComparison.OrdinalIgnoreCase)) { return Debug; } if (levelName.Equals("Info", StringComparison.OrdinalIgnoreCase)) { return Info; } if (levelName.Equals("Warn", StringComparison.OrdinalIgnoreCase)) { return Warn; } if (levelName.Equals("Error", StringComparison.OrdinalIgnoreCase)) { return Error; } if (levelName.Equals("Fatal", StringComparison.OrdinalIgnoreCase)) { return Fatal; } if (levelName.Equals("Off", StringComparison.OrdinalIgnoreCase)) { return Off; } if (levelName.Equals("None", StringComparison.OrdinalIgnoreCase)) { return Off; // .NET Core Microsoft Extension Logging } if (levelName.Equals("Information", StringComparison.OrdinalIgnoreCase)) { return Info; // .NET Core Microsoft Extension Logging } if (levelName.Equals("Warning", StringComparison.OrdinalIgnoreCase)) { return Warn; // .NET Core Microsoft Extension Logging } throw new ArgumentException($"Unknown log level: {levelName}", nameof(levelName)); } /// <summary> /// Returns a string representation of the log level. /// </summary> /// <returns>Log level name.</returns> public override string ToString() { return _name; } string IFormattable.ToString(string format, IFormatProvider formatProvider) { if (format is null || (!"D".Equals(format, StringComparison.OrdinalIgnoreCase))) return _name; else return _ordinal.ToString(); // Like Enum.ToString("D") } /// <inheritdoc/> public override int GetHashCode() { return _ordinal; } /// <inheritdoc/> public override bool Equals(object obj) { return Equals(obj as LogLevel); } /// <summary> /// Determines whether the specified <see cref="NLog.LogLevel"/> instance is equal to this instance. /// </summary> /// <param name="other">The <see cref="NLog.LogLevel"/> to compare with this instance.</param> /// <returns>Value of <c>true</c> if the specified <see cref="NLog.LogLevel"/> is equal to /// this instance; otherwise, <c>false</c>.</returns> public bool Equals(LogLevel other) { return _ordinal == other?._ordinal; } /// <summary> /// Compares the level to the other <see cref="LogLevel"/> object. /// </summary> /// <param name="obj">The other object.</param> /// <returns> /// A value less than zero when this logger's <see cref="Ordinal"/> is /// less than the other logger's ordinal, 0 when they are equal and /// greater than zero when this ordinal is greater than the /// other ordinal. /// </returns> public int CompareTo(object obj) { return CompareTo((LogLevel)obj); } /// <summary> /// Compares the level to the other <see cref="LogLevel"/> object. /// </summary> /// <param name="other">The other object.</param> /// <returns> /// A value less than zero when this logger's <see cref="Ordinal"/> is /// less than the other logger's ordinal, 0 when they are equal and /// greater than zero when this ordinal is greater than the /// other ordinal. /// </returns> public int CompareTo(LogLevel other) { return _ordinal - (other ?? LogLevel.Off)._ordinal; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LayoutRenderers.Wrappers { using NLog; using NLog.Layouts; using Xunit; public class PaddingTests : NLogTestBase { [Fact] public void PositivePaddingWithLeftAlign() { SimpleLayout l; var le = LogEventInfo.Create(LogLevel.Info, "", "VeryBigMessage"); l = @"${message:padding=16:alignmentOnTruncation=left}"; Assert.Equal(" VeryBigMessage", l.Render(le)); l = @"${message:padding=15:alignmentOnTruncation=left}"; Assert.Equal(" VeryBigMessage", l.Render(le)); l = @"${message:padding=14:alignmentOnTruncation=left}"; Assert.Equal("VeryBigMessage", l.Render(le)); l = @"${message:padding=13:alignmentOnTruncation=left}"; Assert.Equal("VeryBigMessage", l.Render(le)); l = @"${message:padding=13:alignmentOnTruncation=left:fixedLength=true}"; Assert.Equal("VeryBigMessag", l.Render(le)); l = @"${level:padding=6:alignmentOnTruncation=left}"; Assert.Equal(" Info", l.Render(le)); l = @"${level:padding=5:alignmentOnTruncation=left}"; Assert.Equal(" Info", l.Render(le)); l = @"${level:padding=4:alignmentOnTruncation=left}"; Assert.Equal("Info", l.Render(le)); l = @"${level:padding=3:alignmentOnTruncation=left}"; Assert.Equal("Info", l.Render(le)); l = @"${level:padding=2:alignmentOnTruncation=left}"; Assert.Equal("Info", l.Render(le)); l = @"${level:padding=2:fixedLength=true:alignmentOnTruncation=left}"; Assert.Equal("In", l.Render(le)); l = @"${level:padding=1:fixedLength=true:alignmentOnTruncation=left}"; Assert.Equal("I", l.Render(le)); l = @"${logger:padding=5:alignmentOnTruncation=left}"; Assert.Equal(" ", l.Render(le)); } [Fact] public void PositivePaddingWithRightAlign() { SimpleLayout l; var le = LogEventInfo.Create(LogLevel.Info, "", "VeryBigMessage"); l = @"${message:padding=16:alignmentOnTruncation=right}"; Assert.Equal(" VeryBigMessage", l.Render(le)); l = @"${message:padding=15:alignmentOnTruncation=right}"; Assert.Equal(" VeryBigMessage", l.Render(le)); l = @"${message:padding=14:alignmentOnTruncation=right}"; Assert.Equal("VeryBigMessage", l.Render(le)); l = @"${message:padding=13:alignmentOnTruncation=right}"; Assert.Equal("VeryBigMessage", l.Render(le)); l = @"${message:padding=13:alignmentOnTruncation=right:fixedLength=true}"; Assert.Equal("eryBigMessage", l.Render(le)); l = @"${level:padding=6:alignmentOnTruncation=right}"; Assert.Equal(" Info", l.Render(le)); l = @"${level:padding=5:alignmentOnTruncation=right}"; Assert.Equal(" Info", l.Render(le)); l = @"${level:padding=4:alignmentOnTruncation=right}"; Assert.Equal("Info", l.Render(le)); l = @"${level:padding=3:alignmentOnTruncation=right}"; Assert.Equal("Info", l.Render(le)); l = @"${level:padding=2:fixedLength=true:alignmentOnTruncation=right}"; Assert.Equal("fo", l.Render(le)); l = @"${level:padding=1:fixedLength=true:alignmentOnTruncation=right}"; Assert.Equal("o", l.Render(le)); l = @"${logger:padding=5:alignmentOnTruncation=right}"; Assert.Equal(" ", l.Render(le)); } [Fact] public void NegativePaddingWithLeftAlign() { SimpleLayout l; var le = LogEventInfo.Create(LogLevel.Info, "", "VeryBigMessage"); l = @"${message:padding=-16:alignmentOnTruncation=left}"; Assert.Equal("VeryBigMessage ", l.Render(le)); l = @"${message:padding=-15:alignmentOnTruncation=left}"; Assert.Equal("VeryBigMessage ", l.Render(le)); l = @"${message:padding=-14:alignmentOnTruncation=left}"; Assert.Equal("VeryBigMessage", l.Render(le)); l = @"${message:padding=-13:alignmentOnTruncation=left}"; Assert.Equal("VeryBigMessage", l.Render(le)); l = @"${message:padding=-13:alignmentOnTruncation=left:fixedLength=true}"; Assert.Equal("VeryBigMessag", l.Render(le)); l = @"${level:padding=-6:alignmentOnTruncation=left}"; Assert.Equal("Info ", l.Render(le)); l = @"${level:padding=-5:alignmentOnTruncation=left}"; Assert.Equal("Info ", l.Render(le)); l = @"${level:padding=-4:alignmentOnTruncation=left}"; Assert.Equal("Info", l.Render(le)); l = @"${level:padding=-3:alignmentOnTruncation=left}"; Assert.Equal("Info", l.Render(le)); l = @"${level:padding=-2:alignmentOnTruncation=left}"; Assert.Equal("Info", l.Render(le)); l = @"${level:padding=-2:fixedLength=true:alignmentOnTruncation=left}"; Assert.Equal("In", l.Render(le)); l = @"${level:padding=-1:fixedLength=true:alignmentOnTruncation=left}"; Assert.Equal("I", l.Render(le)); l = @"${logger:padding=-5:alignmentOnTruncation=left}"; Assert.Equal(" ", l.Render(le)); } [Fact] public void NegativePaddingWithRightAlign() { SimpleLayout l; var le = LogEventInfo.Create(LogLevel.Info, "", "VeryBigMessage"); l = @"${message:padding=-16:alignmentOnTruncation=right}"; Assert.Equal("VeryBigMessage ", l.Render(le)); l = @"${message:padding=-15:alignmentOnTruncation=right}"; Assert.Equal("VeryBigMessage ", l.Render(le)); l = @"${message:padding=-14:alignmentOnTruncation=right}"; Assert.Equal("VeryBigMessage", l.Render(le)); l = @"${message:padding=-13:alignmentOnTruncation=right}"; Assert.Equal("VeryBigMessage", l.Render(le)); l = @"${message:padding=-13:alignmentOnTruncation=right:fixedLength=true}"; Assert.Equal("eryBigMessage", l.Render(le)); l = @"${level:padding=-6:alignmentOnTruncation=right}"; Assert.Equal("Info ", l.Render(le)); l = @"${level:padding=-5:alignmentOnTruncation=right}"; Assert.Equal("Info ", l.Render(le)); l = @"${level:padding=-4:alignmentOnTruncation=right}"; Assert.Equal("Info", l.Render(le)); l = @"${level:padding=-3:alignmentOnTruncation=right}"; Assert.Equal("Info", l.Render(le)); l = @"${level:padding=-2:alignmentOnTruncation=right}"; Assert.Equal("Info", l.Render(le)); l = @"${level:padding=-2:fixedLength=true:alignmentOnTruncation=right}"; Assert.Equal("fo", l.Render(le)); l = @"${level:padding=-1:fixedLength=true:alignmentOnTruncation=right}"; Assert.Equal("o", l.Render(le)); l = @"${logger:padding=-5:alignmentOnTruncation=right}"; Assert.Equal(" ", l.Render(le)); } [Fact] public void DefaultAlignmentIsLeft() { SimpleLayout defaultLayout, leftLayout, rightLayout; var le = LogEventInfo.Create(LogLevel.Info, "", "VeryBigMessage"); defaultLayout = @"${message:padding=5:fixedLength=true}"; leftLayout = @"${message:padding=5:fixedLength=true:alignmentOnTruncation=left}"; rightLayout = @"${message:padding=5:fixedLength=true:alignmentOnTruncation=right}"; Assert.Equal(leftLayout.Render(le), defaultLayout.Render(le)); Assert.NotEqual(rightLayout.Render(le), defaultLayout.Render(le)); } } } <file_sep>using System; using System.Linq; namespace NLog.SourceCodeTests { class Program { static int Main(string[] args) { var tests = new SourceCodeTests(); var success = tests.VerifyFileHeaders(); success = success & tests.VerifyNamespacesAndClassNames(); var noInteractive = args.FirstOrDefault() == "no-interactive"; if (success) { Console.WriteLine("YESS everything OK"); } if (!noInteractive) { Console.WriteLine("press any key"); Console.ReadKey(); } if (success) { //error return 0; } return 1; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 #define SupportsMutex #endif namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.IO.Compression; using System.Text; using System.Threading; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Internal.FileAppenders; using NLog.Layouts; using NLog.Targets.FileArchiveModes; using NLog.Time; /// <summary> /// Writes log messages to one or more files. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/File-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/File-target">Documentation on NLog Wiki</seealso> [Target("File")] public class FileTarget : TargetWithLayoutHeaderAndFooter, ICreateFileParameters { /// <summary> /// Default clean up period of the initialized files. When a file exceeds the clean up period is removed from the list. /// </summary> /// <remarks>Clean up period is defined in days.</remarks> private const int InitializedFilesCleanupPeriod = 2; /// <summary> /// This value disables file archiving based on the size. /// </summary> private const long ArchiveAboveSizeDisabled = -1L; /// <summary> /// Holds the initialized files each given time by the <see cref="FileTarget"/> instance. Against each file, the last write time is stored. /// </summary> /// <remarks>Last write time is store in local time (no UTC).</remarks> private readonly Dictionary<string, DateTime> _initializedFiles = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase); /// <summary> /// List of the associated file appenders with the <see cref="FileTarget"/> instance. /// </summary> private IFileAppenderCache _fileAppenderCache; IFileArchiveMode GetFileArchiveHelper(string archiveFilePattern) { return _fileArchiveHelper ?? (_fileArchiveHelper = FileArchiveModeFactory.CreateArchiveStyle(archiveFilePattern, ArchiveNumbering, GetArchiveDateFormatString(ArchiveDateFormat), ArchiveFileName != null, MaxArchiveFiles > 0 || MaxArchiveDays > 0)); } private IFileArchiveMode _fileArchiveHelper; private Timer _autoClosingTimer; /// <summary> /// The number of initialized files at any one time. /// </summary> private int _initializedFilesCounter; /// <summary> /// The maximum number of archive files that should be kept. /// </summary> private int _maxArchiveFiles; /// <summary> /// The maximum days of archive files that should be kept. /// </summary> private int _maxArchiveDays; /// <summary> /// The filename as target /// </summary> private FilePathLayout _fullFileName; /// <summary> /// The archive file name as target /// </summary> private FilePathLayout _fullArchiveFileName; private FileArchivePeriod _archiveEvery; private long _archiveAboveSize; private bool _enableArchiveFileCompression; /// <summary> /// The date of the previous log event. /// </summary> private DateTime? _previousLogEventTimestamp; /// <summary> /// The file name of the previous log event. /// </summary> private string _previousLogFileName; private bool _concurrentWrites; private bool _cleanupFileName; private FilePathKind _fileNameKind = FilePathKind.Unknown; private FilePathKind _archiveFileKind; /// <summary> /// Initializes a new instance of the <see cref="FileTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> public FileTarget() : this(FileAppenderCache.Empty) { } internal FileTarget(IFileAppenderCache fileAppenderCache) { ArchiveNumbering = ArchiveNumberingMode.Sequence; _maxArchiveFiles = 0; _maxArchiveDays = 0; ArchiveEvery = FileArchivePeriod.None; ArchiveAboveSize = ArchiveAboveSizeDisabled; _cleanupFileName = true; _fileAppenderCache = fileAppenderCache; } #if !NET35 && !NET40 static FileTarget() { FileCompressor = new ZipArchiveFileCompressor(); } #endif /// <summary> /// Initializes a new instance of the <see cref="FileTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> /// <param name="name">Name of the target.</param> public FileTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets the name of the file to write to. /// </summary> /// <remarks> /// This FileName string is a layout which may include instances of layout renderers. /// This lets you use a single target to write to multiple files. /// </remarks> /// <example> /// The following value makes NLog write logging events to files based on the log level in the directory where /// the application runs. /// <code>${basedir}/${level}.log</code> /// All <c>Debug</c> messages will go to <c>Debug.log</c>, all <c>Info</c> messages will go to <c>Info.log</c> and so on. /// You can combine as many of the layout renderers as you want to produce an arbitrary log file name. /// </example> /// <docgen category='General Options' order='2' /> [RequiredParameter] public Layout FileName { get { return _fullFileName?.GetLayout(); } set { _fullFileName = CreateFileNameLayout(value); ResetFileAppenders("FileName Changed"); } } private FilePathLayout CreateFileNameLayout(Layout value) { if (value is null) return null; return new FilePathLayout(value, CleanupFileName, FileNameKind); } /// <summary> /// Cleanup invalid values in a filename, e.g. slashes in a filename. If set to <c>true</c>, this can impact the performance of massive writes. /// If set to <c>false</c>, nothing gets written when the filename is wrong. /// </summary> /// <docgen category='Output Options' order='100' /> public bool CleanupFileName { get => _cleanupFileName; set { if (_cleanupFileName != value) { _cleanupFileName = value; _fullFileName = CreateFileNameLayout(FileName); _fullArchiveFileName = CreateFileNameLayout(ArchiveFileName); ResetFileAppenders("CleanupFileName Changed"); } } } /// <summary> /// Is the <see cref="FileName"/> an absolute or relative path? /// </summary> /// <docgen category='Output Options' order='100' /> public FilePathKind FileNameKind { get => _fileNameKind; set { if (_fileNameKind != value) { _fileNameKind = value; _fullFileName = CreateFileNameLayout(FileName); _fullArchiveFileName = CreateFileNameLayout(ArchiveFileName); ResetFileAppenders("FileNameKind Changed"); } } } /// <summary> /// Gets or sets a value indicating whether to create directories if they do not exist. /// </summary> /// <remarks> /// Setting this to false may improve performance a bit, but you'll receive an error /// when attempting to write to a directory that's not present. /// </remarks> /// <docgen category='Output Options' order='50' /> public bool CreateDirs { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether to delete old log file on startup. /// </summary> /// <remarks> /// This option works only when the "FileName" parameter denotes a single file. /// </remarks> /// <docgen category='Output Options' order='50' /> public bool DeleteOldFileOnStartup { get; set; } /// <summary> /// Gets or sets a value indicating whether to replace file contents on each write instead of appending log message at the end. /// </summary> /// <docgen category='Output Options' order='100' /> public bool ReplaceFileContentsOnEachWrite { get; set; } /// <summary> /// Gets or sets a value indicating whether to keep log file open instead of opening and closing it on each logging event. /// </summary> /// <remarks> /// KeepFileOpen = true gives the best performance, and ensure the file-lock is not lost to other applications.<br/> /// KeepFileOpen = false gives the best compability, but slow performance and lead to file-locking issues with other applications. /// </remarks> /// <docgen category='Performance Tuning Options' order='10' /> public bool KeepFileOpen { get => _keepFileOpen; set { if (_keepFileOpen != value) { _keepFileOpen = value; ResetFileAppenders("KeepFileOpen Changed"); } } } private bool _keepFileOpen = true; /// <summary> /// Gets or sets a value indicating whether to enable log file(s) to be deleted. /// </summary> /// <docgen category='Output Options' order='50' /> public bool EnableFileDelete { get; set; } = true; /// <summary> /// Gets or sets the file attributes (Windows only). /// </summary> /// <docgen category='Output Options' order='100' /> public Win32FileAttributes FileAttributes { get => _fileAttributes; set { if (value != Win32FileAttributes.Normal && PlatformDetector.IsWin32) { ForceManaged = false; } _fileAttributes = value; } } Win32FileAttributes _fileAttributes = Win32FileAttributes.Normal; bool ICreateFileParameters.IsArchivingEnabled => IsArchivingEnabled; int ICreateFileParameters.FileOpenRetryCount => ConcurrentWrites ? ConcurrentWriteAttempts : (KeepFileOpen ? 0 : (_concurrentWriteAttempts ?? 2)); int ICreateFileParameters.FileOpenRetryDelay => ConcurrentWriteAttemptDelay; /// <summary> /// Gets or sets the line ending mode. /// </summary> /// <docgen category='Output Options' order='100' /> public LineEndingMode LineEnding { get; set; } = LineEndingMode.Default; /// <summary> /// Gets or sets a value indicating whether to automatically flush the file buffers after each log message. /// </summary> /// <docgen category='Performance Tuning Options' order='50' /> public bool AutoFlush { get; set; } = true; /// <summary> /// Gets or sets the number of files to be kept open. Setting this to a higher value may improve performance /// in a situation where a single File target is writing to many files /// (such as splitting by level or by logger). /// </summary> /// <remarks> /// The files are managed on a LRU (least recently used) basis, which flushes /// the files that have not been used for the longest period of time should the /// cache become full. As a rule of thumb, you shouldn't set this parameter to /// a very high value. A number like 10-15 shouldn't be exceeded, because you'd /// be keeping a large number of files open which consumes system resources. /// </remarks> /// <docgen category='Performance Tuning Options' order='10' /> public int OpenFileCacheSize { get; set; } = 5; /// <summary> /// Gets or sets the maximum number of seconds that files are kept open. Zero or negative means disabled. /// </summary> /// <docgen category='Performance Tuning Options' order='50' /> public int OpenFileCacheTimeout { get; set; } /// <summary> /// Gets or sets the maximum number of seconds before open files are flushed. Zero or negative means disabled. /// </summary> /// <docgen category='Performance Tuning Options' order='50' /> public int OpenFileFlushTimeout { get; set; } /// <summary> /// Gets or sets the log file buffer size in bytes. /// </summary> /// <docgen category='Performance Tuning Options' order='50' /> public int BufferSize { get; set; } = 32768; /// <summary> /// Gets or sets the file encoding. /// </summary> /// <docgen category='Output Options' order='10' /> public Encoding Encoding { get => _encoding; set { _encoding = value; if (!_writeBom.HasValue && InitialValueBom(value)) _writeBom = true; } } private Encoding _encoding = Encoding.UTF8; /// <summary> /// Gets or sets whether or not this target should just discard all data that its asked to write. /// Mostly used for when testing NLog Stack except final write /// </summary> /// <docgen category='Performance Tuning Options' order='100' /> public bool DiscardAll { get; set; } /// <summary> /// Gets or sets a value indicating whether concurrent writes to the log file by multiple processes on the same host. /// </summary> /// <remarks> /// This makes multi-process logging possible. NLog uses a special technique /// that lets it keep the files open for writing. /// </remarks> /// <docgen category='Performance Tuning Options' order='10' /> public bool ConcurrentWrites { get => _concurrentWrites; set { if (_concurrentWrites != value) { _concurrentWrites = value; ResetFileAppenders("ConcurrentWrites Changed"); } } } /// <summary> /// Gets or sets a value indicating whether concurrent writes to the log file by multiple processes on different network hosts. /// </summary> /// <remarks> /// This effectively prevents files from being kept open. /// </remarks> /// <docgen category='Performance Tuning Options' order='50' /> public bool NetworkWrites { get; set; } /// <summary> /// Gets or sets a value indicating whether to write BOM (byte order mark) in created files. /// /// Defaults to true for UTF-16 and UTF-32 /// </summary> /// <docgen category='Output Options' order='50' /> public bool WriteBom { get => _writeBom ?? false; set => _writeBom = value; } private bool? _writeBom; /// <summary> /// Gets or sets the number of times the write is appended on the file before NLog /// discards the log message. /// </summary> /// <docgen category='Performance Tuning Options' order='100' /> public int ConcurrentWriteAttempts { get => _concurrentWriteAttempts ?? 10; set => _concurrentWriteAttempts = value; } private int? _concurrentWriteAttempts; /// <summary> /// Gets or sets the delay in milliseconds to wait before attempting to write to the file again. /// </summary> /// <remarks> /// The actual delay is a random value between 0 and the value specified /// in this parameter. On each failed attempt the delay base is doubled /// up to <see cref="ConcurrentWriteAttempts" /> times. /// </remarks> /// <example> /// Assuming that ConcurrentWriteAttemptDelay is 10 the time to wait will be:<p/> /// a random value between 0 and 10 milliseconds - 1st attempt<br/> /// a random value between 0 and 20 milliseconds - 2nd attempt<br/> /// a random value between 0 and 40 milliseconds - 3rd attempt<br/> /// a random value between 0 and 80 milliseconds - 4th attempt<br/> /// ...<p/> /// and so on. /// </example> /// <docgen category='Performance Tuning Options' order='100' /> public int ConcurrentWriteAttemptDelay { get; set; } = 1; /// <summary> /// Gets or sets a value indicating whether to archive old log file on startup. /// </summary> /// <remarks> /// This option works only when the "FileName" parameter denotes a single file. /// After archiving the old file, the current log file will be empty. /// </remarks> /// <docgen category='Archival Options' order='50' /> public bool ArchiveOldFileOnStartup { get => _archiveOldFileOnStartup ?? false; set => _archiveOldFileOnStartup = value; } private bool? _archiveOldFileOnStartup; /// <summary> /// Gets or sets a value of the file size threshold to archive old log file on startup. /// </summary> /// <remarks> /// This option won't work if <see cref="ArchiveOldFileOnStartup"/> is set to <c>false</c> /// Default value is 0 which means that the file is archived as soon as archival on /// startup is enabled. /// </remarks> /// <docgen category='Archival Options' order='50' /> public long ArchiveOldFileOnStartupAboveSize { get; set; } /// <summary> /// Gets or sets a value specifying the date format to use when archiving files. /// </summary> /// <remarks> /// This option works only when the "ArchiveNumbering" parameter is set either to Date or DateAndSequence. /// </remarks> /// <docgen category='Archival Options' order='50' /> public string ArchiveDateFormat { get => _archiveDateFormat; set { if (_archiveDateFormat != value) { _archiveDateFormat = value; ResetFileAppenders("ArchiveDateFormat Changed"); // Reset archive file-monitoring } } } private string _archiveDateFormat = string.Empty; /// <summary> /// Gets or sets the size in bytes above which log files will be automatically archived. /// </summary> /// <remarks> /// Notice when combined with <see cref="ArchiveNumberingMode.Date"/> then it will attempt to append to any existing /// archive file if grown above size multiple times. New archive file will be created when using <see cref="ArchiveNumberingMode.DateAndSequence"/> /// </remarks> /// <docgen category='Archival Options' order='50' /> public long ArchiveAboveSize { get => _archiveAboveSize; set { var newValue = value > 0 ? value : ArchiveAboveSizeDisabled; if ((_archiveAboveSize > 0) != (newValue > 0)) { _archiveAboveSize = newValue; ResetFileAppenders("ArchiveAboveSize Changed"); // Reset archive file-monitoring } else { _archiveAboveSize = newValue; } } } /// <summary> /// Gets or sets a value indicating whether to automatically archive log files every time the specified time passes. /// </summary> /// <remarks> /// Files are moved to the archive as part of the write operation if the current period of time changes. For example /// if the current <c>hour</c> changes from 10 to 11, the first write that will occur /// on or after 11:00 will trigger the archiving. /// </remarks> /// <docgen category='Archival Options' order='50' /> public FileArchivePeriod ArchiveEvery { get => _archiveEvery; set { if (_archiveEvery != value) { _archiveEvery = value; ResetFileAppenders("ArchiveEvery Changed"); // Reset archive file-monitoring } } } /// <summary> /// Is the <see cref="ArchiveFileName"/> an absolute or relative path? /// </summary> /// <docgen category='Archival Options' order='50' /> public FilePathKind ArchiveFileKind { get => _archiveFileKind; set { if (_archiveFileKind != value) { _archiveFileKind = value; _fullArchiveFileName = CreateFileNameLayout(ArchiveFileName); ResetFileAppenders("ArchiveFileKind Changed"); // Reset archive file-monitoring } } } /// <summary> /// Gets or sets the name of the file to be used for an archive. /// </summary> /// <remarks> /// It may contain a special placeholder {#####} /// that will be replaced with a sequence of numbers depending on /// the archiving strategy. The number of hash characters used determines /// the number of numerical digits to be used for numbering files. /// </remarks> /// <docgen category='Archival Options' order='50' /> public Layout ArchiveFileName { get { return _fullArchiveFileName?.GetLayout(); } set { _fullArchiveFileName = CreateFileNameLayout(value); ResetFileAppenders("ArchiveFileName Changed"); // Reset archive file-monitoring } } /// <summary> /// Gets or sets the maximum number of archive files that should be kept. /// </summary> /// <docgen category='Archival Options' order='50' /> public int MaxArchiveFiles { get => _maxArchiveFiles; set { if (_maxArchiveFiles != value) { _maxArchiveFiles = value; ResetFileAppenders("MaxArchiveFiles Changed"); // Enforce archive cleanup } } } /// <summary> /// Gets or sets the maximum days of archive files that should be kept. /// </summary> /// <docgen category='Archival Options' order='50' /> public int MaxArchiveDays { get => _maxArchiveDays; set { if (_maxArchiveDays != value) { _maxArchiveDays = value; ResetFileAppenders("MaxArchiveDays Changed"); // Enforce archive cleanup } } } /// <summary> /// Gets or sets the way file archives are numbered. /// </summary> /// <docgen category='Archival Options' order='50' /> public ArchiveNumberingMode ArchiveNumbering { get => _archiveNumbering; set { if (_archiveNumbering != value) { _archiveNumbering = value; ResetFileAppenders("ArchiveNumbering Changed"); // Reset archive file-monitoring } } } private ArchiveNumberingMode _archiveNumbering; /// <summary> /// Used to compress log files during archiving. /// This may be used to provide your own implementation of a zip file compressor, /// on platforms other than .Net4.5. /// Defaults to ZipArchiveFileCompressor on .Net4.5 and to null otherwise. /// </summary> /// <docgen category='Archival Options' order='50' /> public static IFileCompressor FileCompressor { get; set; } /// <summary> /// Gets or sets a value indicating whether to compress archive files into the zip archive format. /// </summary> /// <docgen category='Archival Options' order='50' /> public bool EnableArchiveFileCompression { get => _enableArchiveFileCompression && FileCompressor != null; set { if (_enableArchiveFileCompression != value) { _enableArchiveFileCompression = value; ResetFileAppenders("EnableArchiveFileCompression Changed"); // Reset archive file-monitoring } } } /// <summary> /// Gets or set a value indicating whether a managed file stream is forced, instead of using the native implementation. /// </summary> /// <docgen category='Output Options' order='100' /> public bool ForceManaged { get; set; } = true; #if SupportsMutex /// <summary> /// Gets or sets a value indicating whether file creation calls should be synchronized by a system global mutex. /// </summary> /// <docgen category='Output Options' order='100' /> public bool ForceMutexConcurrentWrites { get; set; } #endif /// <summary> /// Gets or sets a value indicating whether the footer should be written only when the file is archived. /// </summary> /// <docgen category='Archival Options' order='50' /> public bool WriteFooterOnArchivingOnly { get; set; } /// <summary> /// Gets the characters that are appended after each line. /// </summary> protected internal string NewLineChars => LineEnding.NewLineCharacters; /// <summary> /// Refresh the ArchiveFilePatternToWatch option of the <see cref="FileAppenderCache" />. /// The log file must be watched for archiving when multiple processes are writing to the same /// open file. /// </summary> private void RefreshArchiveFilePatternToWatch(string fileName, LogEventInfo logEvent) { _fileAppenderCache.CheckCloseAppenders -= AutoCloseAppendersAfterArchive; bool mustWatchArchiving = IsArchivingEnabled && KeepFileOpen && ConcurrentWrites; bool mustWatchActiveFile = EnableFileDelete && ((KeepFileOpen && ConcurrentWrites) || (IsSimpleKeepFileOpen && !EnableFileDeleteSimpleMonitor)); if (mustWatchArchiving || mustWatchActiveFile) { _fileAppenderCache.CheckCloseAppenders += AutoCloseAppendersAfterArchive; // Activates FileSystemWatcher } #if !NETSTANDARD1_3 if (mustWatchArchiving) { string archiveFilePattern = GetArchiveFileNamePattern(fileName, logEvent); var fileArchiveStyle = !string.IsNullOrEmpty(archiveFilePattern) ? GetFileArchiveHelper(archiveFilePattern) : null; string fileNameMask = fileArchiveStyle != null ? _fileArchiveHelper.GenerateFileNameMask(archiveFilePattern) : string.Empty; string directoryMask = !string.IsNullOrEmpty(fileNameMask) ? Path.Combine(Path.GetDirectoryName(archiveFilePattern), fileNameMask) : string.Empty; _fileAppenderCache.ArchiveFilePatternToWatch = directoryMask; } else { _fileAppenderCache.ArchiveFilePatternToWatch = null; } #endif } /// <summary> /// Removes records of initialized files that have not been /// accessed in the last two days. /// </summary> /// <remarks> /// Files are marked 'initialized' for the purpose of writing footers when the logging finishes. /// </remarks> public void CleanupInitializedFiles() { try { CleanupInitializedFiles(TimeSource.Current.Time.AddDays(-InitializedFilesCleanupPeriod)); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) throw; InternalLogger.Error(exception, "{0}: Exception in CleanupInitializedFiles", this); } } /// <summary> /// Removes records of initialized files that have not been /// accessed after the specified date. /// </summary> /// <param name="cleanupThreshold">The cleanup threshold.</param> /// <remarks> /// Files are marked 'initialized' for the purpose of writing footers when the logging finishes. /// </remarks> public void CleanupInitializedFiles(DateTime cleanupThreshold) { InternalLogger.Trace("{0}: CleanupInitializedFiles with cleanupThreshold {1}", this, cleanupThreshold); List<string> filesToFinalize = null; // Select the files require to be finalized. foreach (var file in _initializedFiles) { if (file.Value < cleanupThreshold) { if (filesToFinalize is null) { filesToFinalize = new List<string>(); } filesToFinalize.Add(file.Key); } } // Finalize the files. if (filesToFinalize != null) { foreach (string fileName in filesToFinalize) { FinalizeFile(fileName); } } InternalLogger.Trace("{0}: CleanupInitializedFiles Completed and finalized {0} files", this, filesToFinalize?.Count ?? 0); } /// <summary> /// Flushes all pending file operations. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <remarks> /// The timeout parameter is ignored, because file APIs don't provide /// the needed functionality. /// </remarks> protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { InternalLogger.Trace("{0}: FlushAsync", this); _fileAppenderCache.FlushAppenders(); asyncContinuation(null); InternalLogger.Trace("{0}: FlushAsync Done", this); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception)) { throw; } asyncContinuation(exception); } } /// <summary> /// Returns the suitable appender factory ( <see cref="IFileAppenderFactory"/>) to be used to generate the file /// appenders associated with the <see cref="FileTarget"/> instance. /// /// The type of the file appender factory returned depends on the values of various <see cref="FileTarget"/> properties. /// </summary> /// <returns><see cref="IFileAppenderFactory"/> suitable for this instance.</returns> private IFileAppenderFactory GetFileAppenderFactory() { if (DiscardAll) { return NullAppender.TheFactory; } else if (!KeepFileOpen) { return RetryingMultiProcessFileAppender.TheFactory; } else if (NetworkWrites) { return RetryingMultiProcessFileAppender.TheFactory; } else if (ConcurrentWrites) { #if SupportsMutex if (!ForceMutexConcurrentWrites) { #if MONO if (PlatformDetector.IsUnix) { return UnixMultiProcessFileAppender.TheFactory; } #elif !NETSTANDARD if (PlatformDetector.IsWin32 && !PlatformDetector.IsMono) { return WindowsMultiProcessFileAppender.TheFactory; } #endif } if (MutexDetector.SupportsSharableMutex) { return MutexMultiProcessFileAppender.TheFactory; } else #endif // SupportsMutex { return RetryingMultiProcessFileAppender.TheFactory; } } else if (IsArchivingEnabled) return CountingSingleProcessFileAppender.TheFactory; else return SingleProcessFileAppender.TheFactory; } private bool IsArchivingEnabled => ArchiveAboveSize != ArchiveAboveSizeDisabled || ArchiveEvery != FileArchivePeriod.None; private bool IsSimpleKeepFileOpen => KeepFileOpen && !ConcurrentWrites && !NetworkWrites && !ReplaceFileContentsOnEachWrite; private bool EnableFileDeleteSimpleMonitor => EnableFileDelete && IsSimpleKeepFileOpen #if !NETSTANDARD && !PlatformDetector.IsWin32 #endif ; bool ICreateFileParameters.EnableFileDeleteSimpleMonitor => EnableFileDeleteSimpleMonitor; /// <summary> /// Initializes file logging by creating data structures that /// enable efficient multi-file logging. /// </summary> protected override void InitializeTarget() { base.InitializeTarget(); var appenderFactory = GetFileAppenderFactory(); if (InternalLogger.IsTraceEnabled) { InternalLogger.Trace("{0}: Using appenderFactory: {1}", this, appenderFactory.GetType()); } _fileAppenderCache = new FileAppenderCache(OpenFileCacheSize, appenderFactory, this); if ((OpenFileCacheSize > 0 || EnableFileDelete) && (OpenFileCacheTimeout > 0 || OpenFileFlushTimeout > 0)) { int openFileAutoTimeoutSecs = (OpenFileCacheTimeout > 0 && OpenFileFlushTimeout > 0) ? Math.Min(OpenFileCacheTimeout, OpenFileFlushTimeout) : Math.Max(OpenFileCacheTimeout, OpenFileFlushTimeout); InternalLogger.Trace("{0}: Start autoClosingTimer", this); _autoClosingTimer = new Timer( (state) => AutoClosingTimerCallback(this, EventArgs.Empty), null, openFileAutoTimeoutSecs * 1000, openFileAutoTimeoutSecs * 1000); } } /// <summary> /// Closes the file(s) opened for writing. /// </summary> protected override void CloseTarget() { base.CloseTarget(); foreach (string fileName in new List<string>(_initializedFiles.Keys)) { FinalizeFile(fileName); } _fileArchiveHelper = null; var currentTimer = _autoClosingTimer; if (currentTimer != null) { InternalLogger.Trace("{0}: Stop autoClosingTimer", this); _autoClosingTimer = null; currentTimer.WaitForDispose(TimeSpan.Zero); } _fileAppenderCache.CloseAppenders("Dispose"); _fileAppenderCache.Dispose(); } private void ResetFileAppenders(string reason) { _fileArchiveHelper = null; if (IsInitialized) { _fileAppenderCache.CloseAppenders(reason); _initializedFiles.Clear(); } } private readonly ReusableStreamCreator _reusableFileWriteStream = new ReusableStreamCreator(4096); private readonly ReusableStreamCreator _reusableAsyncFileWriteStream = new ReusableStreamCreator(4096); private readonly ReusableBufferCreator _reusableEncodingBuffer = new ReusableBufferCreator(1024); /// <summary> /// Writes the specified logging event to a file specified in the FileName /// parameter. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(LogEventInfo logEvent) { var logFileName = GetFullFileName(logEvent); if (string.IsNullOrEmpty(logFileName)) { throw new ArgumentException("The path is not of a legal form."); } using (var targetStream = _reusableFileWriteStream.Allocate()) { using (var targetBuilder = ReusableLayoutBuilder.Allocate()) using (var targetBuffer = _reusableEncodingBuffer.Allocate()) { RenderFormattedMessageToStream(logEvent, targetBuilder.Result, targetBuffer.Result, targetStream.Result); } ProcessLogEvent(logEvent, logFileName, new ArraySegment<byte>(targetStream.Result.GetBuffer(), 0, (int)targetStream.Result.Length)); } } /// <summary> /// Get full filename (=absolute) and cleaned if needed. /// </summary> /// <param name="logEvent"></param> /// <returns></returns> internal string GetFullFileName(LogEventInfo logEvent) { if (_fullFileName is null) return null; if (_fullFileName.IsFixedFilePath) return _fullFileName.Render(logEvent); using (var targetBuilder = ReusableLayoutBuilder.Allocate()) { return _fullFileName.RenderWithBuilder(logEvent, targetBuilder.Result); } } SortHelpers.KeySelector<AsyncLogEventInfo, string> _getFullFileNameDelegate; /// <summary> /// Writes the specified array of logging events to a file specified in the FileName /// parameter. /// </summary> /// <param name="logEvents">An array of <see cref="AsyncLogEventInfo"/> objects.</param> /// <remarks> /// This function makes use of the fact that the events are batched by sorting /// the requests by filename. This optimizes the number of open/close calls /// and can help improve performance. /// </remarks> protected override void Write(IList<AsyncLogEventInfo> logEvents) { if (_getFullFileNameDelegate is null) _getFullFileNameDelegate = c => GetFullFileName(c.LogEvent); var buckets = logEvents.BucketSort(_getFullFileNameDelegate); using (var reusableStream = _reusableAsyncFileWriteStream.Allocate()) { var ms = reusableStream.Result ?? new MemoryStream(); foreach (var bucket in buckets) { int bucketCount = bucket.Value.Count; if (bucketCount <= 0) continue; string fileName = bucket.Key; if (string.IsNullOrEmpty(fileName)) { InternalLogger.Warn("{0}: FileName Layout returned empty string. The path is not of a legal form.", this); var emptyPathException = new ArgumentException("The path is not of a legal form."); for (int i = 0; i < bucketCount; ++i) { bucket.Value[i].Continuation(emptyPathException); } continue; } int currentIndex = 0; while (currentIndex < bucketCount) { ms.Position = 0; ms.SetLength(0); var written = WriteToMemoryStream(bucket.Value, currentIndex, ms); AppendMemoryStreamToFile(fileName, bucket.Value[currentIndex].LogEvent, ms, out var lastException); for (int i = 0; i < written; ++i) { bucket.Value[currentIndex++].Continuation(lastException); } } } } } private int WriteToMemoryStream(IList<AsyncLogEventInfo> logEvents, int startIndex, MemoryStream ms) { long maxBufferSize = BufferSize * 100; // Max Buffer Default = 30 KiloByte * 100 = 3 MegaByte using (var targetStream = _reusableFileWriteStream.Allocate()) using (var targetBuilder = ReusableLayoutBuilder.Allocate()) using (var targetBuffer = _reusableEncodingBuffer.Allocate()) { var formatBuilder = targetBuilder.Result; var transformBuffer = targetBuffer.Result; var encodingStream = targetStream.Result; for (int i = startIndex; i < logEvents.Count; ++i) { // For some CPU's then it is faster to write to a small MemoryStream, and then copy to the larger one encodingStream.Position = 0; encodingStream.SetLength(0); formatBuilder.ClearBuilder(); AsyncLogEventInfo ev = logEvents[i]; RenderFormattedMessageToStream(ev.LogEvent, formatBuilder, transformBuffer, encodingStream); ms.Write(encodingStream.GetBuffer(), 0, (int)encodingStream.Length); if (ms.Length > maxBufferSize && !ReplaceFileContentsOnEachWrite) return i - startIndex + 1; // Max Chunk Size Limit to avoid out-of-memory issues } } return logEvents.Count - startIndex; } private void ProcessLogEvent(LogEventInfo logEvent, string fileName, ArraySegment<byte> bytesToWrite) { DateTime previousLogEventTimestamp = InitializeFile(fileName, logEvent); bool initializedNewFile = previousLogEventTimestamp == DateTime.MinValue; if (initializedNewFile && fileName == _previousLogFileName && _previousLogEventTimestamp.HasValue) previousLogEventTimestamp = _previousLogEventTimestamp.Value; bool archiveOccurred = TryArchiveFile(fileName, logEvent, bytesToWrite.Count, previousLogEventTimestamp, initializedNewFile); if (archiveOccurred) initializedNewFile = InitializeFile(fileName, logEvent) == DateTime.MinValue || initializedNewFile; if (ReplaceFileContentsOnEachWrite) { ReplaceFileContent(fileName, bytesToWrite, true); } else { WriteToFile(fileName, bytesToWrite, initializedNewFile); } _previousLogFileName = fileName; _previousLogEventTimestamp = logEvent.TimeStamp; } /// <summary> /// Formats the log event for write. /// </summary> /// <param name="logEvent">The log event to be formatted.</param> /// <returns>A string representation of the log event.</returns> [Obsolete("No longer used and replaced by RenderFormattedMessage. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected virtual string GetFormattedMessage(LogEventInfo logEvent) { return Layout.Render(logEvent); } /// <summary> /// Gets the bytes to be written to the file. /// </summary> /// <param name="logEvent">Log event.</param> /// <returns>Array of bytes that are ready to be written.</returns> [Obsolete("No longer used and replaced by RenderFormattedMessage. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected virtual byte[] GetBytesToWrite(LogEventInfo logEvent) { string text = GetFormattedMessage(logEvent); int textBytesCount = Encoding.GetByteCount(text); int newLineBytesCount = Encoding.GetByteCount(NewLineChars); byte[] bytes = new byte[textBytesCount + newLineBytesCount]; Encoding.GetBytes(text, 0, text.Length, bytes, 0); Encoding.GetBytes(NewLineChars, 0, NewLineChars.Length, bytes, textBytesCount); return TransformBytes(bytes); } /// <summary> /// Modifies the specified byte array before it gets sent to a file. /// </summary> /// <param name="value">The byte array.</param> /// <returns>The modified byte array. The function can do the modification in-place.</returns> [Obsolete("No longer used and replaced by TransformStream. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected virtual byte[] TransformBytes(byte[] value) { return value; } /// <summary> /// Gets the bytes to be written to the file. /// </summary> /// <param name="logEvent">The log event to be formatted.</param> /// <param name="formatBuilder"><see cref="StringBuilder"/> to help format log event.</param> /// <param name="transformBuffer">Optional temporary char-array to help format log event.</param> /// <param name="streamTarget">Destination <see cref="MemoryStream"/> for the encoded result.</param> protected virtual void RenderFormattedMessageToStream(LogEventInfo logEvent, StringBuilder formatBuilder, char[] transformBuffer, MemoryStream streamTarget) { RenderFormattedMessage(logEvent, formatBuilder); formatBuilder.Append(NewLineChars); TransformBuilderToStream(logEvent, formatBuilder, transformBuffer, streamTarget); } /// <summary> /// Formats the log event for write. /// </summary> /// <param name="logEvent">The log event to be formatted.</param> /// <param name="target"><see cref="StringBuilder"/> for the result.</param> protected virtual void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { Layout.Render(logEvent, target); } private void TransformBuilderToStream(LogEventInfo logEvent, StringBuilder builder, char[] transformBuffer, MemoryStream workStream) { builder.CopyToStream(workStream, Encoding, transformBuffer); TransformStream(logEvent, workStream); } /// <summary> /// Modifies the specified byte array before it gets sent to a file. /// </summary> /// <param name="logEvent">The LogEvent being written</param> /// <param name="stream">The byte array.</param> protected virtual void TransformStream(LogEventInfo logEvent, MemoryStream stream) { } private void AppendMemoryStreamToFile(string currentFileName, LogEventInfo firstLogEvent, MemoryStream ms, out Exception lastException) { try { ArraySegment<byte> bytes = new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length); ProcessLogEvent(firstLogEvent, currentFileName, bytes); lastException = null; } catch (Exception exception) { if (ExceptionMustBeRethrown(exception)) { throw; } lastException = exception; } } /// <summary> /// Archives fileName to archiveFileName. /// </summary> /// <param name="fileName">File name to be archived.</param> /// <param name="archiveFileName">Name of the archive file.</param> private void ArchiveFile(string fileName, string archiveFileName) { string archiveFolderPath = Path.GetDirectoryName(archiveFileName); if (archiveFolderPath != null && !Directory.Exists(archiveFolderPath)) Directory.CreateDirectory(archiveFolderPath); if (string.Equals(fileName, archiveFileName, StringComparison.OrdinalIgnoreCase)) { InternalLogger.Info("{0}: Archiving {1} skipped as ArchiveFileName equals FileName", this, fileName); } else if (EnableArchiveFileCompression) { InternalLogger.Info("{0}: Archiving {1} to compressed {2}", this, fileName, archiveFileName); if (File.Exists(archiveFileName)) { InternalLogger.Warn("{0}: Failed archiving because compressed file already exists: {1}", this, archiveFileName); } else { ArchiveFileCompress(fileName, archiveFileName); } } else { InternalLogger.Info("{0}: Archiving {1} to {2}", this, fileName, archiveFileName); if (File.Exists(archiveFileName)) { ArchiveFileAppendExisting(fileName, archiveFileName); } else { ArchiveFileMove(fileName, archiveFileName); } } } private void ArchiveFileCompress(string fileName, string archiveFileName) { int fileCompressRetryCount = ConcurrentWrites ? ConcurrentWriteAttempts : 2; for (int i = 1; i <= fileCompressRetryCount; ++i) { try { if (FileCompressor is IArchiveFileCompressor archiveFileCompressor) { string entryName = (ArchiveNumbering != ArchiveNumberingMode.Rolling) ? (Path.GetFileNameWithoutExtension(archiveFileName) + Path.GetExtension(fileName)) : Path.GetFileName(fileName); archiveFileCompressor.CompressFile(fileName, archiveFileName, entryName); } else { FileCompressor.CompressFile(fileName, archiveFileName); } break; // Success } catch (DirectoryNotFoundException) { throw; // Skip retry when directory does not exist } catch (FileNotFoundException) { throw; // Skip retry when file does not exist } catch (IOException ex) { if (i == fileCompressRetryCount) throw; if (File.Exists(archiveFileName)) throw; int sleepTimeMs = i * 50; InternalLogger.Warn("{0}: Archiving Attempt #{1} to compress {2} to {3} failed - {4} {5}. Sleeping for {6}ms", this, i, fileName, archiveFileName, ex.GetType(), ex.Message, sleepTimeMs); AsyncHelpers.WaitForDelay(TimeSpan.FromMilliseconds(sleepTimeMs)); } } DeleteAndWaitForFileDelete(fileName); } private void ArchiveFileAppendExisting(string fileName, string archiveFileName) { //todo handle double footer InternalLogger.Info("{0}: Already exists, append to {1}", this, archiveFileName); //copy to archive file. var fileShare = FileShare.ReadWrite; if (EnableFileDelete) { fileShare |= FileShare.Delete; } using (FileStream fileStream = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, fileShare)) using (FileStream archiveFileStream = File.Open(archiveFileName, FileMode.Append)) { fileStream.CopyAndSkipBom(archiveFileStream, Encoding); //clear old content fileStream.SetLength(0); if (EnableFileDelete && !DeleteOldArchiveFile(fileName)) { // Attempt to delete file to reset File-Creation-Time (Delete under file-lock) fileShare &= ~FileShare.Delete; // Retry after having released file-lock } fileStream.Close(); // This flushes the content, too. #if !NET35 archiveFileStream.Flush(true); #else archiveFileStream.Flush(); #endif } if ((fileShare & FileShare.Delete) == FileShare.None) { DeleteOldArchiveFile(fileName); // Attempt to delete file to reset File-Creation-Time } } private void ArchiveFileMove(string fileName, string archiveFileName) { try { InternalLogger.Debug("{0}: Move file from '{1}' to '{2}'", this, fileName, archiveFileName); File.Move(fileName, archiveFileName); } catch (IOException ex) { if (IsSimpleKeepFileOpen) throw; // No need to retry, when only single process access if (!EnableFileDelete && KeepFileOpen) throw; // No need to retry when file delete has been disabled if (ConcurrentWrites && !MutexDetector.SupportsSharableMutex) throw; // No need to retry when not having a real archive mutex to protect us // It is possible to move a file while other processes has open file-handles. // Unless the other process is actively writing, then the file move might fail. // We are already holding the archive-mutex, so lets retry if things are stable InternalLogger.Warn(ex, "{0}: Archiving failed. Checking for retry move of {1} to {2}.", this, fileName, archiveFileName); if (!File.Exists(fileName) || File.Exists(archiveFileName)) throw; AsyncHelpers.WaitForDelay(TimeSpan.FromMilliseconds(50)); if (!File.Exists(fileName) || File.Exists(archiveFileName)) throw; InternalLogger.Debug("{0}: Archiving retrying move of {1} to {2}.", this, fileName, archiveFileName); File.Move(fileName, archiveFileName); } } private bool DeleteOldArchiveFile(string fileName) { try { InternalLogger.Info("{0}: Deleting old archive file: '{1}'.", this, fileName); CloseInvalidFileHandle(fileName); File.Delete(fileName); return true; } catch (DirectoryNotFoundException exception) { //never rethrow this, as this isn't an exceptional case. InternalLogger.Debug(exception, "{0}: Failed to delete old log file '{1}' as directory is missing.", this, fileName); return false; } catch (Exception exception) { InternalLogger.Warn(exception, "{0}: Failed to delete old archive file: '{1}'.", this, fileName); if (ExceptionMustBeRethrown(exception)) { throw; } return false; } } private void DeleteAndWaitForFileDelete(string fileName) { try { InternalLogger.Trace("{0}: Waiting for file delete of '{1}' for 12 sec", this, fileName); var originalFileCreationTime = (new FileInfo(fileName)).CreationTime; if (DeleteOldArchiveFile(fileName) && File.Exists(fileName)) { FileInfo currentFileInfo; for (int i = 0; i < 120; ++i) { AsyncHelpers.WaitForDelay(TimeSpan.FromMilliseconds(100)); currentFileInfo = new FileInfo(fileName); if (!currentFileInfo.Exists || currentFileInfo.CreationTime != originalFileCreationTime) return; } InternalLogger.Warn("{0}: Timeout while deleting old archive file: '{1}'.", this, fileName); } } catch (Exception exception) { InternalLogger.Warn(exception, "{0}: Failed to delete old archive file: '{1}'.", this, fileName); if (ExceptionMustBeRethrown(exception)) { throw; } } } /// <summary> /// Gets the correct formatting <see langword="String"/> to be used based on the value of <see /// cref="ArchiveEvery"/> for converting <see langword="DateTime"/> values which will be inserting into file /// names during archiving. /// /// This value will be computed only when a empty value or <see langword="null"/> is passed into <paramref name="defaultFormat"/> /// </summary> /// <param name="defaultFormat">Date format to used irrespectively of <see cref="ArchiveEvery"/> value.</param> /// <returns>Formatting <see langword="String"/> for dates.</returns> private string GetArchiveDateFormatString(string defaultFormat) { // If archiveDateFormat is not set in the config file, use a default // date format string based on the archive period. if (!string.IsNullOrEmpty(defaultFormat)) return defaultFormat; switch (ArchiveEvery) { case FileArchivePeriod.Year: return "yyyy"; case FileArchivePeriod.Month: return "yyyyMM"; case FileArchivePeriod.Hour: return "yyyyMMddHH"; case FileArchivePeriod.Minute: return "yyyyMMddHHmm"; default: return "yyyyMMdd"; // Also for Weekdays } } private DateTime? GetArchiveDate(string fileName, LogEventInfo logEvent, DateTime previousLogEventTimestamp) { // Using File LastModified to handle FileArchivePeriod.Month (where file creation time is one month ago) var fileLastModifiedUtc = _fileAppenderCache.GetFileLastWriteTimeUtc(fileName); InternalLogger.Trace("{0}: Calculating archive date. File-LastModifiedUtc: {1}; Previous LogEvent-TimeStamp: {2}", this, fileLastModifiedUtc, previousLogEventTimestamp); if (!fileLastModifiedUtc.HasValue) { if (previousLogEventTimestamp == DateTime.MinValue) { InternalLogger.Info("{0}: Unable to acquire useful timestamp to archive file: {1}", this, fileName); return null; } return previousLogEventTimestamp; } var lastWriteTimeSource = Time.TimeSource.Current.FromSystemTime(fileLastModifiedUtc.Value); if (previousLogEventTimestamp != DateTime.MinValue) { if (previousLogEventTimestamp > lastWriteTimeSource) { InternalLogger.Trace("{0}: Using previous LogEvent-TimeStamp {1}, because more recent than File-LastModified {2}", this, previousLogEventTimestamp, lastWriteTimeSource); return previousLogEventTimestamp; } if (PreviousLogOverlappedPeriod(logEvent, previousLogEventTimestamp, lastWriteTimeSource)) { InternalLogger.Trace("{0}: Using previous LogEvent-TimeStamp {1}, because archive period is overlapping with File-LastModified {2}", this, previousLogEventTimestamp, lastWriteTimeSource); return previousLogEventTimestamp; } if (!AutoFlush && IsSimpleKeepFileOpen && previousLogEventTimestamp < lastWriteTimeSource) { InternalLogger.Trace("{0}: Using previous LogEvent-TimeStamp {1}, because AutoFlush=false affects File-LastModified {2}", this, previousLogEventTimestamp, lastWriteTimeSource); return previousLogEventTimestamp; } } InternalLogger.Trace("{0}: Using last write time: {1}", this, lastWriteTimeSource); return lastWriteTimeSource; } private bool PreviousLogOverlappedPeriod(LogEventInfo logEvent, DateTime previousLogEventTimestamp, DateTime lastFileWrite) { string formatString = GetArchiveDateFormatString(string.Empty); string lastWriteTimeString = lastFileWrite.ToString(formatString, CultureInfo.InvariantCulture); string logEventTimeString = logEvent.TimeStamp.ToString(formatString, CultureInfo.InvariantCulture); if (lastWriteTimeString != logEventTimeString) return false; DateTime? periodAfterPreviousLogEventTime = CalculateNextArchiveEventTime(previousLogEventTimestamp); if (!periodAfterPreviousLogEventTime.HasValue) return false; string periodAfterPreviousLogEventTimeString = periodAfterPreviousLogEventTime.Value.ToString(formatString, CultureInfo.InvariantCulture); return lastWriteTimeString == periodAfterPreviousLogEventTimeString; } DateTime? CalculateNextArchiveEventTime(DateTime timestamp) { switch (ArchiveEvery) { case FileArchivePeriod.Year: return timestamp.AddYears(1); case FileArchivePeriod.Month: return timestamp.AddMonths(1); case FileArchivePeriod.Day: return timestamp.AddDays(1); case FileArchivePeriod.Hour: return timestamp.AddHours(1); case FileArchivePeriod.Minute: return timestamp.AddMinutes(1); case FileArchivePeriod.Sunday: return CalculateNextWeekday(timestamp, DayOfWeek.Sunday); case FileArchivePeriod.Monday: return CalculateNextWeekday(timestamp, DayOfWeek.Monday); case FileArchivePeriod.Tuesday: return CalculateNextWeekday(timestamp, DayOfWeek.Tuesday); case FileArchivePeriod.Wednesday: return CalculateNextWeekday(timestamp, DayOfWeek.Wednesday); case FileArchivePeriod.Thursday: return CalculateNextWeekday(timestamp, DayOfWeek.Thursday); case FileArchivePeriod.Friday: return CalculateNextWeekday(timestamp, DayOfWeek.Friday); case FileArchivePeriod.Saturday: return CalculateNextWeekday(timestamp, DayOfWeek.Saturday); default: return null; } } /// <summary> /// Calculate the DateTime of the requested day of the week. /// </summary> /// <param name="previousLogEventTimestamp">The DateTime of the previous log event.</param> /// <param name="dayOfWeek">The next occurring day of the week to return a DateTime for.</param> /// <returns>The DateTime of the next occurring dayOfWeek.</returns> /// <remarks>For example: if previousLogEventTimestamp is Thursday 2017-03-02 and dayOfWeek is Sunday, this will return /// Sunday 2017-03-05. If dayOfWeek is Thursday, this will return *next* Thursday 2017-03-09.</remarks> public static DateTime CalculateNextWeekday(DateTime previousLogEventTimestamp, DayOfWeek dayOfWeek) { // Shamelessly taken from https://stackoverflow.com/a/7611480/1354930 int start = (int)previousLogEventTimestamp.DayOfWeek; int target = (int)dayOfWeek; if (target <= start) target += 7; return previousLogEventTimestamp.AddDays(target - start); } /// <summary> /// Invokes the archiving process after determining when and which type of archiving is required. /// </summary> /// <param name="fileName">File name to be checked and archived.</param> /// <param name="eventInfo">Log event that the <see cref="FileTarget"/> instance is currently processing.</param> /// <param name="previousLogEventTimestamp">The DateTime of the previous log event for this file.</param> /// <param name="initializedNewFile">File has just been opened.</param> private void DoAutoArchive(string fileName, LogEventInfo eventInfo, DateTime previousLogEventTimestamp, bool initializedNewFile) { InternalLogger.Debug("{0}: Do archive file: '{1}'", this, fileName); var fileInfo = new FileInfo(fileName); if (!fileInfo.Exists) { CloseInvalidFileHandle(fileName); // Close possible stale file handles return; } string archiveFilePattern = GetArchiveFileNamePattern(fileName, eventInfo); if (string.IsNullOrEmpty(archiveFilePattern)) { InternalLogger.Warn("{0}: Skip auto archive because archiveFilePattern is blank", this); return; } DateTime? archiveDate = GetArchiveDate(fileName, eventInfo, previousLogEventTimestamp); var archiveFileName = GenerateArchiveFileNameAfterCleanup(fileName, fileInfo, archiveFilePattern, archiveDate, initializedNewFile); if (!string.IsNullOrEmpty(archiveFileName)) { ArchiveFile(fileInfo.FullName, archiveFileName); } } private string GenerateArchiveFileNameAfterCleanup(string fileName, FileInfo fileInfo, string archiveFilePattern, DateTime? archiveDate, bool initializedNewFile) { InternalLogger.Trace("{0}: Archive pattern '{1}'", this, archiveFilePattern); var fileArchiveStyle = GetFileArchiveHelper(archiveFilePattern); var existingArchiveFiles = fileArchiveStyle.GetExistingArchiveFiles(archiveFilePattern); if (MaxArchiveFiles == 1) { InternalLogger.Trace("{0}: MaxArchiveFiles = 1", this); // Perform archive cleanup before generating the next filename, // as next archive-filename can be affected by existing files. for (int i = existingArchiveFiles.Count - 1; i >= 0; i--) { var oldArchiveFile = existingArchiveFiles[i]; if (!string.Equals(oldArchiveFile.FileName, fileInfo.FullName, StringComparison.OrdinalIgnoreCase)) { DeleteOldArchiveFile(oldArchiveFile.FileName); existingArchiveFiles.RemoveAt(i); } } if (initializedNewFile && string.Equals(Path.GetDirectoryName(archiveFilePattern), fileInfo.DirectoryName, StringComparison.OrdinalIgnoreCase)) { DeleteOldArchiveFile(fileName); return null; } } var archiveFileName = archiveDate.HasValue ? fileArchiveStyle.GenerateArchiveFileName(archiveFilePattern, archiveDate.Value, existingArchiveFiles) : null; if (archiveFileName is null) return null; if (!initializedNewFile) { FinalizeFile(fileName, isArchiving: true); } if (existingArchiveFiles.Count > 0) { CleanupOldArchiveFiles(fileInfo, archiveFilePattern, existingArchiveFiles, archiveFileName); } return archiveFileName.FileName; } private void CleanupOldArchiveFiles(FileInfo currentFile, string archiveFilePattern, List<DateAndSequenceArchive> existingArchiveFiles, DateAndSequenceArchive newArchiveFile = null) { var fileArchiveStyle = GetFileArchiveHelper(archiveFilePattern); if (fileArchiveStyle.IsArchiveCleanupEnabled) { if (currentFile != null) ExcludeActiveFileFromOldArchiveFiles(currentFile, existingArchiveFiles); if (newArchiveFile != null) existingArchiveFiles.Add(newArchiveFile); var cleanupArchiveFiles = fileArchiveStyle.CheckArchiveCleanup(archiveFilePattern, existingArchiveFiles, MaxArchiveFiles, MaxArchiveDays); foreach (var oldArchiveFile in cleanupArchiveFiles) { DeleteOldArchiveFile(oldArchiveFile.FileName); } } } private static void ExcludeActiveFileFromOldArchiveFiles(FileInfo currentFile, List<DateAndSequenceArchive> existingArchiveFiles) { if (existingArchiveFiles.Count > 0) { var archiveDirectory = Path.GetDirectoryName(existingArchiveFiles[0].FileName); if (string.Equals(archiveDirectory, currentFile.DirectoryName, StringComparison.OrdinalIgnoreCase)) { // Extra handling when archive-directory is the same as logging-directory for (int i = 0; i < existingArchiveFiles.Count; ++i) { if (string.Equals(existingArchiveFiles[i].FileName, currentFile.FullName, StringComparison.OrdinalIgnoreCase)) { existingArchiveFiles.RemoveAt(i); break; } } } } } /// <summary> /// Gets the pattern that archive files will match /// </summary> /// <param name="fileName">Filename of the log file</param> /// <param name="eventInfo">Log event that the <see cref="FileTarget"/> instance is currently processing.</param> /// <returns>A string with a pattern that will match the archive filenames</returns> private string GetArchiveFileNamePattern(string fileName, LogEventInfo eventInfo) { if (_fullArchiveFileName is null) { if (EnableArchiveFileCompression) return Path.ChangeExtension(fileName, ".zip"); else return fileName; } else { //The archive file name is given. There are two possibilities //(1) User supplied the Filename with pattern //(2) User supplied the normal filename string archiveFileName = _fullArchiveFileName.Render(eventInfo); return archiveFileName; } } /// <summary> /// Archives the file if it should be archived. /// </summary> /// <param name="fileName">The file name to check for.</param> /// <param name="ev">Log event that the <see cref="FileTarget"/> instance is currently processing.</param> /// <param name="upcomingWriteSize">The size in bytes of the next chunk of data to be written in the file.</param> /// <param name="previousLogEventTimestamp">The DateTime of the previous log event for this file.</param> /// <param name="initializedNewFile">File has just been opened.</param> /// <returns>True when archive operation of the file was completed (by this target or a concurrent target)</returns> private bool TryArchiveFile(string fileName, LogEventInfo ev, int upcomingWriteSize, DateTime previousLogEventTimestamp, bool initializedNewFile) { if (!IsArchivingEnabled) return false; string archiveFile = string.Empty; BaseFileAppender archivedAppender = null; try { archiveFile = GetArchiveFileName(fileName, ev, upcomingWriteSize, previousLogEventTimestamp, initializedNewFile); if (!string.IsNullOrEmpty(archiveFile)) { archivedAppender = TryCloseFileAppenderBeforeArchive(fileName, archiveFile); } #if !NETSTANDARD1_3 // Closes all file handles if any archive operation has been detected by file-watcher _fileAppenderCache.InvalidateAppendersForArchivedFiles(); #endif } catch (Exception exception) { InternalLogger.Warn(exception, "{0}: Failed to check archive for file '{1}'.", this, fileName); if (ExceptionMustBeRethrown(exception)) { throw; } } if (string.IsNullOrEmpty(archiveFile)) return false; try { #if SupportsMutex try { if (archivedAppender is BaseMutexFileAppender mutexFileAppender && mutexFileAppender.ArchiveMutex != null) { mutexFileAppender.ArchiveMutex.WaitOne(); } else if (!IsSimpleKeepFileOpen) { InternalLogger.Debug("{0}: Archive mutex not available for file '{1}'", this, archiveFile); } } catch (AbandonedMutexException) { // ignore the exception, another process was killed without properly releasing the mutex // the mutex has been acquired, so proceed to writing // See: https://msdn.microsoft.com/en-us/library/system.threading.abandonedmutexexception.aspx } #endif ArchiveFileAfterCloseFileAppender(archivedAppender, archiveFile, ev, upcomingWriteSize, previousLogEventTimestamp); return true; } finally { #if SupportsMutex if (archivedAppender is BaseMutexFileAppender mutexFileAppender) mutexFileAppender.ArchiveMutex?.ReleaseMutex(); #endif archivedAppender?.Dispose(); // Dispose of Archive Mutex } } /// <summary> /// Closes any active file-appenders that matches the input filenames. /// File-appender is requested to invalidate/close its filehandle, but keeping its archive-mutex alive /// </summary> private BaseFileAppender TryCloseFileAppenderBeforeArchive(string fileName, string archiveFile) { InternalLogger.Trace("{0}: Archive attempt for file '{1}'", this, archiveFile); BaseFileAppender archivedAppender = _fileAppenderCache.InvalidateAppender(fileName); if (fileName != archiveFile) { var fileAppender = _fileAppenderCache.InvalidateAppender(archiveFile); archivedAppender = archivedAppender ?? fileAppender; } if (!string.IsNullOrEmpty(_previousLogFileName) && _previousLogFileName != archiveFile && _previousLogFileName != fileName) { var fileAppender = _fileAppenderCache.InvalidateAppender(_previousLogFileName); archivedAppender = archivedAppender ?? fileAppender; } return archivedAppender; } private void ArchiveFileAfterCloseFileAppender(BaseFileAppender archivedAppender, string archiveFile, LogEventInfo ev, int upcomingWriteSize, DateTime previousLogEventTimestamp) { try { DateTime fallbackFileCreationTimeSource = previousLogEventTimestamp; if (archivedAppender != null && IsSimpleKeepFileOpen) { var fileCreationTimeUtc = archivedAppender.GetFileCreationTimeUtc(); if (fileCreationTimeUtc > DateTime.MinValue) { var fileCreationTimeSource = Time.TimeSource.Current.FromSystemTime(fileCreationTimeUtc.Value); if (fileCreationTimeSource < fallbackFileCreationTimeSource || fallbackFileCreationTimeSource == DateTime.MinValue) { fallbackFileCreationTimeSource = fileCreationTimeSource; } } } // Check again if archive is needed. We could have been raced by another process var validatedArchiveFile = GetArchiveFileName(archiveFile, ev, upcomingWriteSize, fallbackFileCreationTimeSource, false); if (string.IsNullOrEmpty(validatedArchiveFile)) { InternalLogger.Debug("{0}: Skip archiving '{1}' because no longer necessary", this, archiveFile); _initializedFiles.Remove(archiveFile); } else { if (archiveFile != validatedArchiveFile) { _initializedFiles.Remove(archiveFile); archiveFile = validatedArchiveFile; } _initializedFiles.Remove(archiveFile); DoAutoArchive(archiveFile, ev, previousLogEventTimestamp, false); } if (_previousLogFileName == archiveFile) { _previousLogFileName = null; _previousLogEventTimestamp = null; } } catch (Exception exception) { InternalLogger.Warn(exception, "{0}: Failed to archive file '{1}'.", this, archiveFile); if (ExceptionMustBeRethrown(exception)) { throw; } } } /// <summary> /// Indicates if the automatic archiving process should be executed. /// </summary> /// <param name="fileName">File name to be written.</param> /// <param name="ev">Log event that the <see cref="FileTarget"/> instance is currently processing.</param> /// <param name="upcomingWriteSize">The size in bytes of the next chunk of data to be written in the file.</param> /// <param name="previousLogEventTimestamp">The DateTime of the previous log event for this file.</param> /// <param name="initializedNewFile">File has just been opened.</param> /// <returns>Filename to archive. If <c>null</c>, then nothing to archive.</returns> private string GetArchiveFileName(string fileName, LogEventInfo ev, int upcomingWriteSize, DateTime previousLogEventTimestamp, bool initializedNewFile) { fileName = fileName ?? _previousLogFileName; if (!string.IsNullOrEmpty(fileName)) { return GetArchiveFileNameBasedOnFileSize(fileName, upcomingWriteSize, initializedNewFile) ?? GetArchiveFileNameBasedOnTime(fileName, ev, previousLogEventTimestamp, initializedNewFile); } return null; } /// <summary> /// Returns the correct filename to archive /// </summary> private string GetPotentialFileForArchiving(string fileName) { if (!string.IsNullOrEmpty(fileName)) { return fileName; } if (!string.IsNullOrEmpty(_previousLogFileName)) { return _previousLogFileName; } return fileName; } /// <summary> /// Gets the file name for archiving, or null if archiving should not occur based on file size. /// </summary> /// <param name="fileName">File name to be written.</param> /// <param name="upcomingWriteSize">The size in bytes of the next chunk of data to be written in the file.</param> /// <param name="initializedNewFile">File has just been opened.</param> /// <returns>Filename to archive. If <c>null</c>, then nothing to archive.</returns> private string GetArchiveFileNameBasedOnFileSize(string fileName, int upcomingWriteSize, bool initializedNewFile) { if (ArchiveAboveSize == ArchiveAboveSizeDisabled) { return null; } var archiveFileName = GetPotentialFileForArchiving(fileName); if (string.IsNullOrEmpty(archiveFileName)) { return null; } //this is an expensive call var fileLength = _fileAppenderCache.GetFileLength(archiveFileName); if (!fileLength.HasValue) { archiveFileName = TryFallbackToPreviousLogFileName(archiveFileName, initializedNewFile); if (!string.IsNullOrEmpty(archiveFileName)) { upcomingWriteSize = 0; return GetArchiveFileNameBasedOnFileSize(archiveFileName, upcomingWriteSize, false); } else { return null; } } if (archiveFileName != fileName) { upcomingWriteSize = 0; // Not going to write to this file } var shouldArchive = (fileLength.Value + upcomingWriteSize) > ArchiveAboveSize; if (shouldArchive) { InternalLogger.Debug("{0}: Start archiving '{1}' because FileSize={2} + {3} is larger than ArchiveAboveSize={4}", this, archiveFileName, fileLength.Value, upcomingWriteSize, ArchiveAboveSize); return archiveFileName; // Will re-check if archive is still necessary after flush/close file } return null; } /// <summary> /// Check if archive operation should check previous filename, because FileAppenderCache tells us current filename no longer exists /// </summary> private string TryFallbackToPreviousLogFileName(string archiveFileName, bool initializedNewFile) { if (!initializedNewFile && _initializedFiles.Remove(archiveFileName)) { // Register current filename needs re-initialization InternalLogger.Debug("{0}: Invalidate appender as archive file no longer exists: '{1}'", this, archiveFileName); _fileAppenderCache.InvalidateAppender(archiveFileName)?.Dispose(); } if (!string.IsNullOrEmpty(_previousLogFileName) && !string.Equals(archiveFileName, _previousLogFileName, StringComparison.OrdinalIgnoreCase)) { return _previousLogFileName; } return string.Empty; } /// <summary> /// Returns the file name for archiving, or null if archiving should not occur based on date/time. /// </summary> /// <param name="fileName">File name to be written.</param> /// <param name="logEvent">Log event that the <see cref="FileTarget"/> instance is currently processing.</param> /// <param name="previousLogEventTimestamp">The DateTime of the previous log event for this file.</param> /// <param name="initializedNewFile">File has just been opened.</param> /// <returns>Filename to archive. If <c>null</c>, then nothing to archive.</returns> private string GetArchiveFileNameBasedOnTime(string fileName, LogEventInfo logEvent, DateTime previousLogEventTimestamp, bool initializedNewFile) { if (ArchiveEvery == FileArchivePeriod.None) { return null; } var archiveFileName = GetPotentialFileForArchiving(fileName); if (string.IsNullOrEmpty(archiveFileName)) { return null; } DateTime? creationTimeSource = TryGetArchiveFileCreationTimeSource(archiveFileName, previousLogEventTimestamp); if (!creationTimeSource.HasValue) { archiveFileName = TryFallbackToPreviousLogFileName(archiveFileName, initializedNewFile); if (!string.IsNullOrEmpty(archiveFileName)) { return GetArchiveFileNameBasedOnTime(archiveFileName, logEvent, previousLogEventTimestamp, false); } else { return null; } } DateTime fileCreateTime = TruncateArchiveTime(creationTimeSource.Value, ArchiveEvery); DateTime logEventTime = TruncateArchiveTime(logEvent.TimeStamp, ArchiveEvery); if (fileCreateTime != logEventTime) { string formatString = GetArchiveDateFormatString(string.Empty); var validLogEventTime = EnsureValidLogEventTimeStamp(logEvent.TimeStamp, creationTimeSource.Value); string fileCreated = creationTimeSource.Value.ToString(formatString, CultureInfo.InvariantCulture); string logEventRecorded = validLogEventTime.ToString(formatString, CultureInfo.InvariantCulture); var shouldArchive = fileCreated != logEventRecorded; if (shouldArchive) { InternalLogger.Debug("{0}: Start archiving '{1}' because FileCreatedTime='{2}' is older than now '{3}' using ArchiveEvery='{4}'", this, archiveFileName, fileCreated, logEventRecorded, formatString); return archiveFileName; // Will re-check if archive is still necessary after flush/close file } } return null; } private DateTime? TryGetArchiveFileCreationTimeSource(string fileName, DateTime previousLogEventTimestamp) { // Linux FileSystems doesn't always have file-birth-time, so NLog tries to provide a little help DateTime? fallbackTimeSourceLinux = (previousLogEventTimestamp != DateTime.MinValue && IsSimpleKeepFileOpen) ? previousLogEventTimestamp : (DateTime?)null; var creationTimeSource = _fileAppenderCache.GetFileCreationTimeSource(fileName, fallbackTimeSourceLinux); if (!creationTimeSource.HasValue) return null; if (previousLogEventTimestamp > DateTime.MinValue && previousLogEventTimestamp < creationTimeSource) { if (TruncateArchiveTime(previousLogEventTimestamp, FileArchivePeriod.Minute) < TruncateArchiveTime(creationTimeSource.Value, FileArchivePeriod.Minute) && PlatformDetector.IsUnix) { if (IsSimpleKeepFileOpen) { InternalLogger.Debug("{0}: Adjusted file creation time from {1} to {2}. Linux FileSystem probably don't support file birthtime.", this, creationTimeSource, previousLogEventTimestamp); creationTimeSource = previousLogEventTimestamp; } else { InternalLogger.Debug("{0}: File creation time {1} newer than previous file write time {2}. Linux FileSystem probably don't support file birthtime, unless multiple applications are writing to the same file. Configure FileTarget.KeepFileOpen=true AND FileTarget.ConcurrentWrites=false, so NLog can fix this.", this, creationTimeSource, previousLogEventTimestamp); } } } return creationTimeSource; } /// <summary> /// Truncates the input-time, so comparison of low resolution times (like dates) are not affected by ticks /// </summary> /// <param name="input">High resolution Time</param> /// <param name="resolution">Time Resolution Level</param> /// <returns>Truncated Low Resolution Time</returns> private static DateTime TruncateArchiveTime(DateTime input, FileArchivePeriod resolution) { switch (resolution) { case FileArchivePeriod.Year: return new DateTime(input.Year, 1, 1, 0, 0, 0, 0, input.Kind); case FileArchivePeriod.Month: return new DateTime(input.Year, input.Month, 1, 0, 0, 0, input.Kind); case FileArchivePeriod.Day: return input.Date; case FileArchivePeriod.Hour: return input.AddTicks(-(input.Ticks % TimeSpan.TicksPerHour)); case FileArchivePeriod.Minute: return input.AddTicks(-(input.Ticks % TimeSpan.TicksPerMinute)); case FileArchivePeriod.Sunday: return CalculateNextWeekday(input.Date, DayOfWeek.Sunday); case FileArchivePeriod.Monday: return CalculateNextWeekday(input.Date, DayOfWeek.Monday); case FileArchivePeriod.Tuesday: return CalculateNextWeekday(input.Date, DayOfWeek.Tuesday); case FileArchivePeriod.Wednesday: return CalculateNextWeekday(input.Date, DayOfWeek.Wednesday); case FileArchivePeriod.Thursday: return CalculateNextWeekday(input.Date, DayOfWeek.Thursday); case FileArchivePeriod.Friday: return CalculateNextWeekday(input.Date, DayOfWeek.Friday); case FileArchivePeriod.Saturday: return CalculateNextWeekday(input.Date, DayOfWeek.Saturday); default: return input; // Unknown time-resolution-truncate, leave unchanged } } private void AutoCloseAppendersAfterArchive(object sender, EventArgs state) { bool lockTaken = Monitor.TryEnter(SyncRoot, TimeSpan.FromSeconds(2)); if (!lockTaken) return; // Archive events triggered by FileWatcher are important, but not life critical try { if (!IsInitialized) { return; } InternalLogger.Trace("{0}: Auto Close FileAppenders after archive", this); _fileAppenderCache.CloseExpiredAppenders(DateTime.MinValue); } catch (Exception exception) { #if DEBUG if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } #endif InternalLogger.Warn(exception, "{0}: Exception in AutoCloseAppendersAfterArchive", this); } finally { Monitor.Exit(SyncRoot); } } private void AutoClosingTimerCallback(object sender, EventArgs state) { bool lockTaken = Monitor.TryEnter(SyncRoot, TimeSpan.FromSeconds(0.5)); if (!lockTaken) return; // Timer will trigger again, no need for timers to queue up try { if (!IsInitialized) { return; } if (OpenFileCacheTimeout > 0) { DateTime expireTimeUtc = DateTime.UtcNow.AddSeconds(-OpenFileCacheTimeout); InternalLogger.Trace("{0}: Auto Close FileAppenders", this); _fileAppenderCache.CloseExpiredAppenders(expireTimeUtc); } if (OpenFileFlushTimeout > 0 && !AutoFlush) { ConditionalFlushOpenFileAppenders(); } } catch (Exception exception) { #if DEBUG if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } #endif InternalLogger.Warn(exception, "{0}: Exception in AutoClosingTimerCallback", this); } finally { Monitor.Exit(SyncRoot); } } private void ConditionalFlushOpenFileAppenders() { DateTime flushTime = Time.TimeSource.Current.Time.AddSeconds(-Math.Max(OpenFileFlushTimeout, 5) * 2); bool flushAppenders = false; foreach (var file in _initializedFiles) { if (file.Value > flushTime) { flushAppenders = true; break; } } if (flushAppenders) { // Only request flush of file-handles, when something has been written InternalLogger.Trace("{0}: Auto Flush FileAppenders", this); _fileAppenderCache.FlushAppenders(); } } /// <summary> /// Evaluates which parts of a file should be written (header, content, footer) based on various properties of /// <see cref="FileTarget"/> instance and writes them. /// </summary> /// <param name="fileName">File name to be written.</param> /// <param name="bytes">Raw sequence of <see langword="byte"/> to be written into the content part of the file.</param> /// <param name="initializedNewFile">File has just been opened.</param> private void WriteToFile(string fileName, ArraySegment<byte> bytes, bool initializedNewFile) { BaseFileAppender appender = _fileAppenderCache.AllocateAppender(fileName); try { if (initializedNewFile) { WriteHeaderAndBom(appender); } appender.Write(bytes.Array, bytes.Offset, bytes.Count); if (AutoFlush) { appender.Flush(); } } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed write to file '{1}'.", this, fileName); _fileAppenderCache.InvalidateAppender(fileName)?.Dispose(); throw; } } /// <summary> /// Initialize a file to be used by the <see cref="FileTarget"/> instance. Based on the number of initialized /// files and the values of various instance properties clean up and/or archiving processes can be invoked. /// </summary> /// <param name="fileName">File name to be written.</param> /// <param name="logEvent">Log event that the <see cref="FileTarget"/> instance is currently processing.</param> /// <returns>The DateTime of the previous log event for this file (DateTime.MinValue if just initialized).</returns> private DateTime InitializeFile(string fileName, LogEventInfo logEvent) { if (_initializedFiles.Count != 0 && logEvent.TimeStamp == _previousLogEventTimestamp && _previousLogFileName == fileName) { return logEvent.TimeStamp; } var now = logEvent.TimeStamp; if (!_initializedFiles.TryGetValue(fileName, out var lastTime)) { PrepareForNewFile(fileName, logEvent); _initializedFilesCounter++; if (_initializedFilesCounter > OpenFileCacheSize) { // Attempt to write footer, before closing file appender _initializedFilesCounter = 0; CleanupInitializedFiles(); _initializedFilesCounter = Math.Min(_initializedFiles.Count, OpenFileCacheSize / 2); } _initializedFiles[fileName] = now; return DateTime.MinValue; } else if (lastTime != now) { now = EnsureValidLogEventTimeStamp(now, lastTime); _initializedFiles[fileName] = now; } return lastTime; } private static DateTime EnsureValidLogEventTimeStamp(DateTime logEventTimeStamp, DateTime previousTimeStamp) { // Truncating using DateTime.Date is "expensive", so first check if it look like it is from the past if (logEventTimeStamp < previousTimeStamp && logEventTimeStamp.Date < previousTimeStamp.Date) { // Received LogEvent from the past when comparing to the previous timestamp var currentTime = TimeSource.Current.Time; if (logEventTimeStamp.Date < currentTime.AddMinutes(-1).Date) { // It is not because the machine-time has changed. Probably a LogEvent from the past if (currentTime.Date < previousTimeStamp.Date) return currentTime; // Previous timestamp is from the future. We choose machine-time else return previousTimeStamp; } } return logEventTimeStamp; } private void CloseInvalidFileHandle(string fileName) { try { _fileAppenderCache.InvalidateAppender(fileName)?.Dispose(); } finally { _initializedFiles.Remove(fileName); // Skip finalize non-existing file } } /// <summary> /// Writes the file footer and finalizes the file in <see cref="FileTarget"/> instance internal structures. /// </summary> /// <param name="fileName">File name to close.</param> /// <param name="isArchiving">Indicates if the file is being finalized for archiving.</param> private void FinalizeFile(string fileName, bool isArchiving = false) { try { InternalLogger.Trace("{0}: FinalizeFile '{1}, isArchiving: {2}'", this, fileName, isArchiving); if ((isArchiving) || (!WriteFooterOnArchivingOnly)) WriteFooter(fileName); } finally { CloseInvalidFileHandle(fileName); } } /// <summary> /// Writes the footer information to a file. /// </summary> /// <param name="fileName">The file path to write to.</param> private void WriteFooter(string fileName) { ArraySegment<byte> footerBytes = GetLayoutBytes(Footer); if (footerBytes.Count > 0 && File.Exists(fileName)) { WriteToFile(fileName, footerBytes, false); } } /// <summary> /// Decision logic whether to archive logfile on startup. /// <see cref="ArchiveOldFileOnStartup"/> and <see cref="ArchiveOldFileOnStartupAboveSize"/> properties. /// </summary> /// <param name="fileName">File name to be written.</param> /// <returns>Decision whether to archive or not.</returns> internal bool ShouldArchiveOldFileOnStartup(string fileName) { if (_archiveOldFileOnStartup == false) { // explicitly disabled and not the default return false; } var aboveSizeSet = ArchiveOldFileOnStartupAboveSize > 0; if (aboveSizeSet) { // Check whether size threshold exceeded var length = _fileAppenderCache.GetFileLength(fileName); return length.HasValue && length.Value > ArchiveOldFileOnStartupAboveSize; } // No size threshold specified, use archiveOldFileOnStartup flag return _archiveOldFileOnStartup == true; } /// <summary> /// Invokes the archiving and clean up of older archive file based on the values of /// <see cref="NLog.Targets.FileTarget.ArchiveOldFileOnStartup"/> and /// <see cref="NLog.Targets.FileTarget.DeleteOldFileOnStartup"/> properties respectively. /// </summary> /// <param name="fileName">File name to be written.</param> /// <param name="logEvent">Log event that the <see cref="FileTarget"/> instance is currently processing.</param> private void PrepareForNewFile(string fileName, LogEventInfo logEvent) { InternalLogger.Debug("{0}: Preparing for new file: '{1}'", this, fileName); RefreshArchiveFilePatternToWatch(fileName, logEvent); try { if (ShouldArchiveOldFileOnStartup(fileName)) { DoAutoArchive(fileName, logEvent, DateTime.MinValue, true); } } catch (Exception exception) { InternalLogger.Warn(exception, "{0}: Unable to archive old log file '{1}'.", this, fileName); if (ExceptionMustBeRethrown(exception)) { throw; } } if (DeleteOldFileOnStartup) { DeleteOldArchiveFile(fileName); } try { string archiveFilePattern = GetArchiveFileNamePattern(fileName, logEvent); if (!string.IsNullOrEmpty(archiveFilePattern)) { var fileArchiveStyle = GetFileArchiveHelper(archiveFilePattern); if (fileArchiveStyle.AttemptCleanupOnInitializeFile(archiveFilePattern, MaxArchiveFiles, MaxArchiveDays)) { var existingArchiveFiles = fileArchiveStyle.GetExistingArchiveFiles(archiveFilePattern); if (existingArchiveFiles.Count > 0) { CleanupOldArchiveFiles(new FileInfo(fileName), archiveFilePattern, existingArchiveFiles); } } } } catch (Exception exception) { InternalLogger.Warn(exception, "FileTarget(Name={0}): Failed to cleanup old archive files when starting on new file: '{1}'", Name, fileName); if (ExceptionMustBeRethrown(exception)) { throw; } } } /// <summary> /// Creates the file specified in <paramref name="fileName"/> and writes the file content in each entirety i.e. /// Header, Content and Footer. /// </summary> /// <param name="fileName">The name of the file to be written.</param> /// <param name="bytes">Sequence of <see langword="byte"/> to be written in the content section of the file.</param> /// <param name="firstAttempt">First attempt to write?</param> /// <remarks>This method is used when the content of the log file is re-written on every write.</remarks> private void ReplaceFileContent(string fileName, ArraySegment<byte> bytes, bool firstAttempt) { try { using (FileStream fs = File.Create(fileName)) { ArraySegment<byte> headerBytes = GetLayoutBytes(Header); if (headerBytes.Count > 0) { fs.Write(headerBytes.Array, headerBytes.Offset, headerBytes.Count); } fs.Write(bytes.Array, bytes.Offset, bytes.Count); ArraySegment<byte> footerBytes = GetLayoutBytes(Footer); if (footerBytes.Count > 0) { fs.Write(footerBytes.Array, footerBytes.Offset, footerBytes.Count); } } } catch (DirectoryNotFoundException) { if (!CreateDirs || !firstAttempt) { throw; } Directory.CreateDirectory(Path.GetDirectoryName(fileName)); //retry. ReplaceFileContent(fileName, bytes, false); } } private static bool InitialValueBom(Encoding encoding) { // Initial of true for UTF 16 and UTF 32 const int utf16 = 1200; const int utf16Be = 1201; const int utf32 = 12000; const int urf32Be = 12001; var codePage = encoding?.CodePage ?? 0; return codePage == utf16 || codePage == utf16Be || codePage == utf32 || codePage == urf32Be; } /// <summary> /// Writes the header information and byte order mark to a file. /// </summary> /// <param name="appender">File appender associated with the file.</param> private void WriteHeaderAndBom(BaseFileAppender appender) { //performance: cheap check before checking file info if (Header is null && !WriteBom) return; var length = appender.GetFileLength(); // Write header and BOM only on empty files or if file info cannot be obtained. if (length is null || length == 0) { if (WriteBom) { InternalLogger.Trace("{0}: Write byte order mark from encoding={1}", this, Encoding); var preamble = Encoding.GetPreamble(); if (preamble.Length > 0) appender.Write(preamble, 0, preamble.Length); } if (Header != null) { InternalLogger.Trace("{0}: Write header", this); ArraySegment<byte> headerBytes = GetLayoutBytes(Header); if (headerBytes.Count > 0) { appender.Write(headerBytes.Array, headerBytes.Offset, headerBytes.Count); } } } } /// <summary> /// The sequence of <see langword="byte"/> to be written in a file after applying any formatting and any /// transformations required from the <see cref="Layout"/>. /// </summary> /// <param name="layout">The layout used to render output message.</param> /// <returns>Sequence of <see langword="byte"/> to be written.</returns> /// <remarks>Usually it is used to render the header and hooter of the files.</remarks> private ArraySegment<byte> GetLayoutBytes(Layout layout) { if (layout is null) { return default(ArraySegment<byte>); } using (var targetBuilder = ReusableLayoutBuilder.Allocate()) using (var targetBuffer = _reusableEncodingBuffer.Allocate()) { var nullEvent = LogEventInfo.CreateNullEvent(); layout.Render(nullEvent, targetBuilder.Result); targetBuilder.Result.Append(NewLineChars); using (MemoryStream ms = new MemoryStream(targetBuilder.Result.Length)) { TransformBuilderToStream(nullEvent, targetBuilder.Result, targetBuffer.Result, ms); return new ArraySegment<byte>(ms.ToArray()); } } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.MessageTemplates { using System; using NLog.MessageTemplates; using Xunit; public class ParserTests { private static object[] ManyParameters = new object[100]; [Theory] [InlineData("", 0)] [InlineData("Hello {0}", 1)] [InlineData("I like my {car}", 1)] [InlineData("But when Im drunk I need a {cool} bike", 1)] [InlineData("I have {0} {1} {2} parameters", 3)] [InlineData("{0} on front", 1)] [InlineData(" {0} on front", 1)] [InlineData("end {1}", 1)] [InlineData("end {1} ", 1)] [InlineData("{name} is my name", 1)] [InlineData(" {name} is my name", 1)] [InlineData("{multiple}{parameters}", 2)] [InlineData("I have {{text}} and {{0}}", 0)] [InlineData("{{text}}{{0}}", 0)] [InlineData(" {{text}}{{0}} ", 0)] [InlineData(" {0} ", 1)] [InlineData(" {1} ", 1)] [InlineData(" {2} ", 1)] [InlineData(" {3} {4} {9} {8} {5} {6} {7}", 7)] [InlineData(" {{ ", 0)] [InlineData("{{ ", 0)] [InlineData(" {{", 0)] [InlineData(" }} ", 0)] [InlineData("}} ", 0)] [InlineData(" }}", 0)] [InlineData("{0:000}", 1)] [InlineData("{aaa:000}", 1)] [InlineData(" {@serialize} ", 1)] [InlineData(" {$stringify} ", 1)] [InlineData(" {alignment,-10} ", 1)] [InlineData(" {alignment,10} ", 1)] [InlineData(" {0,10} ", 1)] [InlineData(" {0,-10} ", 1)] [InlineData(" {0,-10:test} ", 1)] [InlineData("{{{0:d}}}", 1)] [InlineData("{{{0:0{{}", 1)] public void ParseAndPrint(string input, int parameterCount) { var logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, input, ManyParameters); logEventInfo.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null); var templateAuto = logEventInfo.MessageTemplateParameters; Assert.Equal(parameterCount, templateAuto.Count); } [Theory] [InlineData("{0}", 0, null)] [InlineData("{001}", 1, null)] [InlineData("{9}", 9, null)] [InlineData("{1 }", 1, null)] [InlineData("{1} {2}", 1, null)] [InlineData("{@3} {$4}", 3, null)] [InlineData("{3,6}", 3, null)] [InlineData("{5:R}", 5, "R")] [InlineData("{0:0}", 0, "0")] public void ParsePositional(string input, int index, string format) { var logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, input, ManyParameters); logEventInfo.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null); var template = logEventInfo.MessageTemplateParameters; Assert.True(template.IsPositional); Assert.True(template.Count >= 1); Assert.Equal(format, template[0].Format); Assert.Equal(index, template[0].PositionalIndex); } [Theory] [InlineData("{ 0}")] [InlineData("{-1}")] [InlineData("{1.2}")] [InlineData("{42r}")] [InlineData("{6} {x}")] [InlineData("{a} {x}")] public void ParseNominal(string input) { var logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, input, ManyParameters); logEventInfo.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null); var template = logEventInfo.MessageTemplateParameters; Assert.False(template.IsPositional); } [Theory] [InlineData("{hello}", "hello")] [InlineData("{@hello}", "hello")] [InlineData("{$hello}", "hello")] [InlineData("{#hello}", "#hello")] [InlineData("{ spaces ,-3}", " spaces ")] [InlineData("{special!:G})", "special!")] [InlineData("{noescape_in_name}}}", "noescape_in_name")] [InlineData("{noescape_in_name{{}", "noescape_in_name{{")] [InlineData("{0}", "0")] [InlineData("{18 }", "18 ")] public void ParseName(string input, string name) { var logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, input, ManyParameters); logEventInfo.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null); var template = logEventInfo.MessageTemplateParameters; Assert.Equal(1, template.Count); Assert.Equal(name, template[0].Name); } [Theory] [InlineData("{aaa}", "")] [InlineData("{@a}", "@")] [InlineData("{@A}", "@")] [InlineData("{@8}", "@")] [InlineData("{@aaa}", "@")] [InlineData("{$a}", "$")] [InlineData("{$A}", "$")] [InlineData("{$9}", "$")] [InlineData("{$aaa}", "$")] public void ParseHoleType(string input, string holeType) { var logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, input, ManyParameters); logEventInfo.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null); var template = logEventInfo.MessageTemplateParameters; Assert.Equal(1, template.Count); CaptureType captureType = CaptureType.Normal; if (holeType == "@") captureType = CaptureType.Serialize; else if (holeType == "$") captureType = CaptureType.Stringify; Assert.Equal(captureType, template[0].CaptureType); } [Theory] [InlineData(" {0,-10:nl-nl} ", -10, "nl-nl")] [InlineData(" {0,-10} ", -10, null)] [InlineData("{0, 36 }", 36, null)] [InlineData("{0,-36 :x}", -36, "x")] [InlineData(" {0:nl-nl} ", 0, "nl-nl")] [InlineData(" {0} ", 0, null)] public void ParseFormatAndAlignment_numeric(string input, int? alignment, string format) { var logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, input, ManyParameters); logEventInfo.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null); var template = logEventInfo.MessageTemplateParameters; Assert.Equal(1, template.Count); var hole = template[0]; Assert.Equal("0", hole.Name); Assert.Equal(0, hole.PositionalIndex); Assert.Equal(format, hole.Format); Assert.NotNull(alignment); } [Theory] [InlineData(" {car,-10:nl-nl} ", -10, "nl-nl")] [InlineData(" {car,-10} ", -10, null)] [InlineData(" {car:nl-nl} ", 0, "nl-nl")] [InlineData(" {car} ", 0, null)] public void ParseFormatAndAlignment_text(string input, int? alignment, string format) { var logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, input, ManyParameters); logEventInfo.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null); var template = logEventInfo.MessageTemplateParameters; Assert.Equal(1, template.Count); var hole = template[0]; Assert.False(template.IsPositional); Assert.Equal("car", hole.Name); Assert.Equal(format, hole.Format); Assert.NotNull(alignment); } [Theory] [InlineData("Hello {0")] [InlineData("Hello 0}")] [InlineData("Hello {a:")] [InlineData("Hello {a")] [InlineData("Hello {a,")] [InlineData("Hello {a,1")] [InlineData("{")] [InlineData("}")] [InlineData("}}}")] [InlineData("}}}{")] [InlineData("{}}{")] [InlineData("{a,-3.5}")] [InlineData("{a,2x}")] [InlineData("{a,--2}")] [InlineData("{a,-2")] [InlineData("{a,-2 :N0")] [InlineData("{a,-2.0")] [InlineData("{a,:N0}")] [InlineData("{a,}")] [InlineData("{a,{}")] [InlineData("{a:{}")] [InlineData("{a,d{e}")] [InlineData("{a:d{e}")] public void ThrowsTemplateParserException(string input) { Assert.Throws<TemplateParserException>(() => { var logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, input, ManyParameters); logEventInfo.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null); var template = logEventInfo.MessageTemplateParameters; }); } } } <file_sep>using NLog; using NLog.Targets; class Example { static void Main(string[] args) { DatabaseTarget target = new DatabaseTarget(); DatabaseParameterInfo param; target.DBProvider = "oledb"; target.ConnectionString = "Provider=msdaora;Data Source=MYORACLEDB;User Id=DBO;Password=<PASSWORD>;"; target.CommandText = "insert into LOGTABLE( TIME_STAMP,LOGLEVEL,LOGGER,CALLSITE,MESSAGE) values(?,?,?,?,?)"; target.Parameters.Add(new DatabaseParameterInfo("TIME_STAMP", "${longdate}")); target.Parameters.Add(new DatabaseParameterInfo("LOGLEVEL", "${level:uppercase=true}")); target.Parameters.Add(new DatabaseParameterInfo("LOGGER", "${logger}")); target.Parameters.Add(new DatabaseParameterInfo("CALLSITE", "${callsite:filename=true}")); target.Parameters.Add(new DatabaseParameterInfo("MESSAGE", "${message}")); NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.IO; using System.Net; using NSubstitute; namespace NLog.UnitTests.Mocks { [Obsolete("WebRequest is obsolete. Use HttpClient instead.")] public sealed class WebRequestMock : WebRequest, IDisposable { public Uri RequestedAddress { get; set; } public bool FirstRequestMustFail { get; set; } public MemoryStream RequestStream => _requestStream; private readonly ManualDisposableMemoryStream _requestStream = new ManualDisposableMemoryStream(); /// <inheritdoc/> public WebRequestMock() { } /// <inheritdoc/> public override WebResponse EndGetResponse(IAsyncResult asyncResult) { if (FirstRequestMustFail) { FirstRequestMustFail = false; RequestStream.Position = 0; RequestStream.SetLength(0); System.Threading.Thread.Sleep(50); throw new InvalidDataException("You are doomed"); } var responseStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("new response 1")); var webResponseMock = Substitute.For<WebResponse>(); webResponseMock.GetResponseStream().Returns(responseStream); return webResponseMock; } /// <inheritdoc/> public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) { var result = CreateAsyncResultMock(state); System.Threading.Tasks.Task.Run(() => callback(result)); return result; } /// <inheritdoc/> public override Stream EndGetRequestStream(IAsyncResult asyncResult) { return RequestStream; } /// <inheritdoc/> public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) { var result = CreateAsyncResultMock(state); callback(result); return result; } /// <inheritdoc/> public override string Method { get; set; } public string GetRequestContentAsString() { var content = RequestStream.ToArray(); var contentAsString = System.Text.Encoding.UTF8.GetString(content); return contentAsString; } private static IAsyncResult CreateAsyncResultMock(object state) { var asyncResult = Substitute.For<IAsyncResult>(); asyncResult.AsyncState.Returns(state); return asyncResult; } /// <inheritdoc/> public void Dispose() { _requestStream?.RealDispose(); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using NLog.Common; using NLog.Config; using NLog.Internal; /// <summary> /// The base class for all targets which call methods (local or remote). /// Manages parameters and type coercion. /// </summary> public abstract class MethodCallTargetBase : Target { /// <summary> /// Initializes a new instance of the <see cref="MethodCallTargetBase" /> class. /// </summary> protected MethodCallTargetBase() { Parameters = new List<MethodCallParameter>(); } /// <summary> /// Gets the array of parameters to be passed. /// </summary> /// <docgen category='Layout Options' order='10' /> [ArrayParameter(typeof(MethodCallParameter), "parameter")] public IList<MethodCallParameter> Parameters { get; private set; } /// <summary> /// Prepares an array of parameters to be passed based on the logging event and calls DoInvoke(). /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(AsyncLogEventInfo logEvent) { object[] parameters = Parameters.Count > 0 ? new object[Parameters.Count] : ArrayHelper.Empty<object>(); for (int i = 0; i < parameters.Length; ++i) { try { parameters[i] = GetParameterValue(logEvent.LogEvent, Parameters[i]); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; InternalLogger.Warn(ex, "{0}: Failed to get parameter value {1}", this, Parameters[i].Name); throw; } } DoInvoke(parameters, logEvent); } private object GetParameterValue(LogEventInfo logEvent, MethodCallParameter param) { return param.RenderValue(logEvent); } /// <summary> /// Calls the target DoInvoke method, and handles AsyncContinuation callback /// </summary> /// <param name="parameters">Method call parameters.</param> /// <param name="logEvent">The logging event.</param> protected virtual void DoInvoke(object[] parameters, AsyncLogEventInfo logEvent) { DoInvoke(parameters, logEvent.Continuation); } /// <summary> /// Calls the target DoInvoke method, and handles AsyncContinuation callback /// </summary> /// <param name="parameters">Method call parameters.</param> /// <param name="continuation">The continuation.</param> protected virtual void DoInvoke(object[] parameters, AsyncContinuation continuation) { try { DoInvoke(parameters); continuation(null); } catch (Exception ex) { if (ExceptionMustBeRethrown(ex)) { throw; } continuation(ex); } } /// <summary> /// Calls the target method. Must be implemented in concrete classes. /// </summary> /// <param name="parameters">Method call parameters.</param> protected abstract void DoInvoke(object[] parameters); } } <file_sep>using System; using NLog; using NLog.Targets; using NLog.Targets.Wrappers; using System.Diagnostics; class Example { static void Main(string[] args) { FileTarget wrappedTarget = new FileTarget(); wrappedTarget.FileName = "${basedir}/file.txt"; RepeatingTargetWrapper target = new RepeatingTargetWrapper(); target.WrappedTarget = wrappedTarget; target.RepeatCount = 3; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); } } <file_sep>namespace MergeApiXml { using System; using System.IO; using System.Linq; class Program { static int Main(string[] args) { try { string releaseDir = args[0]; string outputDir = Path.Combine(releaseDir, "Website"); Directory.CreateDirectory(outputDir); string outputFile = Path.Combine(releaseDir, "NLogMerged.api.xml"); var merger = new NLogApiMerger(); merger.AddRelease("1.0", @"\\MASTER\lab\NLog\1.0\Release"); merger.AddRelease("2.0", releaseDir); merger.Merge(); // remove properties which have been removed in NLog 2.0 foreach (var prop in merger.Result.Root.Descendants("property") .Where(c => c.Element("supported-in").Elements("release").All(e => (string)e.Attribute("name") != "2.0")) .ToList()) { prop.Remove(); }; Console.WriteLine("Saving {0}...", outputFile); merger.Result.Save(outputFile); return 0; } catch (Exception ex) { Console.WriteLine("ERROR: {0}", ex); return 1; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 namespace NLog.Config { using System; using System.Linq; using System.Threading; using NLog.Common; using NLog.Internal; using NLog.Internal.Fakeables; /// <summary> /// Enables FileWatcher for the currently loaded NLog Configuration File, /// and supports automatic reload on file modification. /// </summary> internal class LoggingConfigurationWatchableFileLoader : LoggingConfigurationFileLoader { private const int ReconfigAfterFileChangedTimeout = 1000; private readonly object _lockObject = new object(); private Timer _reloadTimer; private MultiFileWatcher _watcher; private bool _isDisposing; private LogFactory _logFactory; public LoggingConfigurationWatchableFileLoader(IAppEnvironment appEnvironment) :base(appEnvironment) { } public override LoggingConfiguration Load(LogFactory logFactory, string filename = null) { #if !NETSTANDARD if (string.IsNullOrEmpty(filename)) { var config = TryLoadFromAppConfig(); if (config != null) return config; } #endif return base.Load(logFactory, filename); } public override void Activated(LogFactory logFactory, LoggingConfiguration config) { _logFactory = logFactory; TryUnwatchConfigFile(); if (config != null) { TryWachtingConfigFile(config); } } protected override void Dispose(bool disposing) { if (disposing) { _isDisposing = true; if (_watcher != null) { // Disable startup of new reload-timers _watcher.FileChanged -= ConfigFileChanged; _watcher.StopWatching(); } var currentTimer = _reloadTimer; if (currentTimer != null) { _reloadTimer = null; currentTimer.WaitForDispose(TimeSpan.Zero); } // Dispose file-watcher after having dispose timer to avoid race _watcher?.Dispose(); } base.Dispose(disposing); } #if !NETSTANDARD private LoggingConfiguration TryLoadFromAppConfig() { try { // Try to load default configuration. return XmlLoggingConfiguration.AppConfig; } catch (Exception ex) { //loading could fail due to an invalid XML file (app.config) etc. if (ex.MustBeRethrown()) { throw; } return null; } } #endif internal void ReloadConfigOnTimer(object state) { if (_reloadTimer is null && _isDisposing) { return; //timer was disposed already. } LoggingConfiguration oldConfig = (LoggingConfiguration)state; InternalLogger.Info("Reloading configuration..."); lock (_lockObject) { if (_isDisposing) { return; //timer was disposed already. } var currentTimer = _reloadTimer; if (currentTimer != null) { _reloadTimer = null; currentTimer.WaitForDispose(TimeSpan.Zero); } } lock (_logFactory._syncRoot) { LoggingConfiguration newConfig; try { if (!ReferenceEquals(_logFactory._config, oldConfig)) { InternalLogger.Warn("NLog Config changed in between. Not reloading."); return; } newConfig = oldConfig.Reload(); if (ReferenceEquals(newConfig, oldConfig)) return; if (newConfig is IInitializeSucceeded config2 && config2.InitializeSucceeded != true) { InternalLogger.Warn("NLog Config Reload() failed. Invalid XML?"); return; } } catch (Exception exception) { #if DEBUG if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } #endif InternalLogger.Warn(exception, "NLog configuration failed to reload"); #pragma warning disable CS0618 // Type or member is obsolete _logFactory?.NotifyConfigurationReloaded(new LoggingConfigurationReloadedEventArgs(false, exception)); #pragma warning restore CS0618 // Type or member is obsolete return; } try { TryUnwatchConfigFile(); _logFactory.Configuration = newConfig; // Triggers LogFactory to call Activated(...) that adds file-watch again #pragma warning disable CS0618 // Type or member is obsolete _logFactory?.NotifyConfigurationReloaded(new LoggingConfigurationReloadedEventArgs(true)); #pragma warning restore CS0618 // Type or member is obsolete } catch (Exception exception) { #if DEBUG if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } #endif InternalLogger.Warn(exception, "NLog configuration reloaded, failed to be assigned"); _watcher.Watch(oldConfig.FileNamesToWatch); #pragma warning disable CS0618 // Type or member is obsolete _logFactory?.NotifyConfigurationReloaded(new LoggingConfigurationReloadedEventArgs(false, exception)); #pragma warning restore CS0618 // Type or member is obsolete } } } private void ConfigFileChanged(object sender, EventArgs args) { InternalLogger.Info("Configuration file change detected! Reloading in {0}ms...", ReconfigAfterFileChangedTimeout); // In the rare cases we may get multiple notifications here, // but we need to reload config only once. // // The trick is to schedule the reload in one second after // the last change notification comes in. lock (_lockObject) { if (_isDisposing) { return; } if (_reloadTimer is null) { var configuration = _logFactory._config; if (configuration != null) { _reloadTimer = new Timer( ReloadConfigOnTimer, configuration, ReconfigAfterFileChangedTimeout, Timeout.Infinite); } } else { _reloadTimer.Change( ReconfigAfterFileChangedTimeout, Timeout.Infinite); } } } private void TryWachtingConfigFile(LoggingConfiguration config) { try { var fileNamesToWatch = config.FileNamesToWatch?.ToList(); if (fileNamesToWatch?.Count > 0) { if (_watcher is null) { _watcher = new MultiFileWatcher(); _watcher.FileChanged += ConfigFileChanged; } _watcher.Watch(fileNamesToWatch); } } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } //ToArray needed for .Net 3.5 InternalLogger.Warn(exception, "Cannot start file watching: {0}", string.Join(",", _logFactory._config.FileNamesToWatch.ToArray())); } } private void TryUnwatchConfigFile() { try { _watcher?.StopWatching(); } catch (Exception exception) { InternalLogger.Error(exception, "Cannot stop file watching."); if (exception.MustBeRethrown()) { throw; } } } } } #endif <file_sep>using System; using System.Data; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; using System.ComponentModel; namespace WebService1 { [WebService(Namespace = "http://www.nlog-project.org/example")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] public class Service1 : System.Web.Services.WebService { [WebMethod] public void HelloWorld(string n1, string n2, string n3) { HttpContext.Current.Trace.Write("n1 " + n1); HttpContext.Current.Trace.Write("n2 " + n2); HttpContext.Current.Trace.Write("n3 " + n3); } } } <file_sep>using NLog; using NLog.Win32.Targets; class Example { static void Main(string[] args) { ColoredConsoleTarget target = new ColoredConsoleTarget(); target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule("log", ConsoleOutputColor.NoChange, ConsoleOutputColor.DarkGreen)); target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule("abc", ConsoleOutputColor.Cyan, ConsoleOutputColor.NoChange)); NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace); Logger logger = LogManager.GetLogger("Example"); logger.Trace("trace log message abcdefghijklmnopq"); logger.Debug("debug log message"); logger.Info("info log message abc abcdefghijklmnopq"); logger.Warn("warn log message"); logger.Error("error log abcdefghijklmnopq message abc"); logger.Fatal("fatal log message abcdefghijklmnopq abc"); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #define DEBUG // System.Diagnostics.Debug.WriteLine namespace NLog.Targets { /// <summary> /// Outputs log messages through <see cref="System.Diagnostics.Debug.WriteLine(string)" /> /// </summary> /// <remarks> /// <a href="https://github.com/NLog/NLog/wiki/DebugSystem-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/NLog/NLog/wiki/DebugSystem-target">Documentation on NLog Wiki</seealso> [Target("DebugSystem")] public sealed class DebugSystemTarget : TargetWithLayoutHeaderAndFooter { /// <summary> /// Initializes a new instance of the <see cref="DebugSystemTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> public DebugSystemTarget() : base() { } /// <summary> /// Initializes a new instance of the <see cref="DebugSystemTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> /// <param name="name">Name of the target.</param> public DebugSystemTarget(string name) : this() { Name = name; } /// <inheritdoc/> protected override void InitializeTarget() { base.InitializeTarget(); if (Header != null) { DebugWriteLine(RenderLogEvent(Header, LogEventInfo.CreateNullEvent())); } } /// <inheritdoc/> protected override void CloseTarget() { if (Footer != null) { DebugWriteLine(RenderLogEvent(Footer, LogEventInfo.CreateNullEvent())); } base.CloseTarget(); } /// <summary> /// Outputs the rendered logging event through <see cref="System.Diagnostics.Debug.WriteLine(string)" /> /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(LogEventInfo logEvent) { DebugWriteLine(RenderLogEvent(Layout, logEvent)); } private void DebugWriteLine(string message) { System.Diagnostics.Debug.WriteLine(message); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Globalization; using System.Linq; using NLog.Common; using NLog.Internal; namespace NLog.Config { internal static class LoggingConfigurationElementExtensions { public static bool MatchesName(this ILoggingConfigurationElement section, string expectedName) { return string.Equals(section?.Name?.Trim(), expectedName, StringComparison.OrdinalIgnoreCase); } public static void AssertName(this ILoggingConfigurationElement section, params string[] allowedNames) { foreach (var en in allowedNames) { if (section.MatchesName(en)) return; } throw new InvalidOperationException( $"Assertion failed. Expected element name '{string.Join("|", allowedNames)}', actual: '{section?.Name}'."); } public static string GetRequiredValue(this ILoggingConfigurationElement element, string attributeName, string section) { string value = element.GetOptionalValue(attributeName, null); if (value is null) { throw new NLogConfigurationException($"Expected {attributeName} on {element.Name} in {section}"); } if (StringHelpers.IsNullOrWhiteSpace(value)) { throw new NLogConfigurationException( $"Expected non-empty {attributeName} on {element.Name} in {section}"); } return value; } public static string GetOptionalValue(this ILoggingConfigurationElement element, string attributeName, string defaultValue) { return element.Values .Where(configItem => string.Equals(configItem.Key, attributeName, StringComparison.OrdinalIgnoreCase)) .Select(configItem => configItem.Value).FirstOrDefault() ?? defaultValue; } /// <summary> /// Gets the optional boolean attribute value. /// </summary> /// <param name="element"></param> /// <param name="attributeName">Name of the attribute.</param> /// <param name="defaultValue">Default value to return if the attribute is not found or if there is a parse error</param> /// <returns>Boolean attribute value or default.</returns> public static bool GetOptionalBooleanValue(this ILoggingConfigurationElement element, string attributeName, bool defaultValue) { string value = element.GetOptionalValue(attributeName, null); if (string.IsNullOrEmpty(value)) { return defaultValue; } try { return Convert.ToBoolean(value.Trim(), CultureInfo.InvariantCulture); } catch (Exception exception) { var configException = new NLogConfigurationException($"'{attributeName}' hasn't a valid boolean value '{value}'. {defaultValue} will be used", exception); if (configException.MustBeRethrown()) { throw configException; } InternalLogger.Error(exception, configException.Message); return defaultValue; } } public static string GetConfigItemTypeAttribute(this ILoggingConfigurationElement element, string sectionNameForRequiredValue = null) { var typeAttributeValue = sectionNameForRequiredValue != null ? element.GetRequiredValue("type", sectionNameForRequiredValue) : element.GetOptionalValue("type", null); return StripOptionalNamespacePrefix(typeAttributeValue)?.Trim(); } /// <summary> /// Remove the namespace (before :) /// </summary> /// <example> /// x:a, will be a /// </example> /// <param name="attributeValue"></param> /// <returns></returns> private static string StripOptionalNamespacePrefix(string attributeValue) { if (attributeValue is null) { return null; } int p = attributeValue.IndexOf(':'); if (p < 0) { return attributeValue; } return attributeValue.Substring(p + 1); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Globalization; using System.IO; using System.Text; using NLog.MessageTemplates; namespace NLog.Internal { /// <summary> /// Helpers for <see cref="StringBuilder"/>, which is used in e.g. layout renderers. /// </summary> internal static class StringBuilderExt { /// <summary> /// Renders the specified log event context item and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">append to this</param> /// <param name="value">value to be appended</param> /// <param name="format">format string. If @, then serialize the value with the Default JsonConverter.</param> /// <param name="formatProvider">provider, for example culture</param> /// <param name="valueFormatter">NLog string.Format interface</param> public static void AppendFormattedValue(this StringBuilder builder, object value, string format, IFormatProvider formatProvider, IValueFormatter valueFormatter) { string stringValue = value as string; if (stringValue != null && string.IsNullOrEmpty(format)) { builder.Append(value); // Avoid automatic quotes } else if (format == MessageTemplates.ValueFormatter.FormatAsJson) { valueFormatter.FormatValue(value, null, CaptureType.Serialize, formatProvider, builder); } else if (value != null) { valueFormatter.FormatValue(value, format, CaptureType.Normal, formatProvider, builder); } } /// <summary> /// Appends int without using culture, and most importantly without garbage /// </summary> /// <param name="builder"></param> /// <param name="value">value to append</param> public static void AppendInvariant(this StringBuilder builder, int value) { // Deal with negative numbers if (value < 0) { builder.Append('-'); uint uint_value = uint.MaxValue - ((uint)value) + 1; // NOSONAR: This is to deal with Int32.MinValue AppendInvariant(builder, uint_value); } else { AppendInvariant(builder, (uint)value); } } /// <summary> /// Appends uint without using culture, and most importantly without garbage /// /// Credits <NAME> - https://www.gavpugh.com/2010/04/01/xnac-avoiding-garbage-when-working-with-stringbuilder/ /// </summary> /// <param name="builder"></param> /// <param name="value">value to append</param> public static void AppendInvariant(this StringBuilder builder, uint value) { if (value == 0) { builder.Append('0'); return; } int digitCount = CalculateDigitCount(value); ApppendValueWithDigitCount(builder, value, digitCount); } private static int CalculateDigitCount(uint value) { // Calculate length of integer when written out int length = 0; uint length_calc = value; do { length_calc /= 10; length++; } while (length_calc > 0); return length; } private static void ApppendValueWithDigitCount(StringBuilder builder, uint value, int digitCount) { // Pad out space for writing. builder.Append('0', digitCount); int strpos = builder.Length; // We're writing backwards, one character at a time. while (digitCount > 0) { strpos--; // Lookup from static char array, to cover hex values too builder[strpos] = charToInt[value % 10]; value /= 10; digitCount--; } } private static readonly char[] charToInt = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; /// <summary> /// Convert DateTime into UTC and format to yyyy-MM-ddTHH:mm:ss.fffffffZ - ISO 8601 Compliant Date Format (Round-Trip-Time) /// </summary> public static void AppendXmlDateTimeUtcRoundTrip(this StringBuilder builder, DateTime dateTime) { if (dateTime.Kind == DateTimeKind.Unspecified) dateTime = new DateTime(dateTime.Ticks, DateTimeKind.Utc); else dateTime = dateTime.ToUniversalTime(); builder.Append4DigitsZeroPadded(dateTime.Year); builder.Append('-'); builder.Append2DigitsZeroPadded(dateTime.Month); builder.Append('-'); builder.Append2DigitsZeroPadded(dateTime.Day); builder.Append('T'); builder.Append2DigitsZeroPadded(dateTime.Hour); builder.Append(':'); builder.Append2DigitsZeroPadded(dateTime.Minute); builder.Append(':'); builder.Append2DigitsZeroPadded(dateTime.Second); int fraction = (int)(dateTime.Ticks % 10000000); if (fraction > 0) { builder.Append('.'); // Remove trailing zeros int max_digit_count = 7; while (fraction % 10 == 0) { --max_digit_count; fraction /= 10; } // Append the remaining fraction int digitCount = CalculateDigitCount((uint)fraction); if (max_digit_count > digitCount) builder.Append('0', max_digit_count - digitCount); ApppendValueWithDigitCount(builder, (uint)fraction, digitCount); } builder.Append('Z'); } /// <summary> /// Clears the provider StringBuilder /// </summary> /// <param name="builder"></param> public static void ClearBuilder(this StringBuilder builder) { try { #if !NET35 builder.Clear(); #else builder.Length = 0; #endif } catch { // Default StringBuilder Clear() can cause the StringBuilder to re-allocate new internal char-array // This can fail in low memory conditions when StringBuilder is big, so instead try to clear the StringBuilder "gently" if (builder.Length > 1) builder.Remove(0, builder.Length - 1); builder.Remove(0, builder.Length); } } /// <summary> /// Copies the contents of the StringBuilder to the MemoryStream using the specified encoding (Without BOM/Preamble) /// </summary> /// <param name="builder">StringBuilder source</param> /// <param name="ms">MemoryStream destination</param> /// <param name="encoding">Encoding used for converter string into byte-stream</param> /// <param name="transformBuffer">Helper char-buffer to minimize memory allocations</param> public static void CopyToStream(this StringBuilder builder, MemoryStream ms, Encoding encoding, char[] transformBuffer) { int charCount; int byteCount = encoding.GetMaxByteCount(builder.Length); long position = ms.Position; ms.SetLength(position + byteCount); for (int i = 0; i < builder.Length; i += transformBuffer.Length) { charCount = Math.Min(builder.Length - i, transformBuffer.Length); builder.CopyTo(i, transformBuffer, 0, charCount); byteCount = encoding.GetBytes(transformBuffer, 0, charCount, ms.GetBuffer(), (int)position); position += byteCount; } ms.Position = position; if (position != ms.Length) { ms.SetLength(position); } } public static void CopyToBuffer(this StringBuilder builder, char[] destination, int destinationIndex) { builder.CopyTo(0, destination, destinationIndex, builder.Length); } /// <summary> /// Copies the contents of the StringBuilder to the destination StringBuilder /// </summary> /// <param name="builder">StringBuilder source</param> /// <param name="destination">StringBuilder destination</param> public static void CopyTo(this StringBuilder builder, StringBuilder destination) { int sourceLength = builder.Length; if (sourceLength > 0) { destination.EnsureCapacity(sourceLength + destination.Length); if (sourceLength < 8) { // Skip char-buffer allocation for small strings for (int i = 0; i < sourceLength; ++i) destination.Append(builder[i]); } else if (sourceLength < 512) { // Single char-buffer allocation through string-object destination.Append(builder.ToString()); } else { // Reuse single char-buffer allocation for large StringBuilders char[] buffer = new char[256]; for (int i = 0; i < sourceLength; i += buffer.Length) { int charCount = Math.Min(sourceLength - i, buffer.Length); builder.CopyTo(i, buffer, 0, charCount); destination.Append(buffer, 0, charCount); } } } } /// <summary> /// Scans the StringBuilder for the position of needle character /// </summary> /// <param name="builder">StringBuilder source</param> /// <param name="needle">needle character to search for</param> /// <param name="startPos"></param> /// <returns>Index of the first occurrence (Else -1)</returns> public static int IndexOf(this StringBuilder builder, char needle, int startPos = 0) { var builderLength = builder.Length; for (int i = startPos; i < builderLength; ++i) if (builder[i] == needle) return i; return -1; } /// <summary> /// Scans the StringBuilder for the position of needle character /// </summary> /// <param name="builder">StringBuilder source</param> /// <param name="needles">needle characters to search for</param> /// <param name="startPos"></param> /// <returns>Index of the first occurrence (Else -1)</returns> public static int IndexOfAny(this StringBuilder builder, char[] needles, int startPos = 0) { var builderLength = builder.Length; for (int i = startPos; i < builderLength; ++i) if (CharArrayContains(builder[i], needles)) return i; return -1; } private static bool CharArrayContains(char searchChar, char[] needles) { for (int i = 0; i < needles.Length; ++i) { if (needles[i] == searchChar) return true; } return false; } /// <summary> /// Compares the contents of two StringBuilders /// </summary> /// <remarks> /// Correct implementation of <see cref="StringBuilder.Equals(StringBuilder)" /> that also works when <see cref="StringBuilder.Capacity"/> is not the same /// </remarks> /// <returns>True when content is the same</returns> public static bool EqualTo(this StringBuilder builder, StringBuilder other) { var builderLength = builder.Length; if (builderLength != other.Length) return false; for (int x = 0; x < builderLength; ++x) { if (builder[x] != other[x]) { return false; } } return true; } /// <summary> /// Compares the contents of a StringBuilder and a String /// </summary> /// <returns>True when content is the same</returns> public static bool EqualTo(this StringBuilder builder, string other) { if (builder.Length != other.Length) return false; for (int i = 0; i < other.Length; ++i) { if (builder[i] != other[i]) return false; } return true; } /// <summary> /// Append a number and pad with 0 to 2 digits /// </summary> /// <param name="builder">append to this</param> /// <param name="number">the number</param> internal static void Append2DigitsZeroPadded(this StringBuilder builder, int number) { builder.Append((char)((number / 10) + '0')); builder.Append((char)((number % 10) + '0')); } /// <summary> /// Append a number and pad with 0 to 4 digits /// </summary> /// <param name="builder">append to this</param> /// <param name="number">the number</param> internal static void Append4DigitsZeroPadded(this StringBuilder builder, int number) { builder.Append((char)(((number / 1000) % 10) + '0')); builder.Append((char)(((number / 100) % 10) + '0')); builder.Append((char)(((number / 10) % 10) + '0')); builder.Append((char)(((number / 1) % 10) + '0')); } /// <summary> /// Append a numeric type (byte, int, double, decimal) as string /// </summary> internal static void AppendNumericInvariant(this StringBuilder sb, IConvertible value, TypeCode objTypeCode) { switch (objTypeCode) { case TypeCode.Byte: sb.AppendInvariant(value.ToByte(CultureInfo.InvariantCulture)); break; case TypeCode.SByte: sb.AppendInvariant(value.ToSByte(CultureInfo.InvariantCulture)); break; case TypeCode.Int16: sb.AppendInvariant(value.ToInt16(CultureInfo.InvariantCulture)); break; case TypeCode.Int32: sb.AppendInvariant(value.ToInt32(CultureInfo.InvariantCulture)); break; case TypeCode.Int64: { long int64 = value.ToInt64(CultureInfo.InvariantCulture); if (int64 < int.MaxValue && int64 > int.MinValue) sb.AppendInvariant((int)int64); else sb.Append(int64); } break; case TypeCode.UInt16: sb.AppendInvariant(value.ToUInt16(CultureInfo.InvariantCulture)); break; case TypeCode.UInt32: sb.AppendInvariant(value.ToUInt32(CultureInfo.InvariantCulture)); break; case TypeCode.UInt64: { ulong uint64 = value.ToUInt64(CultureInfo.InvariantCulture); if (uint64 < uint.MaxValue) sb.AppendInvariant((uint)uint64); else sb.Append(uint64); } break; case TypeCode.Single: { float floatValue = value.ToSingle(CultureInfo.InvariantCulture); #if NETSTANDARD if (!float.IsNaN(floatValue) && !float.IsInfinity(floatValue) && value is IFormattable formattable) { AppendDecimalInvariant(sb, formattable, "{0:R}"); } else #endif { AppendFloatInvariant(sb, floatValue); } } break; case TypeCode.Double: { double doubleValue = value.ToDouble(CultureInfo.InvariantCulture); #if NETSTANDARD if (!double.IsNaN(doubleValue) && !double.IsInfinity(doubleValue) && value is IFormattable formattable) { AppendDecimalInvariant(sb, formattable, "{0:R}"); } else #endif { AppendDoubleInvariant(sb, doubleValue); } } break; case TypeCode.Decimal: { #if NETSTANDARD if (value is IFormattable formattable) { AppendDecimalInvariant(sb, formattable, "{0}"); } else #endif { AppendDecimalInvariant(sb, value.ToDecimal(CultureInfo.InvariantCulture)); } } break; default: sb.Append(XmlHelper.XmlConvertToString(value, objTypeCode)); break; } } #if NETSTANDARD private static void AppendDecimalInvariant(StringBuilder sb, IFormattable formattable, string format) { int orgLength = sb.Length; sb.AppendFormat(CultureInfo.InvariantCulture, format, formattable); // Support ISpanFormattable for (int i = sb.Length - 1; i > orgLength; --i) { if (!char.IsDigit(sb[i])) return; } sb.Append('.'); sb.Append('0'); } #endif private static void AppendDecimalInvariant(StringBuilder sb, decimal decimalValue) { if (Math.Truncate(decimalValue) == decimalValue && decimalValue > int.MinValue && decimalValue < int.MaxValue) { sb.AppendInvariant(Convert.ToInt32(decimalValue)); sb.Append(".0"); } else { sb.Append(XmlHelper.XmlConvertToString(decimalValue)); } } private static void AppendDoubleInvariant(StringBuilder sb, double doubleValue) { if (double.IsNaN(doubleValue) || double.IsInfinity(doubleValue)) { sb.Append(XmlHelper.XmlConvertToString(doubleValue)); } else if (Math.Truncate(doubleValue) == doubleValue && doubleValue > int.MinValue && doubleValue < int.MaxValue) { sb.AppendInvariant(Convert.ToInt32(doubleValue)); sb.Append(".0"); } else { sb.Append(XmlHelper.XmlConvertToString(doubleValue)); } } private static void AppendFloatInvariant(StringBuilder sb, float floatValue) { if (float.IsNaN(floatValue) || float.IsInfinity(floatValue)) { sb.Append(XmlHelper.XmlConvertToString(floatValue)); } else if (Math.Truncate(floatValue) == floatValue && floatValue > int.MinValue && floatValue < int.MaxValue) { sb.AppendInvariant(Convert.ToInt32(floatValue)); sb.Append(".0"); } else { sb.Append(XmlHelper.XmlConvertToString(floatValue)); } } public static void TrimRight(this StringBuilder sb, int startPos = 0) { int i = sb.Length - 1; for (; i >= startPos; i--) if (!char.IsWhiteSpace(sb[i])) break; if (i < sb.Length - 1) sb.Length = i + 1; } } } <file_sep>To open this example in VS2005 you need to get "Visual Studio 2005 Web Application Projects" component available at: https://msdn.microsoft.com/asp.net/reference/infrastructure/wap/default.aspx <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.ComponentModel; using JetBrains.Annotations; /// <summary> /// Logger with only generic methods (passing 'LogLevel' to methods) and core properties. /// </summary> public partial interface ILoggerBase { /// <summary> /// Occurs when logger configuration changes. /// </summary> event EventHandler<EventArgs> LoggerReconfigured; /// <summary> /// Gets the name of the logger. /// </summary> string Name { get; } /// <summary> /// Gets the factory that created this logger. /// </summary> LogFactory Factory { get; } /// <summary> /// Gets a value indicating whether logging is enabled for the specified level. /// </summary> /// <param name="level">Log level to be checked.</param> /// <returns>A value of <see langword="true" /> if logging is enabled for the specified level, otherwise it returns <see langword="false" />.</returns> bool IsEnabled(LogLevel level); #region Log() overloads /// <summary> /// Writes the specified diagnostic message. /// </summary> /// <param name="logEvent">Log event.</param> void Log(LogEventInfo logEvent); /// <summary> /// Writes the specified diagnostic message. /// </summary> /// <param name="wrapperType">Type of custom Logger wrapper.</param> /// <param name="logEvent">Log event.</param> void Log(Type wrapperType, LogEventInfo logEvent); /// <overloads> /// Writes the diagnostic message at the specified level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="level">The log level.</param> /// <param name="value">The value to be written.</param> void Log<T>(LogLevel level, T value); /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> void Log<T>(LogLevel level, IFormatProvider formatProvider, T value); /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> void Log(LogLevel level, LogMessageGenerator messageFunc); /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args) instead. Marked obsolete with v4.3.11")] [EditorBrowsable(EditorBrowsableState.Never)] void LogException(LogLevel level, [Localizable(false)] string message, Exception exception); /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> /// <param name="exception">An exception to be logged.</param> [MessageTemplateFormatMethod("message")] void Log(LogLevel level, Exception exception, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args); /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> /// <param name="exception">An exception to be logged.</param> [MessageTemplateFormatMethod("message")] void Log(LogLevel level, Exception exception, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters and formatting them with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args); /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">Log message.</param> void Log(LogLevel level, [Localizable(false)] string message); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args); /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args) instead. Marked obsolete with v4.3.11")] [EditorBrowsable(EditorBrowsableState.Never)] void Log(LogLevel level, [Localizable(false)] string message, Exception exception); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameter and formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] void Log<TArgument>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument argument); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameter. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] void Log<TArgument>(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, TArgument argument); /// <summary> /// Writes the diagnostic message at the specified level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] void Log<TArgument1, TArgument2>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] void Log<TArgument1, TArgument2>(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2); /// <summary> /// Writes the diagnostic message at the specified level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] void Log<TArgument1, TArgument2, TArgument3>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] void Log<TArgument1, TArgument2, TArgument3>(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3); #endregion } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using System; using System.Collections.Generic; using NLog.Common; using NLog.Conditions; using NLog.Config; using NLog.Internal; /// <summary> /// Filters buffered log entries based on a set of conditions that are evaluated on a group of events. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/PostFilteringWrapper-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/PostFilteringWrapper-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// This example works like this. If there are no Warn,Error or Fatal messages in the buffer /// only Info messages are written to the file, but if there are any warnings or errors, /// the output includes detailed trace (levels &gt;= Debug). /// </p> /// <p> /// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/PostFilteringWrapper/NLog.config" /> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/PostFilteringWrapper/Simple/Example.cs" /> /// </example> [Target("PostFilteringWrapper", IsWrapper = true)] public class PostFilteringTargetWrapper : WrapperTargetBase { /// <summary> /// Initializes a new instance of the <see cref="PostFilteringTargetWrapper" /> class. /// </summary> public PostFilteringTargetWrapper() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="PostFilteringTargetWrapper" /> class. /// </summary> public PostFilteringTargetWrapper(Target wrappedTarget) : this(string.IsNullOrEmpty(wrappedTarget?.Name) ? null : (wrappedTarget.Name + "_wrapped"), wrappedTarget) { } /// <summary> /// Initializes a new instance of the <see cref="PostFilteringTargetWrapper" /> class. /// </summary> /// <param name="name">Name of the target.</param> /// <param name="wrappedTarget">The wrapped target.</param> public PostFilteringTargetWrapper(string name, Target wrappedTarget) { Name = name ?? Name; WrappedTarget = wrappedTarget; } /// <summary> /// Gets or sets the default filter to be applied when no specific rule matches. /// </summary> /// <docgen category='Filtering Options' order='10' /> public ConditionExpression DefaultFilter { get; set; } /// <summary> /// Gets the collection of filtering rules. The rules are processed top-down /// and the first rule that matches determines the filtering condition to /// be applied to log events. /// </summary> /// <docgen category='Filtering Rules' order='10' /> [ArrayParameter(typeof(FilteringRule), "when")] public IList<FilteringRule> Rules { get; } = new List<FilteringRule>(); /// <inheritdoc/> protected override void Write(AsyncLogEventInfo logEvent) { Write((IList<AsyncLogEventInfo>)new[] { logEvent }); // Single LogEvent should also work } /// <summary> /// Evaluates all filtering rules to find the first one that matches. /// The matching rule determines the filtering condition to be applied /// to all items in a buffer. If no condition matches, default filter /// is applied to the array of log events. /// </summary> /// <param name="logEvents">Array of log events to be post-filtered.</param> protected override void Write(IList<AsyncLogEventInfo> logEvents) { InternalLogger.Trace("{0}: Running on {1} events", this, logEvents.Count); var resultFilter = EvaluateAllRules(logEvents) ?? DefaultFilter; if (resultFilter is null) { WrappedTarget.WriteAsyncLogEvents(logEvents); } else { InternalLogger.Trace("{0}: Filter to apply: {1}", this, resultFilter); var resultBuffer = logEvents.Filter(resultFilter, (logEvent, filter) => ShouldLogEvent(logEvent, filter)); InternalLogger.Trace("{0}: After filtering: {1} events.", this, resultBuffer.Count); if (resultBuffer.Count > 0) { InternalLogger.Trace("{0}: Sending to {1}", this, WrappedTarget); WrappedTarget.WriteAsyncLogEvents(resultBuffer); } } } private static bool ShouldLogEvent(AsyncLogEventInfo logEvent, ConditionExpression resultFilter) { object v = resultFilter.Evaluate(logEvent.LogEvent); if (ConditionExpression.BoxedTrue.Equals(v)) { return true; } else { logEvent.Continuation(null); return false; } } /// <summary> /// Evaluate all the rules to get the filtering condition /// </summary> /// <param name="logEvents"></param> /// <returns></returns> private ConditionExpression EvaluateAllRules(IList<AsyncLogEventInfo> logEvents) { if (Rules.Count == 0) return null; for (int i = 0; i < logEvents.Count; ++i) { for (int j = 0; j < Rules.Count; ++j) { var rule = Rules[j]; object v = rule.Exists.Evaluate(logEvents[i].LogEvent); if (ConditionExpression.BoxedTrue.Equals(v)) { InternalLogger.Trace("{0}: Rule matched: {1}", this, rule.Exists); return rule.Filter; } } } return null; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Layouts { using System; using NLog.Layouts; using Xunit; public class LayoutTypedTests : NLogTestBase { [Fact] public void LayoutFixedIntValueTest() { // Arrange Layout<int> layout = 5; // Act var result = layout.RenderValue(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal(5, result); Assert.Equal("5", layout.Render(LogEventInfo.CreateNullEvent())); Assert.True(layout.IsFixed); Assert.Equal(5, layout.FixedValue); Assert.Equal("5", layout.ToString()); Assert.Equal(5, layout); Assert.NotEqual(0, layout); } [Fact] public void LayoutFixedInvalidIntTest() { Layout<int> layout; Assert.Throws<NLogConfigurationException>(() => layout = "abc"); } [Fact] public void LayoutFixedEmptyIntTest() { Layout<int> layout = ""; var result = layout.RenderValue(LogEventInfo.CreateNullEvent()); Assert.Equal(0, result); Assert.Equal("", layout.ToString()); } [Fact] public void LayoutFixedNullEventTest() { // Arrange Layout<int> layout = 5; // Act var result = layout.RenderValue(null); // Assert Assert.Equal(5, result); } [Fact] public void LayoutFixedNullableIntValueTest() { // Arrange Layout<int?> layout = 5; // Act var result = layout.RenderValue(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal(5, result); Assert.Equal("5", layout.Render(LogEventInfo.CreateNullEvent())); Assert.True(layout.IsFixed); Assert.Equal(5, layout.FixedValue); Assert.Equal("5", layout.ToString()); Assert.Equal(5, layout); Assert.NotEqual(0, layout); Assert.NotEqual(default(int?), layout); } [Fact] public void LayoutFixedInvalidNullableIntTest() { Layout<int?> layout; Assert.Throws<NLogConfigurationException>(() => layout = "abc"); } [Fact] public void LayoutFixedEmptyNullableIntTest() { Layout<int?> layout = ""; var result = layout.RenderValue(LogEventInfo.CreateNullEvent()); var result5 = layout.RenderValue(LogEventInfo.CreateNullEvent(), 5); Assert.Null(result); Assert.Null(result5); Assert.Equal("null", layout.ToString()); } [Fact] public void LayoutFixedNullIntValueTest() { // Arrange var nullValue = (int?)null; Layout<int?> layout = new Layout<int?>(nullValue); // Act var result = layout.RenderValue(LogEventInfo.CreateNullEvent()); var result5 = layout.RenderValue(LogEventInfo.CreateNullEvent(), 5); // Assert Assert.Null(result); Assert.Null(result5); Assert.Equal("", layout.Render(LogEventInfo.CreateNullEvent())); Assert.True(layout.IsFixed); Assert.Null(layout.FixedValue); Assert.Equal("null", layout.ToString()); Assert.Equal(nullValue, layout); Assert.NotEqual(0, layout); } [Fact] public void LayoutFixedUrlValueTest() { // Arrange var uri = new Uri("http://nlog"); Layout<Uri> layout = uri.ToString(); // Act var result = layout.RenderValue(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal(uri, result); Assert.Same(result, layout.RenderValue(LogEventInfo.CreateNullEvent())); Assert.Equal(uri.ToString(), layout.Render(LogEventInfo.CreateNullEvent())); Assert.Equal(uri, layout); Assert.True(layout.IsFixed); Assert.Equal(uri, layout.FixedValue); Assert.Same(layout.FixedValue, layout.FixedValue); Assert.Equal(uri.ToString(), layout.ToString()); Assert.Equal(uri, layout); Assert.NotEqual(new Uri("//other"), layout); Assert.NotEqual(default(Uri), layout); } [Fact] public void LayoutFixedNullUrlValueTest() { // Arrange Uri uri = null; Layout<Uri> layout = new Layout<Uri>(uri); // Act var result = layout.RenderValue(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal(uri, result); Assert.Same(result, layout.RenderValue(LogEventInfo.CreateNullEvent())); Assert.Equal("", layout.Render(LogEventInfo.CreateNullEvent())); Assert.True(layout == uri); Assert.False(layout != uri); Assert.True(layout.IsFixed); Assert.Equal(uri, layout.FixedValue); Assert.Same(layout.FixedValue, layout.FixedValue); Assert.Equal("null", layout.ToString()); Assert.NotEqual(new Uri("//other"), layout); } [Fact] public void LayoutFixedInvalidUrlTest() { Layout<Uri> layout; Assert.Throws<NLogConfigurationException>(() => layout = "!!!"); } [Fact] public void LayoutFixedEmptyUrlTest() { var uri = new Uri("http://nlog"); Layout<Uri> layout = ""; var result = layout.RenderValue(LogEventInfo.CreateNullEvent()); var resultFallback = layout.RenderValue(LogEventInfo.CreateNullEvent(), uri); Assert.Null(result); Assert.Equal(uri, resultFallback); Assert.Equal("", layout.ToString()); } [Fact] public void NullLayoutDefaultValueTest() { var nullLayout = default(Layout<int>); Assert.True(default(Layout<int>) == nullLayout); Assert.False(default(Layout<int>) != nullLayout); Assert.True(default(Layout<int>) == default(int)); Assert.False(default(Layout<int>) != default(int)); Assert.True(default(Layout<int>) == null); Assert.False(default(Layout<int>) != null); Assert.True(default(Layout<int?>) == default(int?)); Assert.False(default(Layout<int?>) != default(int?)); Assert.True(default(Layout<int?>) == null); Assert.False(default(Layout<int?>) != null); Assert.True(default(Layout<Uri>) == default(Uri)); Assert.False(default(Layout<Uri>) != default(Uri)); Assert.True(default(Layout<Uri>) == null); Assert.False(default(Layout<Uri>) != null); } [Fact] public void LayoutDynamicIntValueTest() { // Arrange string simpleLayout = "${event-properties:intvalue}"; Layout<int> layout = simpleLayout; // Act var logevent = LogEventInfo.Create(LogLevel.Info, null, null, "{intvalue}", new object[] { 5 }); var result = layout.RenderValue(logevent); // Assert Assert.Equal(5, result); Assert.Equal("5", layout.Render(logevent)); Assert.False(layout.IsFixed); Assert.Equal(simpleLayout, layout.ToString()); Assert.NotEqual(0, layout); } [Fact] public void LayoutDynamicIntNullEventTest() { // Arrange Layout<int> layout = "${event-properties:intvalue}"; // Act var result = layout.RenderValue(null, 42); // Assert Assert.Equal(42, result); } [Fact] public void LayoutDynamicNullableIntValueTest() { // Arrange Layout<int?> layout = "${event-properties:intvalue}"; // Act var logevent = LogEventInfo.Create(LogLevel.Info, null, null, "{intvalue}", new object[] { 5 }); var result = layout.RenderValue(logevent); // Assert Assert.Equal(5, result); Assert.Equal("5", layout.Render(logevent)); Assert.False(layout.IsFixed); Assert.NotEqual(0, layout); Assert.NotEqual(default(int?), layout); } [Fact] public void LayoutDynamicNullableGuidValueTest() { // Arrange Layout<Guid?> layout = "${event-properties:guidvalue}"; var guid = Guid.NewGuid(); // Act var logevent = LogEventInfo.Create(LogLevel.Info, null, null, "{guidvalue}", new object[] { guid }); var result = layout.RenderValue(logevent); // Assert Assert.Equal(guid, result); Assert.Equal(guid.ToString(), layout.Render(logevent)); Assert.False(layout.IsFixed); Assert.NotEqual(default(Guid), layout); Assert.NotEqual(default(Guid?), layout); } [Fact] public void LayoutDynamicNullIntValueTest() { // Arrange Layout<int?> layout = "${event-properties:intvalue}"; // Act var logevent = LogEventInfo.Create(LogLevel.Info, null, null, "{intvalue}", new object[] { null }); var result = layout.RenderValue(logevent); var result5 = layout.RenderValue(logevent, 5); // Assert Assert.Null(result); Assert.Equal(5, result5); Assert.Equal("", layout.Render(logevent)); } [Fact] public void LayoutDynamicUrlValueTest() { // Arrange Layout<Uri> layout = "${event-properties:urlvalue}"; var uri = new Uri("http://nlog"); // Act var logevent = LogEventInfo.Create(LogLevel.Info, null, null, "{urlvalue}", new object[] { uri.ToString() }); var result = layout.RenderValue(logevent); // Assert Assert.Equal(uri, result); Assert.Same(result, layout.RenderValue(logevent)); Assert.Equal(uri.ToString(), layout.Render(logevent)); Assert.False(layout.IsFixed); Assert.NotEqual(uri, layout); Assert.NotEqual(default(Uri), layout); } [Fact] public void LayoutDynamicUrlNullEventTest() { // Arrange Layout<Uri> layout = "${event-properties:urlvalue}"; var uri = new Uri("http://nlog"); // Act var result = layout.RenderValue(null, uri); // Assert Assert.Equal(uri, result); } [Fact] public void LayoutDynamicNullUrlValueTest() { // Arrange Layout<Uri> layout = "${event-properties:urlvalue}"; Uri uri = null; // Act var logevent = LogEventInfo.Create(LogLevel.Info, null, null, "{urlvalue}", new object[] { uri }); var result = layout.RenderValue(logevent); // Assert Assert.Equal(uri, result); Assert.Same(result, layout.RenderValue(logevent)); Assert.Equal("", layout.Render(logevent)); Assert.False(layout.IsFixed); Assert.NotEqual(uri, layout); } [Fact] public void LayoutDynamicIntValueAsyncTest() { // Arrange Layout<int> layout = "${scopeproperty:intvalue}"; // Act var logevent = LogEventInfo.CreateNullEvent(); using (ScopeContext.PushProperty("intvalue", 5)) { layout.Precalculate(logevent); } // Assert Assert.Equal(5, layout.RenderValue(logevent)); Assert.Equal("5", layout.Render(logevent)); Assert.False(layout.IsFixed); Assert.NotEqual(0, layout); } [Fact] public void LayoutDynamicNullableIntValueAsyncTest() { // Arrange Layout<int?> layout = "${scopeproperty:intvalue}"; // Act var logevent = LogEventInfo.CreateNullEvent(); using (ScopeContext.PushProperty("intvalue", 5)) { layout.Precalculate(logevent); } // Assert Assert.Equal(5, layout.RenderValue(logevent)); Assert.Equal("5", layout.Render(logevent)); Assert.False(layout.IsFixed); Assert.NotEqual(0, layout); Assert.NotEqual(default(int?), layout); } [Fact] public void LayoutDynamicUrlValueAsyncTest() { // Arrange Layout<Uri> layout = "${scopeproperty:urlvalue}"; var uri = new Uri("http://nlog"); // Act var logevent = LogEventInfo.CreateNullEvent(); using (ScopeContext.PushProperty("urlvalue", uri.ToString())) { layout.Precalculate(logevent); } // Assert Assert.Equal(uri, layout.RenderValue(logevent)); Assert.Same(layout.RenderValue(logevent), layout.RenderValue(logevent)); Assert.Equal(uri.ToString(), layout.Render(logevent)); Assert.False(layout.IsFixed); Assert.NotEqual(uri, layout); Assert.NotEqual(default(Uri), layout); } [Fact] public void LayoutDynamicUrlValueRawAsyncTest() { // Arrange Layout<Uri> layout = "${event-properties:urlvalue}"; var uri = new Uri("http://nlog"); // Act var logevent = LogEventInfo.Create(LogLevel.Info, null, null, "{urlvalue}", new object[] { uri }); layout.Precalculate(logevent); // Assert Assert.Same(uri, layout.RenderValue(logevent)); Assert.Same(layout.RenderValue(logevent), layout.RenderValue(logevent)); Assert.Same(uri, layout.RenderValue(logevent)); Assert.Equal(uri.ToString(), layout.Render(logevent)); Assert.False(layout.IsFixed); Assert.NotEqual(uri, layout); Assert.NotEqual(default(Uri), layout); } [Fact] public void LayoutDynamicRenderExceptionTypeTest() { // Arrange Layout<Type> layout = "${exception:format=type:norawvalue=true}"; var exception = new System.ApplicationException("Test"); var stringBuilder = new System.Text.StringBuilder(); // Act var logevent = LogEventInfo.Create(LogLevel.Info, null, exception, null, ""); var exceptionType = layout.RenderTypedValue(logevent, stringBuilder, null); stringBuilder.Length = 0; // Assert Assert.Equal(exception.GetType(), exceptionType); Assert.Same(exceptionType, layout.RenderTypedValue(logevent, stringBuilder, null)); } [Fact] public void ComplexTypeTestWithStringConversion() { // Arrange var value = "utf8"; var layout = CreateLayoutRenderedFromProperty<System.Text.Encoding>(); var logEventInfo = CreateLogEventInfoWithValue(value); // Act var result = layout.RenderValue(logEventInfo); // Assert Assert.Equal(System.Text.Encoding.UTF8.EncodingName, result.EncodingName); } [Fact] public void LayoutRenderIntValueWhenNull() { // Arrange var integer = 42; Layout<int> layout = null; // Act var value = LayoutTypedExtensions.RenderValue(layout, null, integer); // Assert Assert.Equal(integer, value); } [Fact] public void LayoutRenderNullableIntValueWhenNull() { // Arrange var integer = 42; Layout<int?> layout = null; // Act var value = LayoutTypedExtensions.RenderValue(layout, null, integer); // Assert Assert.Equal(integer, value); } [Fact] public void LayoutRenderUrlValueWhenNull() { // Arrange var url = new Uri("http://nlog"); Layout<Uri> layout = null; // Act var value = LayoutTypedExtensions.RenderValue(layout, null, url); // Assert Assert.Equal(url, value); } [Fact] public void LayoutEqualsIntValueFixedTest() { // Arrange Layout<int> layout1 = "42"; Layout<int> layout2 = "42"; // Act + Assert Assert.True(layout1 == 42); Assert.True(layout1.Equals(42)); Assert.True(layout1.Equals((object)42)); Assert.Equal(layout1, layout2); Assert.Equal(layout1.GetHashCode(), layout2.GetHashCode()); } [Fact] public void LayoutEqualsNullableIntValueFixedTest() { // Arrange Layout<int?> layout1 = "42"; Layout<int?> layout2 = "42"; // Act + Assert Assert.True(layout1 == 42); Assert.True(layout1.Equals(42)); Assert.True(layout1.Equals((object)42)); Assert.Equal(layout1, layout2); Assert.Equal(layout1.GetHashCode(), layout2.GetHashCode()); } [Fact] public void LayoutEqualsNullIntValueFixedTest() { // Arrange int? nullInt = null; Layout<int?> layout1 = nullInt; Layout<int?> layout2 = nullInt; // Act + Assert Assert.True(layout1 == nullInt); Assert.True(layout1.Equals(nullInt)); Assert.True(layout1.Equals((object)nullInt)); Assert.Equal(layout1, layout2); Assert.Equal(layout1.GetHashCode(), layout2.GetHashCode()); } [Fact] public void LayoutNotEqualsIntValueFixedTest() { // Arrange Layout<int> layout1 = "2"; Layout<int> layout2 = "42"; // Act + Assert Assert.False(layout1 == 42); Assert.False(layout1.Equals(42)); Assert.False(layout1.Equals((object)42)); Assert.NotEqual(layout1, layout2); Assert.NotEqual(layout1.GetHashCode(), layout2.GetHashCode()); } [Fact] public void LayoutNotEqualsNullableIntValueFixedTest() { // Arrange Layout<int?> layout1 = "2"; Layout<int?> layout2 = "42"; // Act + Assert Assert.False(layout1 == 42); Assert.False(layout1.Equals(42)); Assert.False(layout1.Equals((object)42)); Assert.NotEqual(layout1, layout2); Assert.NotEqual(layout1.GetHashCode(), layout2.GetHashCode()); } [Fact] public void LayoutNotEqualsNullIntValueFixedTest() { // Arrange int? nullInt = null; Layout<int?> layout1 = "2"; Layout<int?> layout2 = nullInt; // Act + Assert Assert.False(layout1 == nullInt); Assert.False(layout1.Equals(nullInt)); Assert.False(layout1.Equals((object)nullInt)); Assert.NotEqual(layout1, layout2); Assert.NotEqual(layout1.GetHashCode(), layout2.GetHashCode()); } [Fact] public void LayoutEqualsUrlValueFixedTest() { // Arrange var url = new Uri("http://nlog"); Layout<Uri> layout1 = url; Layout<Uri> layout2 = url; // Act + Assert Assert.True(layout1 == url); Assert.True(layout1.Equals(url)); Assert.True(layout1.Equals((object)url)); Assert.Equal(layout1, layout2); Assert.Equal(layout1.GetHashCode(), layout2.GetHashCode()); } [Fact] public void LayoutEqualsNullUrlValueFixedTest() { // Arrange Uri url = null; Layout<Uri> layout1 = url; Layout<Uri> layout2 = new Layout<Uri>(url); // Act + Assert Assert.Null(layout1); Assert.True(layout1 == url); Assert.True(layout2 == url); Assert.True(layout2.Equals(url)); Assert.True(layout2.Equals((object)url)); Assert.NotEqual(layout1, layout2); } [Fact] public void LayoutNotEqualsUrlValueFixedTest() { // Arrange var url = new Uri("http://nlog"); var url2 = new Uri("http://nolog"); Layout<Uri> layout1 = url2; Layout<Uri> layout2 = url; // Act + Assert Assert.False(layout1 == url); Assert.False(layout1.Equals(url)); Assert.False(layout1.Equals((object)url)); Assert.NotEqual(layout1, layout2); Assert.NotEqual(layout1.GetHashCode(), layout2.GetHashCode()); } [Fact] public void LayoutNotEqualsNullUrlValueFixedTest() { // Arrange Uri url = null; var url2 = new Uri("http://nlog"); Layout<Uri> layout1 = url2; Layout<Uri> layout2 = new Layout<Uri>(url); // Act + Assert Assert.False(layout1 == url); Assert.False(layout1.Equals(url)); Assert.False(layout1.Equals((object)url)); Assert.NotEqual(layout1, layout2); Assert.NotEqual(layout1.GetHashCode(), layout2.GetHashCode()); } [Fact] public void LayoutEqualsIntValueDynamicTest() { // Arrange Layout<int> layout1 = "${event-properties:intvalue}"; Layout<int> layout2 = "${event-properties:intvalue}"; // Act + Assert (LogEventInfo.LayoutCache must work) Assert.NotEqual(layout1, layout2); Assert.NotEqual(layout1.GetHashCode(), layout2.GetHashCode()); Assert.NotEqual(0, layout1); } [Fact] public void LayoutEqualsNullableIntValueDynamicTest() { // Arrange Layout<int?> layout1 = "${event-properties:intvalue}"; Layout<int?> layout2 = "${event-properties:intvalue}"; // Act + Assert (LogEventInfo.LayoutCache must work) Assert.NotEqual(layout1, layout2); Assert.NotEqual(layout1.GetHashCode(), layout2.GetHashCode()); Assert.NotEqual(0, layout1); Assert.NotEqual(default(int?), layout1); } [Fact] public void LayoutEqualsUrlValueDynamicTest() { // Arrange Layout<Uri> layout1 = "${event-properties:urlvalue}"; Layout<Uri> layout2 = "${event-properties:urlvalue}"; // Act + Assert (LogEventInfo.LayoutCache must work) Assert.NotEqual(layout1, layout2); Assert.NotEqual(layout1.GetHashCode(), layout2.GetHashCode()); Assert.NotEqual(default(Uri), layout1); } [Theory] [InlineData(100)] [InlineData(100d)] [InlineData("100")] [InlineData(" 100 ")] public void TypedIntLayoutDynamicTest(object value) { // Arrange var layout = CreateLayoutRenderedFromProperty<int>(); var logEventInfo = CreateLogEventInfoWithValue(value); // Act var result = layout.RenderValue(logEventInfo); // Assert Assert.Equal(100, result); } [Fact] public void TypedNullableIntToIntLayoutDynamicTest() { // Arrange var layout = CreateLayoutRenderedFromProperty<int>(); int? value = 100; var logEventInfo = CreateLogEventInfoWithValue(value); // Act var result = layout.RenderValue(logEventInfo); // Assert Assert.Equal(100, result); } [Theory] [InlineData(100)] [InlineData(100d)] [InlineData("100")] [InlineData(" 100 ")] public void TypedNullableIntLayoutDynamicTest(object value) { // Arrange var layout = CreateLayoutRenderedFromProperty<int?>(); var logEventInfo = CreateLogEventInfoWithValue(value); // Act var result = layout.RenderValue(logEventInfo); // Assert Assert.Equal(100, result); } [Theory] [InlineData(100.5)] [InlineData("100.5", "EN-us")] [InlineData(" 100.5 ", "EN-us")] public void TypedDecimalLayoutDynamicTest(object value, string culture = null) { // Arrange var oldCulture = System.Threading.Thread.CurrentThread.CurrentCulture; try { if (!string.IsNullOrEmpty(culture)) { System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(culture); } var layout = CreateLayoutRenderedFromProperty<decimal>(); var logEventInfo = CreateLogEventInfoWithValue(value); // Act var result = layout.RenderValue(logEventInfo); // Assert decimal expected = 100.5m; Assert.Equal(expected, result); } finally { System.Threading.Thread.CurrentThread.CurrentCulture = oldCulture; } } [Theory] [InlineData(true)] [InlineData("true")] [InlineData(" true ")] public void TypedBoolLayoutDynamicTest(object value) { // Arrange var layout = CreateLayoutRenderedFromProperty<bool>(); var logEventInfo = CreateLogEventInfoWithValue(value); // Act var result = layout.RenderValue(logEventInfo); // Assert Assert.True(result); } /// <remarks>Cache usage, see coverage result</remarks> [Fact] public void SameValueShouldUseCacheAndCorrectResult() { // Arrange var layout = CreateLayoutRenderedFromProperty<bool>(); var logEventInfo1 = CreateLogEventInfoWithValue("true"); var logEventInfo2 = CreateLogEventInfoWithValue("true"); var logEventInfo3 = CreateLogEventInfoWithValue("true"); // Act var result1 = layout.RenderValue(logEventInfo1); var result2 = layout.RenderValue(logEventInfo2); var result3 = layout.RenderValue(logEventInfo3); // Assert Assert.True(result1); Assert.True(result2); Assert.True(result3); } [Fact] public void ComplexTypeTest() { // Arrange + Act + Assert Assert.Throws<NLogConfigurationException>(() => CreateLayoutRenderedFromProperty<TestObject>()); } [Fact] public void WrongValueErrorTest() { // Arrange var value = "12312aa3"; var layout = CreateLayoutRenderedFromProperty<int>(); var logEventInfo = CreateLogEventInfoWithValue(value); // Act var result = layout.RenderValue(logEventInfo); // Assert Assert.Equal(0, result); } [Theory] [InlineData("100", 100)] [InlineData("1 00", null)] public void TryGetRawValueTest(string input, int? expected) { // Arrange var layout = new Layout<int?>("${event-properties:prop1}"); var logEventInfo = LogEventInfo.CreateNullEvent(); logEventInfo.Properties["prop1"] = input; // Act var result = layout.RenderValue(logEventInfo); // Assert Assert.Equal(expected, result); } [Fact] public void TryConvertToShouldHandleNullLayout() { // Arrange var layout = new Layout<int>((Layout)null); var logEventInfo = LogEventInfo.CreateNullEvent(); // Act var result = layout.RenderValue(logEventInfo); // Assert Assert.Equal(0, result); } [Fact] public void RenderShouldHandleInvalidConversionAndLogFactory() { // Arrange var factory = new LogFactory { ThrowExceptions = false, }; var configuration = new NLog.Config.LoggingConfiguration(factory); var layout = new Layout<int>("${event-properties:prop1}"); layout.Initialize(configuration); var logEventInfo = LogEventInfo.CreateNullEvent(); logEventInfo.Properties["prop1"] = "Not a int"; // Act int result; using (new NoThrowNLogExceptions()) { result = layout.RenderValue(logEventInfo); } // Assert Assert.Equal(0, result); } [Fact] public void RenderShouldHandleInvalidConversionAndLogFactoryAndDefault() { // Arrange var factory = new LogFactory { ThrowExceptions = false, }; var configuration = new NLog.Config.LoggingConfiguration(factory); var layout = new Layout<int>("${event-properties:prop1}"); layout.Initialize(configuration); var logEventInfo = LogEventInfo.CreateNullEvent(); logEventInfo.Properties["prop1"] = "Not a int"; // Act int result; using (new NoThrowNLogExceptions()) { result = layout.RenderValue(logEventInfo, 200); } // Assert Assert.Equal(200, result); } [Fact] public void RenderShouldHandleValidConversion() { // Arrange var layout = new Layout<int>("${event-properties:prop1}"); var logEventInfo = LogEventInfo.CreateNullEvent(); logEventInfo.Properties["prop1"] = "100"; // Act var result = layout.RenderValue(logEventInfo); // Assert Assert.Equal(100, result); } #if !DEBUG [Fact(Skip = "RELEASE not working, only DEBUG")] #else [Fact] #endif public void RenderShouldRecognizeStackTraceUsage() { // Arrange object[] callback_args = null; Action<LogEventInfo, object[]> callback = (evt, args) => callback_args = args; var logger = new LogFactory().Setup().LoadConfiguration(builder => { var methodCall = new NLog.Targets.MethodCallTarget("dbg", callback); methodCall.Parameters.Add(new NLog.Targets.MethodCallParameter("LineNumber", "${callsite-linenumber}", typeof(int))); builder.ForLogger().WriteTo(methodCall); }).GetLogger(nameof(RenderShouldRecognizeStackTraceUsage)); // Act logger.Info("Testing"); // Assert Assert.Single(callback_args); var lineNumber = Assert.IsType<int>(callback_args[0]); Assert.True(lineNumber > 0); } [Fact] public void LayoutRendererSupportTypedLayout() { var cif = new NLog.Config.ConfigurationItemFactory(); cif.LayoutRendererFactory.RegisterType<LayoutTypedTestLayoutRenderer>(nameof(LayoutTypedTestLayoutRenderer)); Layout l = new SimpleLayout("${LayoutTypedTestLayoutRenderer:IntProperty=42}", cif); l.Initialize(null); var result = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("42", result); } [Fact] [Obsolete("Instead override type-creation by calling NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public void LayoutRendererSupportTypedLayout_Legacy() { var cif = new NLog.Config.ConfigurationItemFactory(); cif.RegisterType(typeof(LayoutTypedTestLayoutRenderer), string.Empty); Layout l = new SimpleLayout("${LayoutTypedTestLayoutRenderer:IntProperty=42}", cif); l.Initialize(null); var result = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("42", result); } private class TestObject { public string Value { get; set; } } private static Layout<T> CreateLayoutRenderedFromProperty<T>() { var layout = new Layout<T>("${event-properties:value1}"); return layout; } private static LogEventInfo CreateLogEventInfoWithValue(object value) { var logEventInfo = LogEventInfo.Create(LogLevel.Info, "logger1", "message1"); logEventInfo.Properties.Add("value1", value); return logEventInfo; } [NLog.LayoutRenderers.LayoutRenderer(nameof(LayoutTypedTestLayoutRenderer))] public class LayoutTypedTestLayoutRenderer : NLog.LayoutRenderers.LayoutRenderer { public Layout<int> IntProperty { get; set; } = 0; protected override void Append(System.Text.StringBuilder builder, LogEventInfo logEvent) { builder.Append(IntProperty.RenderValue(logEvent).ToString()); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using NLog.Config; using NLog.Filters; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using NLog.Targets.Wrappers; namespace NLog { /// <summary> /// Extension methods to setup NLog <see cref="LoggingConfiguration"/> /// </summary> public static class SetupLoadConfigurationExtensions { /// <summary> /// Configures the global time-source used for all logevents /// </summary> /// <remarks> /// Available by default: <see cref="Time.AccurateLocalTimeSource"/>, <see cref="Time.AccurateUtcTimeSource"/>, <see cref="Time.FastLocalTimeSource"/>, <see cref="Time.FastUtcTimeSource"/> /// </remarks> public static ISetupLoadConfigurationBuilder SetTimeSource(this ISetupLoadConfigurationBuilder configBuilder, NLog.Time.TimeSource timeSource) { NLog.Time.TimeSource.Current = timeSource; return configBuilder; } /// <summary> /// Updates the dictionary <see cref="GlobalDiagnosticsContext"/> ${gdc:item=} with the name-value-pair /// </summary> public static ISetupLoadConfigurationBuilder SetGlobalContextProperty(this ISetupLoadConfigurationBuilder configBuilder, string name, string value) { GlobalDiagnosticsContext.Set(name, value); return configBuilder; } /// <summary> /// Defines <see cref="LoggingRule" /> for redirecting output from matching <see cref="Logger"/> to wanted targets. /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="loggerNamePattern">Logger name pattern to check which <see cref="Logger"/> names matches this rule</param> /// <param name="ruleName">Rule identifier to allow rule lookup</param> public static ISetupConfigurationLoggingRuleBuilder ForLogger(this ISetupLoadConfigurationBuilder configBuilder, string loggerNamePattern = "*", string ruleName = null) { var ruleBuilder = new SetupConfigurationLoggingRuleBuilder(configBuilder.LogFactory, configBuilder.Configuration, loggerNamePattern, ruleName); ruleBuilder.LoggingRule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); return ruleBuilder; } /// <summary> /// Defines <see cref="LoggingRule" /> for redirecting output from matching <see cref="Logger"/> to wanted targets. /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="finalMinLevel">Restrict minimum LogLevel for <see cref="Logger"/> names that matches this rule</param> /// <param name="loggerNamePattern">Logger name pattern to check which <see cref="Logger"/> names matches this rule</param> /// <param name="ruleName">Rule identifier to allow rule lookup</param> public static ISetupConfigurationLoggingRuleBuilder ForLogger(this ISetupLoadConfigurationBuilder configBuilder, LogLevel finalMinLevel, string loggerNamePattern = "*", string ruleName = null) { var ruleBuilder = new SetupConfigurationLoggingRuleBuilder(configBuilder.LogFactory, configBuilder.Configuration, loggerNamePattern, ruleName); if (finalMinLevel != null) { ruleBuilder.LoggingRule.EnableLoggingForLevels(finalMinLevel, LogLevel.MaxLevel); ruleBuilder.LoggingRule.FinalMinLevel = finalMinLevel; } else { ruleBuilder.LoggingRule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); } return ruleBuilder; } /// <summary> /// Defines <see cref="LoggingRule" /> for redirecting output from matching <see cref="Logger"/> to wanted targets. /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="targetName">Override the name for the target created</param> public static ISetupConfigurationTargetBuilder ForTarget(this ISetupLoadConfigurationBuilder configBuilder, string targetName = null) { var ruleBuilder = new SetupConfigurationTargetBuilder(configBuilder.LogFactory, configBuilder.Configuration, targetName); return ruleBuilder; } /// <summary> /// Apply fast filtering based on <see cref="LogLevel"/>. Include LogEvents with same or worse severity as <paramref name="minLevel"/>. /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="minLevel">Minimum level that this rule matches</param> public static ISetupConfigurationLoggingRuleBuilder FilterMinLevel(this ISetupConfigurationLoggingRuleBuilder configBuilder, LogLevel minLevel) { Guard.ThrowIfNull(minLevel); configBuilder.LoggingRule.DisableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); configBuilder.LoggingRule.EnableLoggingForLevels(minLevel, LogLevel.MaxLevel); return configBuilder; } /// <summary> /// Apply fast filtering based on <see cref="LogLevel"/>. Include LogEvents with same or less severity as <paramref name="maxLevel"/>. /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="maxLevel">Maximum level that this rule matches</param> public static ISetupConfigurationLoggingRuleBuilder FilterMaxLevel(this ISetupConfigurationLoggingRuleBuilder configBuilder, LogLevel maxLevel) { Guard.ThrowIfNull(maxLevel); configBuilder.LoggingRule.DisableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); configBuilder.LoggingRule.EnableLoggingForLevels(LogLevel.MinLevel, maxLevel); return configBuilder; } /// <summary> /// Apply fast filtering based on <see cref="LogLevel"/>. Include LogEvents with severity that equals <paramref name="logLevel"/>. /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="logLevel">Single loglevel that this rule matches</param> public static ISetupConfigurationLoggingRuleBuilder FilterLevel(this ISetupConfigurationLoggingRuleBuilder configBuilder, LogLevel logLevel) { Guard.ThrowIfNull(logLevel); if (configBuilder.LoggingRule.IsLoggingEnabledForLevel(logLevel)) { configBuilder.LoggingRule.DisableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); } configBuilder.LoggingRule.EnableLoggingForLevel(logLevel); return configBuilder; } /// <summary> /// Apply fast filtering based on <see cref="LogLevel"/>. Include LogEvents with severity between <paramref name="minLevel"/> and <paramref name="maxLevel"/>. /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="minLevel">Minimum level that this rule matches</param> /// <param name="maxLevel">Maximum level that this rule matches</param> public static ISetupConfigurationLoggingRuleBuilder FilterLevels(this ISetupConfigurationLoggingRuleBuilder configBuilder, LogLevel minLevel, LogLevel maxLevel) { configBuilder.LoggingRule.DisableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); configBuilder.LoggingRule.EnableLoggingForLevels(minLevel ?? LogLevel.MinLevel, maxLevel ?? LogLevel.MaxLevel); return configBuilder; } /// <summary> /// Apply dynamic filtering logic for advanced control of when to redirect output to target. /// </summary> /// <remarks> /// Slower than using Logger-name or LogLevel-severity, because of <see cref="LogEventInfo"/> allocation. /// </remarks> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="filter">Filter for controlling whether to write</param> /// <param name="filterDefaultAction">Default action if none of the filters match</param> public static ISetupConfigurationLoggingRuleBuilder FilterDynamic(this ISetupConfigurationLoggingRuleBuilder configBuilder, Filter filter, FilterResult? filterDefaultAction = null) { Guard.ThrowIfNull(filter); configBuilder.LoggingRule.Filters.Add(filter); if (filterDefaultAction.HasValue) configBuilder.LoggingRule.FilterDefaultAction = filterDefaultAction.Value; return configBuilder; } /// <summary> /// Apply dynamic filtering logic for advanced control of when to redirect output to target. /// </summary> /// <remarks> /// Slower than using Logger-name or LogLevel-severity, because of <see cref="LogEventInfo"/> allocation. /// </remarks> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="filterMethod">Delegate for controlling whether to write</param> /// <param name="filterDefaultAction">Default action if none of the filters match</param> public static ISetupConfigurationLoggingRuleBuilder FilterDynamic(this ISetupConfigurationLoggingRuleBuilder configBuilder, Func<LogEventInfo, FilterResult> filterMethod, FilterResult? filterDefaultAction = null) { Guard.ThrowIfNull(filterMethod); return configBuilder.FilterDynamic(new WhenMethodFilter(filterMethod), filterDefaultAction); } /// <summary> /// Dynamic filtering of LogEvent, where it will be ignored when matching filter-method-delegate /// </summary> /// <remarks> /// Slower than using Logger-name or LogLevel-severity, because of <see cref="LogEventInfo"/> allocation. /// </remarks> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="filterMethod">Delegate for controlling whether to write</param> /// <param name="final">LogEvent will on match also be ignored by following logging-rules</param> public static ISetupConfigurationLoggingRuleBuilder FilterDynamicIgnore(this ISetupConfigurationLoggingRuleBuilder configBuilder, Func<LogEventInfo, bool> filterMethod, bool final = false) { var matchResult = final ? FilterResult.IgnoreFinal : FilterResult.Ignore; var whenMethodFilter = new WhenMethodFilter((evt) => filterMethod(evt) ? matchResult : FilterResult.Neutral) { Action = matchResult }; return configBuilder.FilterDynamic(whenMethodFilter, FilterResult.Neutral); } /// <summary> /// Dynamic filtering of LogEvent, where it will be logged when matching filter-method-delegate /// </summary> /// <remarks> /// Slower than using Logger-name or LogLevel-severity, because of <see cref="LogEventInfo"/> allocation. /// </remarks> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="filterMethod">Delegate for controlling whether to write</param> /// <param name="final">LogEvent will not be evaluated by following logging-rules</param> public static ISetupConfigurationLoggingRuleBuilder FilterDynamicLog(this ISetupConfigurationLoggingRuleBuilder configBuilder, Func<LogEventInfo, bool> filterMethod, bool final = false) { var matchResult = final ? FilterResult.LogFinal : FilterResult.Log; var whenMethodFilter = new WhenMethodFilter((evt) => filterMethod(evt) ? matchResult : FilterResult.Neutral) { Action = matchResult }; return configBuilder.FilterDynamic(whenMethodFilter, final ? FilterResult.IgnoreFinal : FilterResult.Ignore); } /// <summary> /// Move the <see cref="LoggingRule" /> to the top, to match before any of the existing <see cref="LoggingConfiguration.LoggingRules"/> /// </summary> public static ISetupConfigurationLoggingRuleBuilder TopRule(this ISetupConfigurationLoggingRuleBuilder configBuilder, bool insertFirst = true) { var loggingRule = configBuilder.LoggingRule; if (configBuilder.Configuration.LoggingRules.Contains(loggingRule)) { if (!insertFirst) return configBuilder; configBuilder.Configuration.LoggingRules.Remove(loggingRule); } if (insertFirst) configBuilder.Configuration.LoggingRules.Insert(0, loggingRule); else configBuilder.Configuration.LoggingRules.Add(loggingRule); return configBuilder; } /// <summary> /// Redirect output from matching <see cref="Logger"/> to the provided <paramref name="target"/> /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="target">Target that should be written to.</param> /// <returns>Fluent interface for configuring targets for the new LoggingRule.</returns> public static ISetupConfigurationTargetBuilder WriteTo(this ISetupConfigurationTargetBuilder configBuilder, Target target) { if (target != null) { if (string.IsNullOrEmpty(target.Name)) target.Name = EnsureUniqueTargetName(configBuilder.Configuration, target); configBuilder.Targets.Add(target); configBuilder.Configuration.AddTarget(target); } return configBuilder; } /// <summary> /// Redirect output from matching <see cref="Logger"/> to the provided <paramref name="targets"/> /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="targets">Target-collection that should be written to.</param> /// <returns>Fluent interface for configuring targets for the new LoggingRule.</returns> public static ISetupConfigurationTargetBuilder WriteTo(this ISetupConfigurationTargetBuilder configBuilder, params Target[] targets) { if (targets?.Length > 0) { for (int i = 0; i < targets.Length; ++i) { configBuilder.WriteTo(targets[i]); } } return configBuilder; } /// <summary> /// Redirect output from matching <see cref="Logger"/> to the provided <paramref name="targetBuilder"/> /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="targetBuilder">Target-collection that should be written to.</param> /// <returns>Fluent interface for configuring targets for the new LoggingRule.</returns> public static ISetupConfigurationTargetBuilder WriteTo(this ISetupConfigurationTargetBuilder configBuilder, ISetupConfigurationTargetBuilder targetBuilder) { if (ReferenceEquals(configBuilder, targetBuilder)) throw new ArgumentException("ConfigBuilder and TargetBuilder cannot be the same object", nameof(targetBuilder)); if (targetBuilder.Targets?.Count > 0) { for (int i = 0; i < targetBuilder.Targets.Count; ++i) { configBuilder.WriteTo(targetBuilder.Targets[i]); } } return configBuilder; } /// <summary> /// Discard output from matching <see cref="Logger"/>, so it will not reach any following <see cref="LoggingConfiguration.LoggingRules"/>. /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="finalMinLevel">Only discard output from matching Logger when below minimum LogLevel</param> public static void WriteToNil(this ISetupConfigurationLoggingRuleBuilder configBuilder, LogLevel finalMinLevel = null) { var loggingRule = configBuilder.LoggingRule; if (finalMinLevel != null) { if (loggingRule.Targets.Count == 0) { loggingRule = configBuilder.FilterMinLevel(finalMinLevel).LoggingRule; } loggingRule.FinalMinLevel = finalMinLevel; } else { if (loggingRule.Targets.Count == 0) { loggingRule = configBuilder.FilterMaxLevel(LogLevel.MaxLevel).LoggingRule; } if (loggingRule.Filters.Count == 0) { loggingRule.Final = true; } } if (loggingRule.Filters.Count > 0) { if (loggingRule.FilterDefaultAction == FilterResult.Ignore) { loggingRule.FilterDefaultAction = FilterResult.IgnoreFinal; } for (int i = 0; i < loggingRule.Filters.Count; ++i) { if (loggingRule.Filters[i].Action == FilterResult.Ignore) { loggingRule.Filters[i].Action = FilterResult.IgnoreFinal; } } if (loggingRule.Targets.Count == 0) { loggingRule.Targets.Add(new NullTarget()); } } if (!configBuilder.Configuration.LoggingRules.Contains(loggingRule)) { configBuilder.Configuration.LoggingRules.Add(loggingRule); } } /// <summary> /// Returns first target registered /// </summary> public static Target FirstTarget(this ISetupConfigurationTargetBuilder configBuilder) { return System.Linq.Enumerable.First(configBuilder.Targets); } /// <summary> /// Returns first target registered with the specified type /// </summary> /// <typeparam name="T">Type of target</typeparam> public static T FirstTarget<T>(this ISetupConfigurationTargetBuilder configBuilder) where T : Target { var target = System.Linq.Enumerable.First(configBuilder.Targets); for (int i = 0; i < configBuilder.Targets.Count; ++i) { foreach (var unwrappedTarget in YieldAllTargets(configBuilder.Targets[i])) { if (unwrappedTarget is T typedTarget) return typedTarget; } } throw new InvalidCastException($"Unable to cast object of type '{target.GetType()}' to type '{typeof(T)}'"); } internal static IEnumerable<Target> YieldAllTargets(Target target) { yield return target; if (target is WrapperTargetBase wrapperTarget) { foreach (var unwrappedTarget in YieldAllTargets(wrapperTarget.WrappedTarget)) yield return unwrappedTarget; } else if (target is CompoundTargetBase compoundTarget) { foreach (var nestedTarget in compoundTarget.Targets) { foreach (var unwrappedTarget in YieldAllTargets(nestedTarget)) yield return unwrappedTarget; } } } /// <summary> /// Write to <see cref="NLog.Targets.MethodCallTarget"/> /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="logEventAction">Method to call on logevent</param> /// <param name="layouts">Layouts to render object[]-args before calling <paramref name="logEventAction"/></param> public static ISetupConfigurationTargetBuilder WriteToMethodCall(this ISetupConfigurationTargetBuilder configBuilder, Action<LogEventInfo, object[]> logEventAction, Layout[] layouts = null) { Guard.ThrowIfNull(logEventAction); var methodTarget = new MethodCallTarget(string.Empty, logEventAction); if (layouts?.Length > 0) { foreach (var layout in layouts) methodTarget.Parameters.Add(new MethodCallParameter(layout)); } return configBuilder.WriteTo(methodTarget); } #if !NETSTANDARD1_3 /// <summary> /// Write to <see cref="NLog.Targets.ConsoleTarget"/> /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="layout">Override the default Layout for output</param> /// <param name="encoding">Override the default Encoding for output (Ex. UTF8)</param> /// <param name="stderr">Write to stderr instead of standard output (stdout)</param> /// <param name="detectConsoleAvailable">Skip overhead from writing to console, when not available (Ex. running as Windows Service)</param> /// <param name="writeBuffered">Enable batch writing of logevents, instead of Console.WriteLine for each logevent (Requires <see cref="WithAsync"/>)</param> public static ISetupConfigurationTargetBuilder WriteToConsole(this ISetupConfigurationTargetBuilder configBuilder, Layout layout = null, System.Text.Encoding encoding = null, bool stderr = false, bool detectConsoleAvailable = false, bool writeBuffered = false) { var consoleTarget = new ConsoleTarget(); if (layout != null) consoleTarget.Layout = layout; if (encoding != null) consoleTarget.Encoding = encoding; consoleTarget.StdErr = stderr; consoleTarget.DetectConsoleAvailable = detectConsoleAvailable; consoleTarget.WriteBuffer = writeBuffered; return configBuilder.WriteTo(consoleTarget); } /// <summary> /// Write to <see cref="NLog.Targets.TraceTarget"/> /// </summary> /// <param name="configBuilder"></param> /// <param name="layout">Override the default Layout for output</param> /// <param name="rawWrite">Force use <see cref="System.Diagnostics.Trace.WriteLine(string)"/> independent of <see cref="LogLevel"/></param> public static ISetupConfigurationTargetBuilder WriteToTrace(this ISetupConfigurationTargetBuilder configBuilder, Layout layout = null, bool rawWrite = true) { var traceTarget = new TraceTarget(); traceTarget.RawWrite = rawWrite; if (layout != null) traceTarget.Layout = layout; return configBuilder.WriteTo(traceTarget); } #endif /// <summary> /// Write to <see cref="NLog.Targets.DebugSystemTarget"/> /// </summary> /// <param name="configBuilder"></param> /// <param name="layout">Override the default Layout for output</param> public static ISetupConfigurationTargetBuilder WriteToDebug(this ISetupConfigurationTargetBuilder configBuilder, Layout layout = null) { var debugTarget = new DebugSystemTarget(); if (layout != null) debugTarget.Layout = layout; return configBuilder.WriteTo(debugTarget); } /// <summary> /// Write to <see cref="NLog.Targets.DebugSystemTarget"/> (when DEBUG-build) /// </summary> /// <param name="configBuilder"></param> /// <param name="layout">Override the default Layout for output</param> [System.Diagnostics.Conditional("DEBUG")] public static void WriteToDebugConditional(this ISetupConfigurationTargetBuilder configBuilder, Layout layout = null) { configBuilder.WriteToDebug(layout); } /// <summary> /// Write to <see cref="NLog.Targets.FileTarget"/> /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="fileName"></param> /// <param name="layout">Override the default Layout for output</param> /// <param name="encoding">Override the default Encoding for output (Default = UTF8)</param> /// <param name="lineEnding">Override the default line ending characters (Ex. <see cref="LineEndingMode.LF"/> without CR)</param> /// <param name="keepFileOpen">Keep log file open instead of opening and closing it on each logging event</param> /// <param name="concurrentWrites">Activate multi-process synchronization using global mutex on the operating system</param> /// <param name="archiveAboveSize">Size in bytes where log files will be automatically archived.</param> /// <param name="maxArchiveFiles">Maximum number of archive files that should be kept.</param> /// <param name="maxArchiveDays">Maximum days of archive files that should be kept.</param> public static ISetupConfigurationTargetBuilder WriteToFile(this ISetupConfigurationTargetBuilder configBuilder, Layout fileName, Layout layout = null, System.Text.Encoding encoding = null, LineEndingMode lineEnding = null, bool keepFileOpen = true, bool concurrentWrites = false, long archiveAboveSize = 0, int maxArchiveFiles = 0, int maxArchiveDays = 0) { Guard.ThrowIfNull(fileName); var fileTarget = new FileTarget(); fileTarget.FileName = fileName; if (layout != null) fileTarget.Layout = layout; if (encoding != null) fileTarget.Encoding = encoding; if (lineEnding != null) fileTarget.LineEnding = lineEnding; fileTarget.KeepFileOpen = keepFileOpen; fileTarget.ConcurrentWrites = concurrentWrites; fileTarget.ArchiveAboveSize = archiveAboveSize; fileTarget.MaxArchiveFiles = maxArchiveFiles; fileTarget.MaxArchiveDays = maxArchiveDays; return configBuilder.WriteTo(fileTarget); } /// <summary> /// Applies target wrapper for existing <see cref="LoggingRule.Targets"/> /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="wrapperFactory">Factory method for creating target-wrapper</param> public static ISetupConfigurationTargetBuilder WithWrapper(this ISetupConfigurationTargetBuilder configBuilder, Func<Target, Target> wrapperFactory) { Guard.ThrowIfNull(wrapperFactory); var targets = configBuilder.Targets; if (targets?.Count > 0) { for (int i = 0; i < targets.Count; ++i) { var target = targets[i]; var targetWrapper = wrapperFactory(target); if (targetWrapper is null || ReferenceEquals(targetWrapper, target)) continue; if (string.IsNullOrEmpty(targetWrapper.Name)) targetWrapper.Name = EnsureUniqueTargetName(configBuilder.Configuration, targetWrapper, target.Name); targets[i] = targetWrapper; configBuilder.Configuration.AddTarget(targetWrapper); } } else { throw new ArgumentException("Must call WriteTo(...) before applying target wrapper"); } return configBuilder; } /// <summary> /// Applies <see cref="NLog.Targets.Wrappers.AsyncTargetWrapper"/> for existing <see cref="LoggingRule.Targets"/> for asynchronous background writing /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="overflowAction">Action to take when queue overflows</param> /// <param name="queueLimit">Queue size limit for pending logevents</param> /// <param name="batchSize">Batch size when writing on the background thread</param> public static ISetupConfigurationTargetBuilder WithAsync(this ISetupConfigurationTargetBuilder configBuilder, AsyncTargetWrapperOverflowAction overflowAction = AsyncTargetWrapperOverflowAction.Discard, int queueLimit = 10000, int batchSize = 200) { return configBuilder.WithWrapper(t => { if (t is AsyncTargetWrapper) return null; #if !NET35 if (t is AsyncTaskTarget) return null; #endif var asyncWrapper = new AsyncTargetWrapper() { WrappedTarget = t }; asyncWrapper.OverflowAction = overflowAction; asyncWrapper.QueueLimit = queueLimit; asyncWrapper.BatchSize = batchSize; return asyncWrapper; }); } /// <summary> /// Applies <see cref="NLog.Targets.Wrappers.BufferingTargetWrapper"/> for existing <see cref="LoggingRule.Targets"/> for throttled writing /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="bufferSize">Buffer size limit for pending logevents</param> /// <param name="flushTimeout">Timeout for when the buffer will flush automatically using background thread</param> /// <param name="slidingTimeout">Restart timeout when logevent is written</param> /// <param name="overflowAction">Action to take when buffer overflows</param> public static ISetupConfigurationTargetBuilder WithBuffering(this ISetupConfigurationTargetBuilder configBuilder, int? bufferSize = null, TimeSpan? flushTimeout = null, bool? slidingTimeout = null, BufferingTargetWrapperOverflowAction? overflowAction = null) { return configBuilder.WithWrapper(t => { var targetWrapper = new BufferingTargetWrapper() { WrappedTarget = t }; if (bufferSize.HasValue) targetWrapper.BufferSize = bufferSize.Value; if (flushTimeout.HasValue) targetWrapper.FlushTimeout = (int)flushTimeout.Value.TotalMilliseconds; if (slidingTimeout.HasValue) targetWrapper.SlidingTimeout = slidingTimeout.Value; if (overflowAction.HasValue) targetWrapper.OverflowAction = overflowAction.Value; return targetWrapper; }); } /// <summary> /// Applies <see cref="NLog.Targets.Wrappers.AutoFlushTargetWrapper"/> for existing <see cref="LoggingRule.Targets"/> for flushing after conditional event /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="conditionMethod">Method delegate that controls whether logevent should force flush.</param> /// <param name="flushOnConditionOnly">Only flush when <paramref name="conditionMethod"/> triggers (Ignore config-reload and config-shutdown)</param> public static ISetupConfigurationTargetBuilder WithAutoFlush(this ISetupConfigurationTargetBuilder configBuilder, Func<LogEventInfo, bool> conditionMethod, bool? flushOnConditionOnly = null) { return configBuilder.WithWrapper(t => { var targetWrapper = new AutoFlushTargetWrapper() { WrappedTarget = t }; var autoFlushCondition = Conditions.ConditionMethodExpression.CreateMethodNoParameters("AutoFlush", (logEvent) => conditionMethod(logEvent) ? Conditions.ConditionExpression.BoxedTrue : Conditions.ConditionExpression.BoxedFalse); targetWrapper.Condition = autoFlushCondition; if (flushOnConditionOnly.HasValue) targetWrapper.FlushOnConditionOnly = flushOnConditionOnly.Value; return targetWrapper; }); } /// <summary> /// Applies <see cref="NLog.Targets.Wrappers.RetryingTargetWrapper"/> for existing <see cref="LoggingRule.Targets"/> for retrying after failure /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="retryCount">Number of retries that should be attempted on the wrapped target in case of a failure.</param> /// <param name="retryDelay">Time to wait between retries</param> public static ISetupConfigurationTargetBuilder WithRetry(this ISetupConfigurationTargetBuilder configBuilder, int? retryCount = null, TimeSpan? retryDelay = null) { return configBuilder.WithWrapper(t => { var targetWrapper = new RetryingTargetWrapper() { WrappedTarget = t }; if (retryCount.HasValue) targetWrapper.RetryCount = retryCount.Value; if (retryDelay.HasValue) targetWrapper.RetryDelayMilliseconds = (int)retryDelay.Value.TotalMilliseconds; return targetWrapper; }); } /// <summary> /// Applies <see cref="NLog.Targets.Wrappers.FallbackGroupTarget"/> for existing <see cref="LoggingRule.Targets"/> to fallback on failure. /// </summary> /// <param name="configBuilder">Fluent interface parameter.</param> /// <param name="fallbackTarget">Target to use for fallback</param> /// <param name="returnToFirstOnSuccess">Whether to return to the first target after any successful write</param> public static ISetupConfigurationTargetBuilder WithFallback(this ISetupConfigurationTargetBuilder configBuilder, Target fallbackTarget, bool returnToFirstOnSuccess = true) { Guard.ThrowIfNull(fallbackTarget); if (string.IsNullOrEmpty(fallbackTarget.Name)) fallbackTarget.Name = EnsureUniqueTargetName(configBuilder.Configuration, fallbackTarget, "_Fallback"); return configBuilder.WithWrapper(t => { var targetWrapper = new FallbackGroupTarget(); targetWrapper.ReturnToFirstOnSuccess = returnToFirstOnSuccess; targetWrapper.Targets.Add(t); targetWrapper.Targets.Add(fallbackTarget); configBuilder.Configuration.AddTarget(fallbackTarget); return targetWrapper; }); } private static string EnsureUniqueTargetName(LoggingConfiguration configuration, Target target, string suffix = "") { var allTargets = configuration.AllTargets; var targetName = target.Name; if (string.IsNullOrEmpty(targetName)) { targetName = GenerateTargetName(target.GetType()); } if (!string.IsNullOrEmpty(suffix)) { targetName = string.Concat(targetName, "_", suffix); } int targetIndex = 0; string newTargetName = targetName; while (!IsTargetNameUnique(allTargets, target, newTargetName)) { newTargetName = string.Concat(targetName, "_", (++targetIndex).ToString()); } return newTargetName; } private static bool IsTargetNameUnique(IList<Target> allTargets, Target target, string targetName) { for (int i = 0; i < allTargets.Count; ++i) { var otherTarget = allTargets[i]; if (ReferenceEquals(target, otherTarget)) return true; if (string.CompareOrdinal(otherTarget.Name, targetName) == 0) return false; } return true; } private static string GenerateTargetName(Type targetType) { var targetName = targetType.GetFirstCustomAttribute<TargetAttribute>()?.Name ?? targetType.Name; if (string.IsNullOrEmpty(targetName)) targetName = targetType.ToString(); if (targetName.EndsWith("TargetWrapper", StringComparison.Ordinal)) targetName = targetName.Substring(0, targetName.Length - 13); if (targetName.EndsWith("Wrapper", StringComparison.Ordinal)) targetName = targetName.Substring(0, targetName.Length - 7); if (targetName.EndsWith("GroupTarget", StringComparison.Ordinal)) targetName = targetName.Substring(0, targetName.Length - 12); if (targetName.EndsWith("Group", StringComparison.Ordinal)) targetName = targetName.Substring(0, targetName.Length - 5); if (targetName.EndsWith("Target", StringComparison.Ordinal)) targetName = targetName.Substring(0, targetName.Length - 6); if (string.IsNullOrEmpty(targetName)) targetName = "Unknown"; return targetName; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using JetBrains.Annotations; using NLog.Internal; using NLog.Targets; internal static class ServiceRepositoryExtensions { internal static ServiceRepository GetServiceProvider([CanBeNull] this LoggingConfiguration loggingConfiguration) { return loggingConfiguration?.LogFactory?.ServiceRepository ?? LogManager.LogFactory.ServiceRepository; } internal static T ResolveService<T>(this ServiceRepository serviceProvider, bool ignoreExternalProvider = true) where T : class { if (ignoreExternalProvider) { return serviceProvider.GetService<T>(); } else { IServiceProvider externalServiceProvider; try { if (serviceProvider.TryGetService<T>(out var service)) { return service; } externalServiceProvider = serviceProvider.GetService<IServiceProvider>(); } catch (NLogDependencyResolveException) { externalServiceProvider = serviceProvider.GetService<IServiceProvider>(); if (ReferenceEquals(externalServiceProvider, serviceProvider)) { throw; } } catch (Exception ex) { if (ex.MustBeRethrown()) throw; throw new NLogDependencyResolveException(ex.Message, ex, typeof(T)); } if (ReferenceEquals(externalServiceProvider, serviceProvider)) { throw new NLogDependencyResolveException("Instance of class must be registered", typeof(T)); } // External IServiceProvider can be dangerous to use from Logging-library and can lead to deadlock or stackoverflow // But during initialization of Logging-library then use of external IServiceProvider is probably safe var externalService = externalServiceProvider.GetService<T>(); // Cache singleton so also available when logging-library has been fully initialized serviceProvider.RegisterService(typeof(T), externalService); return externalService; } } internal static T GetService<T>(this IServiceProvider serviceProvider) where T : class { try { var service = (serviceProvider ?? LogManager.LogFactory.ServiceRepository).GetService(typeof(T)) as T; if (service is null) throw new NLogDependencyResolveException("Instance of class is unavailable", typeof(T)); return service; } catch (NLogDependencyResolveException ex) { if (ex.ServiceType == typeof(T)) throw; throw new NLogDependencyResolveException(ex.Message, ex, typeof(T)); } catch (Exception ex) { if (ex.MustBeRethrown()) throw; throw new NLogDependencyResolveException(ex.Message, ex, typeof(T)); } } /// <summary> /// Registers singleton-object as implementation of specific interface. /// </summary> /// <remarks> /// If the same single-object implements multiple interfaces then it must be registered for each interface /// </remarks> /// <typeparam name="T">Type of interface</typeparam> /// <param name="serviceRepository">The repo</param> /// <param name="singleton">Singleton object to use for override</param> internal static ServiceRepository RegisterSingleton<T>(this ServiceRepository serviceRepository, T singleton) where T : class { serviceRepository.RegisterService(typeof(T), singleton); return serviceRepository; } /// <summary> /// Registers the string serializer to use with <see cref="LogEventInfo.MessageTemplateParameters"/> /// </summary> internal static ServiceRepository RegisterValueFormatter(this ServiceRepository serviceRepository, [NotNull] IValueFormatter valueFormatter) { Guard.ThrowIfNull(valueFormatter); serviceRepository.RegisterSingleton(valueFormatter); return serviceRepository; } internal static ServiceRepository RegisterJsonConverter(this ServiceRepository serviceRepository, [NotNull] IJsonConverter jsonConverter) { Guard.ThrowIfNull(jsonConverter); serviceRepository.RegisterSingleton(jsonConverter); return serviceRepository; } internal static ServiceRepository RegisterPropertyTypeConverter(this ServiceRepository serviceRepository, [NotNull] IPropertyTypeConverter converter) { Guard.ThrowIfNull(converter); serviceRepository.RegisterSingleton(converter); return serviceRepository; } internal static ServiceRepository RegisterObjectTypeTransformer(this ServiceRepository serviceRepository, [NotNull] IObjectTypeTransformer transformer) { Guard.ThrowIfNull(transformer); serviceRepository.RegisterSingleton(transformer); return serviceRepository; } internal static ServiceRepository RegisterMessageTemplateParser(this ServiceRepository serviceRepository, bool? messageTemplateParser) { if (messageTemplateParser == false) { NLog.Common.InternalLogger.Debug("Message Template String Format always enabled"); serviceRepository.RegisterSingleton<ILogMessageFormatter>(LogMessageStringFormatter.Default); } else if (messageTemplateParser == true) { NLog.Common.InternalLogger.Debug("Message Template Format always enabled"); serviceRepository.RegisterSingleton<ILogMessageFormatter>(new LogMessageTemplateFormatter(serviceRepository, true, false)); } else { //null = auto NLog.Common.InternalLogger.Debug("Message Template Auto Format enabled"); serviceRepository.RegisterSingleton<ILogMessageFormatter>(new LogMessageTemplateFormatter(serviceRepository, false, false)); } return serviceRepository; } internal static bool? ResolveMessageTemplateParser(this ServiceRepository serviceRepository) { var messageFormatter = serviceRepository.GetService<ILogMessageFormatter>(); return messageFormatter?.MessageTemplateParser; } internal static ServiceRepository RegisterDefaults(this ServiceRepository serviceRepository) { serviceRepository.RegisterSingleton<IServiceProvider>(serviceRepository); serviceRepository.RegisterSingleton<ILogMessageFormatter>(new LogMessageTemplateFormatter(serviceRepository, false, false)); serviceRepository.RegisterJsonConverter(new DefaultJsonSerializer(serviceRepository)); serviceRepository.RegisterValueFormatter(new MessageTemplates.ValueFormatter(serviceRepository)); serviceRepository.RegisterPropertyTypeConverter(PropertyTypeConverter.Instance); serviceRepository.RegisterObjectTypeTransformer(new ObjectReflectionCache(serviceRepository)); return serviceRepository; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if MONO namespace NLog.Internal.FileAppenders { using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Security; using System.Text; using System.Threading; using System.Xml; using NLog; using NLog.Common; using NLog.Config; using NLog.Internal; using Mono.Unix; using Mono.Unix.Native; /// <summary> /// Provides a multiprocess-safe atomic file appends while /// keeping the files open. /// </summary> /// <remarks> /// On Unix you can get all the appends to be atomic, even when multiple /// processes are trying to write to the same file, because setting the file /// pointer to the end of the file and appending can be made one operation. /// </remarks> [SecuritySafeCritical] internal class UnixMultiProcessFileAppender : BaseMutexFileAppender { private UnixStream _file; public static readonly IFileAppenderFactory TheFactory = new Factory(); private sealed class Factory : IFileAppenderFactory { BaseFileAppender IFileAppenderFactory.Open(string fileName, ICreateFileParameters parameters) { return new UnixMultiProcessFileAppender(fileName, parameters); } } public UnixMultiProcessFileAppender(string fileName, ICreateFileParameters parameters) : base(fileName, parameters) { UnixFileInfo fileInfo = null; bool fileExists = false; try { fileInfo = new UnixFileInfo(fileName); fileExists = fileInfo.Exists; } catch { } int fd = Syscall.open(fileName, OpenFlags.O_CREAT | OpenFlags.O_WRONLY | OpenFlags.O_APPEND, (FilePermissions)(6 | (6 << 3) | (6 << 6))); if (fd == -1) { if (Stdlib.GetLastError() == Errno.ENOENT && parameters.CreateDirs) { string dirName = Path.GetDirectoryName(fileName); if (!Directory.Exists(dirName) && parameters.CreateDirs) Directory.CreateDirectory(dirName); fd = Syscall.open(fileName, OpenFlags.O_CREAT | OpenFlags.O_WRONLY | OpenFlags.O_APPEND, (FilePermissions)(6 | (6 << 3) | (6 << 6))); } } if (fd == -1) UnixMarshal.ThrowExceptionForLastError(); try { _file = new UnixStream(fd, true); long filePosition = _file.Position; if (fileExists || filePosition > 0) { if (fileInfo != null) { CreationTimeUtc = FileInfoHelper.LookupValidFileCreationTimeUtc(fileInfo, (f) => File.GetCreationTimeUtc(f.FullName), (f) => { f.Refresh(); return f.LastStatusChangeTimeUtc; }, (f) => DateTime.UtcNow).Value; } else { CreationTimeUtc = FileInfoHelper.LookupValidFileCreationTimeUtc(fileName, (f) => File.GetCreationTimeUtc(f), (f) => DateTime.UtcNow).Value; } } else { // We actually created the file and eventually concurrent processes CreationTimeUtc = DateTime.UtcNow; File.SetCreationTimeUtc(FileName, CreationTimeUtc); } } catch { Syscall.close(fd); throw; } } /// <inheritdoc/> public override void Write(byte[] bytes, int offset, int count) { _file?.Write(bytes, offset, count); } /// <inheritdoc/> public override void Close() { if (_file is null) return; InternalLogger.Trace("Closing '{0}'", FileName); try { _file?.Close(); } catch (Exception ex) { // Swallow exception as the file-stream now is in final state (broken instead of closed) InternalLogger.Warn(ex, "Failed to close file '{0}'", FileName); System.Threading.Thread.Sleep(1); // Artificial delay to avoid hammering a bad file location } finally { _file = null; } } /// <inheritdoc/> public override DateTime? GetFileCreationTimeUtc() { return CreationTimeUtc; // File is kept open, so creation time is static } /// <inheritdoc/> public override long? GetFileLength() { FileInfo fileInfo = new FileInfo(FileName); if (!fileInfo.Exists) return null; return fileInfo.Length; } public override void Flush() { // do nothing, the stream is always flushed } } } #endif <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.IO; using System.Linq; using NLog.Common; using NLog.Config; using NLog.Layouts; using NLog.LayoutRenderers; using NLog.Targets; using Xunit; namespace NLog.UnitTests.Config { public class LogFactorySetupTests { [Fact] public void SetupBuilderGetCurrentClassLogger() { // Arrange var logFactory = new LogFactory(); // Act var logger1 = logFactory.Setup().GetCurrentClassLogger(); var logger2 = logFactory.GetCurrentClassLogger(); // Assert Assert.Equal(typeof(LogFactorySetupTests).FullName, logger1.Name); Assert.Same(logger1, logger2); } [Fact] public void SetupBuilderGetLogger() { // Arrange var logFactory = new LogFactory(); // Act var logger1 = logFactory.Setup().GetLogger(nameof(SetupBuilderGetCurrentClassLogger)); var logger2 = logFactory.GetLogger(nameof(SetupBuilderGetCurrentClassLogger)); // Assert Assert.Equal(nameof(SetupBuilderGetCurrentClassLogger), logger1.Name); Assert.Same(logger1, logger2); } [Fact] public void SetupExtensionsSetTimeSourcAccurateUtcTest() { var currentTimeSource = NLog.Time.TimeSource.Current; try { // Arrange var logFactory = new LogFactory(); // Act logFactory.Setup().SetupLogFactory(builder => builder.SetTimeSourcAccurateUtc()); // Assert Assert.Same(NLog.Time.AccurateUtcTimeSource.Current, NLog.Time.TimeSource.Current); } finally { NLog.Time.TimeSource.Current = currentTimeSource; } } [Fact] public void SetupExtensionsSetTimeSourcAccurateLocalTest() { var currentTimeSource = NLog.Time.TimeSource.Current; try { // Arrange var logFactory = new LogFactory(); // Act logFactory.Setup().SetupLogFactory(builder => builder.SetTimeSourcAccurateLocal()); // Assert Assert.Same(NLog.Time.AccurateLocalTimeSource.Current, NLog.Time.TimeSource.Current); } finally { NLog.Time.TimeSource.Current = currentTimeSource; } } [Fact] public void SetupExtensionsSetGlobalContextPropertyTest() { // Arrange NLog.GlobalDiagnosticsContext.Clear(); try { // Act var logFactory = new LogFactory(); logFactory.Setup().SetupLogFactory(builder => builder.SetGlobalContextProperty(nameof(SetupExtensionsSetGlobalContextPropertyTest), "Yes")); // Assert Assert.Equal("Yes", NLog.GlobalDiagnosticsContext.Get(nameof(SetupExtensionsSetGlobalContextPropertyTest))); } finally { NLog.GlobalDiagnosticsContext.Clear(); } } [Fact] public void SetupExtensionsSetAutoShutdownTest() { // Arrange var logFactory = new LogFactory(); Assert.True(logFactory.AutoShutdown); // Act logFactory.Setup().SetupLogFactory(builder => builder.SetAutoShutdown(false)); // Assert Assert.False(logFactory.AutoShutdown); } [Fact] public void SetupExtensionsSetDefaultCultureInfoTest() { // Arrange var logFactory = new LogFactory(); Assert.Null(logFactory.DefaultCultureInfo); // Act logFactory.Setup().SetupLogFactory(builder => builder.SetDefaultCultureInfo(System.Globalization.CultureInfo.InvariantCulture)); logFactory.Setup().LoadConfigurationFromXml("<nlog></nlog>"); // Assert Assert.Same(System.Globalization.CultureInfo.InvariantCulture, logFactory.DefaultCultureInfo); Assert.Same(System.Globalization.CultureInfo.InvariantCulture, logFactory.Configuration.DefaultCultureInfo); } [Fact] public void SetupExtensionsSetGlobalThresholdTest() { // Arrange var logFactory = new LogFactory(); Assert.Equal(LogLevel.Trace, logFactory.GlobalThreshold); // Act logFactory.Setup().SetupLogFactory(builder => builder.SetGlobalThreshold(LogLevel.Error)); // Assert Assert.Equal(LogLevel.Error, logFactory.GlobalThreshold); } [Fact] public void SetupExtensionsSetThrowConfigExceptionsTest() { // Arrange var logFactory = new LogFactory(); Assert.Equal(default(bool?), logFactory.ThrowConfigExceptions); // Act logFactory.Setup().SetupLogFactory(builder => builder.SetThrowConfigExceptions(true)); // Assert Assert.True(logFactory.ThrowConfigExceptions); } [Fact] public void SetupExtensionsAutoLoadExtensionsTest() { // Arrange var logFactory = new LogFactory(); // Act logFactory.Setup().SetupExtensions(ext => ext.AutoLoadExtensions()); Func<LogFactory, LoggingConfiguration> buildConfig = (f) => new XmlLoggingConfiguration(@"<nlog throwExceptions='true'> <targets> <target name='t' type='AutoLoadTarget' /> </targets> <rules> <logger name='*' writeTo='t'> </logger> </rules> </nlog>", null, f); // Assert logFactory.Configuration = buildConfig(logFactory); Assert.NotNull(logFactory.Configuration.FindTargetByName("t")); } [Fact] public void SetupExtensionsRegisterAssemblyNameTest() { // Arrange var logFactory = new LogFactory(); // Act logFactory.Setup().SetupExtensions(ext => ext.RegisterAssembly("NLogAutoLoadExtension")); logFactory.Configuration = new XmlLoggingConfiguration(@"<nlog throwExceptions='true'> <targets> <target name='t' type='AutoLoadTarget' /> </targets> <rules> <logger name='*' writeTo='t'> </logger> </rules> </nlog>", null, logFactory); // Assert Assert.NotNull(logFactory.Configuration.FindTargetByName("t")); } [Fact] public void SetupExtensionsRegisterAssemblyTest() { // Arrange var logFactory = new LogFactory(); // Act logFactory.Setup().SetupExtensions(ext => ext.RegisterAssembly(typeof(MyExtensionNamespace.MyTarget).Assembly)); logFactory.Configuration = new XmlLoggingConfiguration(@"<nlog throwExceptions='true'> <targets> <target name='t' type='MyTarget' /> </targets> <rules> <logger name='*' writeTo='t'> </logger> </rules> </nlog>", null, logFactory); // Assert Assert.NotNull(logFactory.Configuration.FindTargetByName<MyExtensionNamespace.MyTarget>("t")); } [Fact] public void SetupExtensionsRegisterTargetTest() { // Arrange var logFactory = new LogFactory(); // Act logFactory.Setup().SetupExtensions(ext => ext.RegisterTarget<MyExtensionNamespace.MyTarget>("MyTarget")); logFactory.Configuration = new XmlLoggingConfiguration(@"<nlog throwExceptions='true'> <targets> <target name='t' type='MyTarget' /> </targets> <rules> <logger name='*' writeTo='t'> </logger> </rules> </nlog>", null, logFactory); // Assert Assert.NotNull(logFactory.Configuration.FindTargetByName<MyExtensionNamespace.MyTarget>("t")); } [Fact] public void SetupExtensionsRegisterTargetTypeTest() { // Arrange var logFactory = new LogFactory(); // Act logFactory.Setup().SetupExtensions(ext => ext.RegisterTarget<MyExtensionNamespace.MyTarget>()); logFactory.Configuration = new XmlLoggingConfiguration(@"<nlog throwExceptions='true'> <targets> <target name='t' type='MyTarget' /> </targets> <rules> <logger name='*' writeTo='t'> </logger> </rules> </nlog>", null, logFactory); // Assert Assert.NotNull(logFactory.Configuration.FindTargetByName<MyExtensionNamespace.MyTarget>("t")); } [Fact] public void SetupExtensionsRegisterLayoutTest() { // Arrange var logFactory = new LogFactory(); // Act logFactory.Setup().SetupExtensions(ext => ext.RegisterLayout<MyExtensionNamespace.FooLayout>("FooLayout")); logFactory.Configuration = new XmlLoggingConfiguration(@"<nlog throwExceptions='true'> <targets> <target name='debug' type='Debug'> <layout type='foolayout' /> </target> </targets> <rules> <logger name='*' writeTo='debug'> </logger> </rules> </nlog>", null, logFactory); logFactory.GetLogger("Hello").Info("World"); // Assert Assert.Equal("FooFoo0", logFactory.Configuration.FindTargetByName<DebugTarget>("debug").LastMessage); } [Fact] public void SetupExtensionsRegisterLayoutMethodTest() { // Arrange var logFactory = new LogFactory(); // Act logFactory.Setup(b => b.SetupExtensions(ext => ext.RegisterLayoutRenderer("mylayout", (l) => "42"))); logFactory.Configuration = new XmlLoggingConfiguration(@"<nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout='${mylayout}' /> </targets> <rules> <logger name='*' writeTo='debug'> </logger> </rules> </nlog>", null, logFactory); logFactory.GetLogger("Hello").Info("World"); // Assert Assert.Equal("42", logFactory.Configuration.FindTargetByName<DebugTarget>("debug").LastMessage); } [Fact] public void SetupExtensionsRegisterLayoutMethodFluentTest() { // Arrange var logFactory = new LogFactory(); // Act logFactory.Setup() .SetupExtensions(ext => ext.RegisterLayoutRenderer("mylayout", (l) => "42")) .LoadConfiguration(builder => { builder.ForLogger().WriteTo(new DebugTarget() { Layout = "${myLayout}" }); }); logFactory.GetLogger("Hello").Info("World"); // Assert Assert.Equal("42", logFactory.Configuration.FindTargetByName<DebugTarget>("debug").LastMessage); } [Fact] public void SetupExtensionsRegisterLayoutMethodThreadUnsafeTest() { // Arrange var logFactory = new LogFactory(); // Act logFactory.Setup(b => b.SetupExtensions(ext => ext.RegisterLayoutRenderer("mylayout", (l) => "42", LayoutRenderOptions.None))); logFactory.Configuration = new XmlLoggingConfiguration(@"<nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout='${mylayout}' /> </targets> <rules> <logger name='*' writeTo='debug'> </logger> </rules> </nlog>", null, logFactory); logFactory.GetLogger("Hello").Info("World"); ConfigurationItemFactory.Default.LayoutRendererFactory.TryCreateInstance("mylayout", out var layoutRenderer); var layout = new SimpleLayout(new LayoutRenderer[] { layoutRenderer }, "mylayout", ConfigurationItemFactory.Default); layout.Render(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal("42", logFactory.Configuration.FindTargetByName<DebugTarget>("debug").LastMessage); Assert.False(layout.ThreadAgnostic); } [Fact] public void SetupExtensionsRegisterLayoutMethodThreadAgnosticTest() { // Arrange var logFactory = new LogFactory(); // Act logFactory.Setup(b => b.SetupExtensions(ext => ext.RegisterLayoutRenderer("mylayout", (l) => "42", LayoutRenderOptions.ThreadAgnostic))); logFactory.Configuration = new XmlLoggingConfiguration(@"<nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout='${mylayout}' /> </targets> <rules> <logger name='*' writeTo='debug'> </logger> </rules> </nlog>", null, logFactory); logFactory.GetLogger("Hello").Info("World"); ConfigurationItemFactory.Default.LayoutRendererFactory.TryCreateInstance("mylayout", out var layoutRenderer); var layout = new SimpleLayout(new LayoutRenderer[] { layoutRenderer }, "mylayout", ConfigurationItemFactory.Default); layout.Render(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal("42", logFactory.Configuration.FindTargetByName<DebugTarget>("debug").LastMessage); Assert.True(layout.ThreadAgnostic); } [Fact] public void SetupExtensionsRegisterLayoutRendererTest() { // Arrange var logFactory = new LogFactory(); // Act logFactory.Setup().SetupExtensions(ext => ext.RegisterLayoutRenderer<MyExtensionNamespace.FooLayoutRenderer>("foo")); logFactory.Configuration = new XmlLoggingConfiguration(@"<nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout='${foo}' /> </targets> <rules> <logger name='*' writeTo='debug'> </logger> </rules> </nlog>", null, logFactory); logFactory.GetLogger("Hello").Info("World"); // Assert Assert.Equal("foo", logFactory.Configuration.FindTargetByName<DebugTarget>("debug").LastMessage); } [Fact] public void SetupExtensionsRegisterLayoutRendererTypeTest() { // Arrange var logFactory = new LogFactory(); // Act logFactory.Setup().SetupExtensions(ext => ext.RegisterLayoutRenderer<MyExtensionNamespace.FooLayoutRenderer>()); logFactory.Configuration = new XmlLoggingConfiguration(@"<nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout='${foo}' /> </targets> <rules> <logger name='*' writeTo='debug'> </logger> </rules> </nlog>", null, logFactory); logFactory.GetLogger("Hello").Info("World"); // Assert Assert.Equal("foo", logFactory.Configuration.FindTargetByName<DebugTarget>("debug").LastMessage); } [Theory] [InlineData(nameof(LogLevel.Fatal))] [InlineData(nameof(LogLevel.Off))] public void SetupInternalLoggerSetLogLevelTest(string logLevelName) { try { // Arrange var logLevel = LogLevel.FromString(logLevelName); InternalLogger.Reset(); var logFactory = new LogFactory(); // Act logFactory.Setup().SetupInternalLogger(b => b.SetMinimumLogLevel(logLevel)); // Assert Assert.Equal(logLevel, InternalLogger.LogLevel); } finally { InternalLogger.Reset(); } } [Fact] public void SetupInternalLoggerLogToFileTest() { try { // Arrange var logFile = $"{nameof(SetupInternalLoggerLogToFileTest)}.txt"; InternalLogger.Reset(); var logFactory = new LogFactory(); // Act logFactory.Setup().SetupInternalLogger(b => b.LogToFile(logFile).SetMinimumLogLevel(LogLevel.Fatal)); // Assert Assert.Equal(logFile, InternalLogger.LogFile); } finally { InternalLogger.Reset(); } } [Fact] public void SetupInternalLoggerLogToConsoleTest() { try { // Arrange InternalLogger.Reset(); var logFactory = new LogFactory(); // Act logFactory.Setup().SetupInternalLogger(b => b.SetMinimumLogLevel(LogLevel.Fatal).LogToConsole(true)); // Assert Assert.True(InternalLogger.LogToConsole); } finally { InternalLogger.Reset(); } } [Fact] public void SetupInternalLoggerLogToTraceTest() { try { // Arrange InternalLogger.Reset(); var logFactory = new LogFactory(); // Act logFactory.Setup().SetupInternalLogger(b => b.SetMinimumLogLevel(LogLevel.Fatal).LogToTrace(true)); // Assert Assert.True(InternalLogger.LogToTrace); } finally { InternalLogger.Reset(); } } [Fact] public void SetupInternalLoggerLogToWriterTest() { try { // Arrange InternalLogger.Reset(); var logFactory = new LogFactory(); // Act logFactory.Setup().SetupInternalLogger(b => b.SetMinimumLogLevel(LogLevel.Fatal).LogToWriter(Console.Out)); // Assert Assert.Equal(Console.Out, InternalLogger.LogWriter); } finally { InternalLogger.Reset(); } } [Fact] public void SetupInternalLoggerSetupFromEnvironmentVariablesTest() { try { // Arrange InternalLogger.Reset(); var logFactory = new LogFactory(); InternalLogger.LogToConsole = true; // Act logFactory.Setup().SetupInternalLogger(b => b.SetupFromEnvironmentVariables().SetMinimumLogLevel(LogLevel.Fatal)); // Assert Assert.False(InternalLogger.LogToConsole); Assert.Equal(LogLevel.Fatal, InternalLogger.LogLevel); } finally { InternalLogger.Reset(); } } [Fact] public void SetupExtensionsRegisterConditionMethodTest() { // Arrange var logFactory = new LogFactory(); logFactory.Setup().SetupExtensions(s => s.RegisterConditionMethod("hasParameters", evt => evt.Parameters?.Length > 0)); logFactory.Setup().SetupExtensions(s => s.RegisterConditionMethod("isProduction", () => false)); #pragma warning disable CS0618 // Type or member is obsolete logFactory.Setup().SetupExtensions(s => s.RegisterConditionMethod("isValid", typeof(Conditions.ConditionEvaluatorTests.MyConditionMethods).GetMethod(nameof(Conditions.ConditionEvaluatorTests.MyConditionMethods.IsValid)))); #pragma warning restore CS0618 // Type or member is obsolete // Act logFactory.Configuration = new XmlLoggingConfiguration(@"<nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout='${message}' /> </targets> <rules> <logger name='*' writeTo='debug'> <filters defaultAction='Neutral'> <when condition='hasParameters()' action='Ignore' /> <when condition='isProduction()' action='Ignore' /> <when condition='isValid()==false' action='Ignore' /> </filters> </logger> </rules> </nlog>", null, logFactory); logFactory.GetLogger("Hello").Info("World"); logFactory.GetLogger("Hello").Info("{0}", "Earth"); // Assert Assert.Equal("World", logFactory.Configuration.FindTargetByName<DebugTarget>("debug").LastMessage); } [Fact] public void SetupBuilderLoadConfigurationTest() { // Arrange var logFactory = new LogFactory(); var logConfig = new LoggingConfiguration(logFactory); // Act logFactory.Setup().LoadConfiguration(logConfig); // Assert Assert.Same(logConfig, logFactory.Configuration); } [Fact] public void SetupBuilderLoadConfigurationBuilderTest() { // Arrange var logFactory = new LogFactory(); LoggingConfiguration logConfig = null; // Act logFactory.Setup().LoadConfiguration(b => logConfig = b.Configuration); // Assert Assert.Same(logConfig, logFactory.Configuration); } [Fact] public void SetupBuilderLoadConfigurationFromFileTest() { // Arrange var xmlFile = new System.IO.StringReader("<nlog autoshutdown='false'></nlog>"); var appEnv = new Mocks.AppEnvironmentMock(f => true, f => System.Xml.XmlReader.Create(xmlFile)); var configLoader = new LoggingConfigurationFileLoader(appEnv); var logFactory = new LogFactory(configLoader); // Act logFactory.Setup().LoadConfigurationFromFile(); // Assert Assert.False(logFactory.AutoShutdown); } [Fact] public void SetupBuilderLoadConfigurationFromFileMissingButRequiredTest_IntegrationTest() { // Arrange var logFactory = new LogFactory(); // Act Action act = () => logFactory.Setup().LoadConfigurationFromFile(optional: false); // Assert var ex = Assert.Throws<FileNotFoundException>(act); Assert.Contains("NLog.dll.nlog", ex.Message); Assert.Contains(Directory.GetCurrentDirectory(), ex.Message); } [Fact] public void SetupBuilderLoadConfigurationFromFileMissingTest() { // Arrange var appEnv = new Mocks.AppEnvironmentMock(f => false, f => null); var configLoader = new LoggingConfigurationFileLoader(appEnv); var logFactory = new LogFactory(configLoader); // Act logFactory.Setup().LoadConfigurationFromFile(optional: true); // Assert Assert.Null(logFactory.Configuration); } [Fact] public void SetupBuilderLoadNLogConfigFromFileNotExistsTest() { // Arrange var xmlFile = new System.IO.StringReader("<nlog autoshutdown='false'></nlog>"); var appEnv = new Mocks.AppEnvironmentMock(f => false, f => System.Xml.XmlReader.Create(xmlFile)); var configLoader = new LoggingConfigurationFileLoader(appEnv); var logFactory = new LogFactory(configLoader); // Act logFactory.Setup().LoadConfigurationFromFile("NLog.config", optional: true); // Assert Assert.Null(logFactory.Configuration); } [Fact] public void SetupBuilderLoadConfigurationFromFileOptionalFalseTest() { // Arrange var xmlFile = new System.IO.StringReader("<nlog autoshutdown='false'></nlog>"); var appEnv = new Mocks.AppEnvironmentMock(f => false, f => System.Xml.XmlReader.Create(xmlFile)); var configLoader = new LoggingConfigurationFileLoader(appEnv); var logFactory = new LogFactory(configLoader); // Act / Assert Assert.Throws<System.IO.FileNotFoundException>(() => logFactory.Setup().LoadConfigurationFromFile("NLog.config", optional: false)); } [Fact] public void SetupBuilderLoadConfigurationFromXmlTest() { // Arrange var logFactory = new LogFactory(); // Act logFactory.Setup().LoadConfigurationFromXml("<nlog autoshutdown='false'></nlog>"); // Assert Assert.False(logFactory.AutoShutdown); } [Fact] public void SetupBuilderLoadConfigurationFromXmlPatchTest() { // Arrange var xmlFile = new System.IO.StringReader("<nlog autoshutdown='true'></nlog>"); var appEnv = new Mocks.AppEnvironmentMock(f => true, f => System.Xml.XmlReader.Create(xmlFile)); var configLoader = new LoggingConfigurationFileLoader(appEnv); var logFactory = new LogFactory(configLoader); // Act logFactory.Setup(). LoadConfigurationFromXml("<nlog autoshutdown='false'></nlog>"). LoadConfigurationFromFile(). // No effect, since config already loaded LoadConfiguration(b => { b.Configuration.Variables["Hello"] = "World"; }); // Assert Assert.False(logFactory.AutoShutdown); Assert.Single(logFactory.Configuration.Variables); } [Fact] public void SetupBuilder_TimeSource() { // Arrange var originalTimeSource = NLog.Time.TimeSource.Current; try { // Act var logFactory = new LogFactory(); logFactory.Setup().LoadConfiguration(builder => builder.SetTimeSource(new NLog.Time.AccurateUtcTimeSource())); // Assert Assert.Same(typeof(NLog.Time.AccurateUtcTimeSource), NLog.Time.TimeSource.Current.GetType()); } finally { NLog.Time.TimeSource.Current = originalTimeSource; } } [Fact] public void SetupBuilder_GlobalDiagnosticContext() { // Arrange NLog.GlobalDiagnosticsContext.Clear(); try { // Act var logFactory = new LogFactory(); logFactory.Setup().LoadConfiguration(builder => builder.SetGlobalContextProperty(nameof(SetupBuilder_GlobalDiagnosticContext), "Yes")); // Assert Assert.Equal("Yes", NLog.GlobalDiagnosticsContext.Get(nameof(SetupBuilder_GlobalDiagnosticContext))); } finally { NLog.GlobalDiagnosticsContext.Clear(); } } [Fact] public void SetupBuilder_FilterMinLevel() { var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => c.ForLogger().FilterMinLevel(LogLevel.Debug).WriteTo(new DebugTarget() { Layout = "${message}" })).GetCurrentClassLogger(); var target = logFactory.Configuration.AllTargets.OfType<DebugTarget>().FirstOrDefault(); Assert.Single(logFactory.Configuration.AllTargets); Assert.NotNull(target); logger.Info("Info Level"); Assert.Equal("Info Level", target.LastMessage); logger.Info("Fatal Level"); Assert.Equal("Fatal Level", target.LastMessage); logger.Trace("Trace Level"); Assert.Equal("Fatal Level", target.LastMessage); } [Fact] public void SetupBuilder_FilterBlackHole() { var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => { c.ForLogger().FilterMinLevel(LogLevel.Info).WriteTo(new DebugTarget() { Layout = "${message}" }); c.ForLogger("*").TopRule().WriteToNil(LogLevel.Warn); }).GetCurrentClassLogger(); var target = logFactory.Configuration.AllTargets.OfType<DebugTarget>().FirstOrDefault(); Assert.Single(logFactory.Configuration.AllTargets); Assert.NotNull(target); logger.Fatal("Fatal Level"); Assert.Equal("Fatal Level", target.LastMessage); logger.Info("Info Level"); Assert.Equal("Fatal Level", target.LastMessage); } [Fact] public void SetupBuilder_FilterLevels() { var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => c.ForLogger().FilterLevels(LogLevel.Debug, LogLevel.Info).WriteTo(new DebugTarget() { Layout = "${message}" })).GetCurrentClassLogger(); var target = logFactory.Configuration.AllTargets.OfType<DebugTarget>().FirstOrDefault(); Assert.Single(logFactory.Configuration.AllTargets); Assert.NotNull(target); logger.Info("Info Level"); Assert.Equal("Info Level", target.LastMessage); logger.Trace("Trace Level"); Assert.Equal("Info Level", target.LastMessage); logger.Info("Debug Level"); Assert.Equal("Debug Level", target.LastMessage); logger.Warn("Warn Level"); Assert.Equal("Debug Level", target.LastMessage); } [Fact] public void SetupBuilder_FilterLevel() { var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => c.ForLogger().FilterLevel(LogLevel.Debug).WriteTo(new DebugTarget() { Layout = "${message}" })).GetCurrentClassLogger(); var target = logFactory.Configuration.AllTargets.OfType<DebugTarget>().FirstOrDefault(); Assert.Single(logFactory.Configuration.AllTargets); Assert.NotNull(target); logger.Debug("Debug Level"); Assert.Equal("Debug Level", target.LastMessage); logger.Trace("Trace Level"); Assert.Equal("Debug Level", target.LastMessage); logger.Trace("Error Level"); Assert.Equal("Debug Level", target.LastMessage); } [Fact] void SetupBuilder_FilterDynamicMethod() { var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => c.ForLogger().FilterMinLevel(LogLevel.Debug).FilterDynamic(evt => evt.Properties.ContainsKey("Enabled") ? NLog.Filters.FilterResult.Log : NLog.Filters.FilterResult.Ignore).WriteTo(new DebugTarget() { Layout = "${message}" })).GetCurrentClassLogger(); var target = logFactory.Configuration.AllTargets.OfType<DebugTarget>().FirstOrDefault(); Assert.Single(logFactory.Configuration.AllTargets); Assert.NotNull(target); logger.Debug("Debug Level {Enabled:l}", "Yes"); Assert.Equal("Debug Level Yes", target.LastMessage); logger.Info("Info Level No"); Assert.Equal("Debug Level Yes", target.LastMessage); logger.Info("Info Level {Enabled:l}", "Yes"); Assert.Equal("Info Level Yes", target.LastMessage); } [Fact] public void SetupBuilder_FilterDynamicLog() { var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => c.ForLogger().FilterDynamicLog(evt => evt.Properties.ContainsKey("Enabled")).WriteTo(new DebugTarget() { Layout = "${message}" })).GetCurrentClassLogger(); var target = logFactory.Configuration.AllTargets.OfType<DebugTarget>().FirstOrDefault(); Assert.Single(logFactory.Configuration.AllTargets); Assert.NotNull(target); logger.Debug("Debug Level {Enabled:l}", "Yes"); Assert.Equal("Debug Level Yes", target.LastMessage); logger.Info("Info Level No"); Assert.Equal("Debug Level Yes", target.LastMessage); logger.Info("Info Level {Enabled:l}", "Yes"); Assert.Equal("Info Level Yes", target.LastMessage); } [Fact] public void SetupBuilder_FilterDynamicIgnore() { var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => { c.ForLogger().FilterDynamicIgnore(evt => !evt.Properties.ContainsKey("Enabled")).WriteToNil(); c.ForLogger().WriteTo(new DebugTarget() { Layout = "${message}" }); }).GetCurrentClassLogger(); var target = logFactory.Configuration.AllTargets.OfType<DebugTarget>().FirstOrDefault(); Assert.NotNull(target); logger.Debug("Debug Level {Enabled:l}", "Yes"); Assert.Equal("Debug Level Yes", target.LastMessage); logger.Info("Info Level No"); Assert.Equal("Debug Level Yes", target.LastMessage); logger.Info("Info Level {Enabled:l}", "Yes"); Assert.Equal("Info Level Yes", target.LastMessage); } [Fact] public void SetupBuilder_MultipleTargets() { string lastMessage = null; var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => { c.ForLogger() .WriteTo(new DebugTarget() { Layout = "${message}" }) .WriteToMethodCall((evt, args) => lastMessage = evt.FormattedMessage); }).GetCurrentClassLogger(); var target = logFactory.Configuration.AllTargets.OfType<DebugTarget>().FirstOrDefault(); Assert.Equal(2, logFactory.Configuration.AllTargets.Count); Assert.NotNull(target); logger.Debug("Debug Level"); Assert.Equal("Debug Level", target.LastMessage); Assert.Equal("Debug Level", lastMessage); } [Fact] public void SetupBuilder_MultipleTargets2() { string lastMessage = null; var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => { c.ForLogger().WriteTo(new DebugTarget() { Layout = "${message}" }); c.ForLogger().WriteToMethodCall((evt, args) => lastMessage = evt.FormattedMessage); }).GetCurrentClassLogger(); var target = logFactory.Configuration.AllTargets.OfType<DebugTarget>().FirstOrDefault(); Assert.Equal(2, logFactory.Configuration.AllTargets.Count); Assert.NotNull(target); logger.Debug("Debug Level"); Assert.Equal("Debug Level", target.LastMessage); Assert.Equal("Debug Level", lastMessage); } [Fact] public void SetupBuilder_MultipleTargets3() { var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => { var debugTarget1 = new DebugTarget("debug1") { Layout = "${message}" }; var debugTarget2 = new DebugTarget("debug2") { Layout = "${message}" }; c.ForLogger().WriteTo(debugTarget1, debugTarget2).WithAsync(); }).GetCurrentClassLogger(); var target1 = logFactory.Configuration.FindTargetByName<DebugTarget>("debug1"); var target2 = logFactory.Configuration.FindTargetByName<DebugTarget>("debug2"); Assert.Equal(4, logFactory.Configuration.AllTargets.Count); Assert.NotNull(target1); Assert.NotNull(target2); logger.Debug("Debug Level"); logFactory.Flush(); Assert.Equal("Debug Level", target1.LastMessage); Assert.Equal("Debug Level", target2.LastMessage); } [Fact] public void SetupBuilder_ForTarget_WithName() { string lastMessage = null; var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => { var methodTarget = c.ForTarget("mymethod").WriteToMethodCall((evt, args) => lastMessage = evt.FormattedMessage).WithAsync().FirstTarget<MethodCallTarget>(); c.ForLogger().FilterLevel(LogLevel.Fatal).WriteTo(methodTarget); c.ForLogger("ErrorLogger").FilterLevel(LogLevel.Error).WriteTo(methodTarget); }).GetCurrentClassLogger(); var target = logFactory.Configuration.FindTargetByName<MethodCallTarget>("mymethod"); Assert.Equal(2, logFactory.Configuration.AllTargets.Count); Assert.NotNull(target); Assert.True(logger.IsFatalEnabled); Assert.False(logger.IsErrorEnabled); var errorLogger = logFactory.GetLogger("ErrorLogger"); Assert.True(errorLogger.IsFatalEnabled); Assert.True(errorLogger.IsErrorEnabled); logger.Fatal("Debug Level"); logFactory.Flush(); Assert.Equal("Debug Level", lastMessage); } [Fact] public void SetupBuilder_ForTarget_Group() { string lastMessage = null; var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => { var debugTargets = c.ForTarget().WriteToMethodCall((evt, args) => lastMessage = evt.FormattedMessage).WriteTo(new DebugTarget() { Layout = "${message}" }).WithAsync(); c.ForLogger().WriteTo(debugTargets); }).GetCurrentClassLogger(); var debugTarget = logFactory.Configuration.AllTargets.OfType<DebugTarget>().FirstOrDefault(); var methodTarget = logFactory.Configuration.AllTargets.OfType<MethodCallTarget>().FirstOrDefault(); Assert.Equal(4, logFactory.Configuration.AllTargets.Count); Assert.NotNull(debugTarget); Assert.NotNull(methodTarget); logger.Debug("Debug Level"); logFactory.Flush(); Assert.Equal("Debug Level", debugTarget.LastMessage); Assert.Equal("Debug Level", lastMessage); } [Fact] public void SetupBuilder_ForTargetWithName_ShouldFailForGroup() { var logFactory = new LogFactory(); Assert.Throws<ArgumentException>(() => logFactory.Setup().LoadConfiguration(c => c.ForTarget("OnlyOne").WriteTo(new DebugTarget() { Layout = "${message}" }).WriteTo(new DebugTarget() { Layout = "${message}" })) ); } [Fact] public void SetupBuilder_WithWrapperFirst_ShouldFail() { var logFactory = new LogFactory(); Assert.Throws<ArgumentException>(() => logFactory.Setup().LoadConfiguration(c => c.ForLogger().WithAsync().WriteTo(new DebugTarget() { Layout = "${message}" })) ); } [Fact] public void SetupBuilder_WriteToWithBuffering() { var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(new DebugTarget() { Layout = "${message}" }).WithBuffering()).GetCurrentClassLogger(); var target = logFactory.Configuration.AllTargets.OfType<DebugTarget>().FirstOrDefault(); Assert.Equal(2, logFactory.Configuration.AllTargets.Count); Assert.NotNull(target); logger.Debug("Debug Level"); Assert.Equal("", target.LastMessage ?? string.Empty); logFactory.Flush(); Assert.Equal("Debug Level", target.LastMessage); } [Fact] public void SetupBuilder_WriteToWithAutoFlush() { var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(new DebugTarget() { Layout = "${message}" }).WithBuffering().WithAutoFlush(evt => evt.Level == LogLevel.Error)).GetCurrentClassLogger(); var target = logFactory.Configuration.AllTargets.OfType<DebugTarget>().FirstOrDefault(); Assert.Equal(3, logFactory.Configuration.AllTargets.Count); Assert.NotNull(target); logger.Debug("Debug Level"); Assert.Equal("", target.LastMessage ?? string.Empty); logFactory.Flush(); Assert.Equal("Debug Level", target.LastMessage); logger.Error("Error Level"); Assert.Equal("Error Level", target.LastMessage); } [Fact] public void SetupBuilder_WriteToWithAsync() { var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => c.ForLogger().FilterLevel(LogLevel.Debug).WriteTo(new DebugTarget() { Layout = "${message}" }).WithAsync()).GetCurrentClassLogger(); var target = logFactory.Configuration.AllTargets.OfType<DebugTarget>().FirstOrDefault(); Assert.NotNull(logFactory.Configuration); Assert.Equal(2, logFactory.Configuration.AllTargets.Count); Assert.NotNull(target); logger.Debug("Debug Level"); logFactory.Flush(); Assert.Equal("Debug Level", target.LastMessage); } [Fact] public void SetupBuilder_WriteToWithFallback() { bool exceptionWasThrown = false; var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => { c.ForLogger() .WriteToMethodCall((evt, args) => { exceptionWasThrown = true; throw new Exception("Abort"); }) .WithFallback(new DebugTarget() { Layout = "${message}" }); }).GetCurrentClassLogger(); var target = logFactory.Configuration.AllTargets.OfType<DebugTarget>().FirstOrDefault(); Assert.NotNull(logFactory.Configuration); Assert.Equal(3, logFactory.Configuration.AllTargets.Count); Assert.NotNull(target); using (new NLogTestBase.NoThrowNLogExceptions()) { logger.Debug("Debug Level"); Assert.Equal("Debug Level", target.LastMessage); Assert.True(exceptionWasThrown); } } [Fact] public void SetupBuilder_WriteToWithRetry() { int methodCalls = 0; var logFactory = new LogFactory(); var logger = logFactory.Setup().LoadConfiguration(c => c.ForLogger().WriteToMethodCall((evt, args) => { if (methodCalls++ > 0) return; throw new Exception("Abort"); }).WithRetry()).GetCurrentClassLogger(); Assert.NotNull(logFactory.Configuration); Assert.Equal(2, logFactory.Configuration.AllTargets.Count); using (new NLogTestBase.NoThrowNLogExceptions()) { logger.Debug("Debug Level"); Assert.Equal(2, methodCalls); } } [Fact] public void SetupBuilder_LoadConfigEmbeddedResource() { var logFactory = new LogFactory(); var config = logFactory.Setup().LoadConfigurationFromAssemblyResource(typeof(LogFactorySetupTests).Assembly, "NLog.UnitTests.config").LogFactory.Configuration; Assert.NotNull(logFactory.Configuration); Assert.NotEmpty(logFactory.Configuration.Variables); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System.Collections.Generic; using System.Text; using NLog.Config; /// <summary> /// A specialized layout that renders LogEvent as JSON-Array /// </summary> /// <remarks> /// <a href="https://github.com/NLog/NLog/wiki/JsonArrayLayout">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/NLog/NLog/wiki/JsonArrayLayout">Documentation on NLog Wiki</seealso> [Layout("JsonArrayLayout")] [ThreadAgnostic] public class JsonArrayLayout : Layout { private Layout[] _precalculateLayouts = null; private IJsonConverter JsonConverter { get => _jsonConverter ?? (_jsonConverter = ResolveService<IJsonConverter>()); set => _jsonConverter = value; } private IJsonConverter _jsonConverter; /// <summary> /// Gets the array of items to include in JSON-Array /// </summary> /// <docgen category='Layout Options' order='10' /> [ArrayParameter(typeof(Layout), "item")] public IList<Layout> Items { get; } = new List<Layout>(); /// <summary> /// Gets or sets the option to suppress the extra spaces in the output json /// </summary> /// <docgen category='Layout Options' order='10' /> public bool SuppressSpaces { get; set; } /// <summary> /// Gets or sets the option to render the empty object value {} /// </summary> /// <docgen category='Layout Options' order='10' /> public bool RenderEmptyObject { get; set; } = true; /// <inheritdoc/> protected override void InitializeLayout() { base.InitializeLayout(); _precalculateLayouts = ResolveLayoutPrecalculation(Items); } /// <inheritdoc/> protected override void CloseLayout() { JsonConverter = null; _precalculateLayouts = null; base.CloseLayout(); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { PrecalculateBuilderInternal(logEvent, target, _precalculateLayouts); } /// <inheritdoc/> protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { int orgLength = target.Length; RenderJsonFormattedMessage(logEvent, target); if (target.Length == orgLength && RenderEmptyObject) { target.Append(SuppressSpaces ? "[]" : "[ ]"); } } /// <inheritdoc/> protected override string GetFormattedMessage(LogEventInfo logEvent) { return RenderAllocateBuilder(logEvent); } private void RenderJsonFormattedMessage(LogEventInfo logEvent, StringBuilder sb) { int orgLength = sb.Length; //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < Items.Count; i++) { var layout = Items[i]; int beforeDelimeterLength = sb.Length; if (beforeDelimeterLength == orgLength) sb.Append(SuppressSpaces ? "[" : "[ "); else sb.Append(SuppressSpaces ? "," : ", "); if (!RenderLayoutJsonValue(logEvent, layout, sb)) { sb.Length = beforeDelimeterLength; } } if (sb.Length != orgLength) { sb.Append(SuppressSpaces ? "]" : " ]"); } } private bool RenderLayoutJsonValue(LogEventInfo logEvent, Layout layout, StringBuilder sb) { int beforeValueLength = sb.Length; if (layout is JsonLayout) { layout.Render(logEvent, sb); } else if (layout.TryGetRawValue(logEvent, out object rawValue)) { if (!JsonConverter.SerializeObject(rawValue, sb)) { return false; } } else { sb.Append('"'); beforeValueLength = sb.Length; layout.Render(logEvent, sb); if (beforeValueLength != sb.Length) { NLog.Targets.DefaultJsonSerializer.PerformJsonEscapeWhenNeeded(sb, beforeValueLength, true, false); sb.Append('"'); } } return beforeValueLength != sb.Length; } /// <inheritdoc/> public override string ToString() { return ToStringWithNestedItems(Items, l => l.ToString()); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.IO; using System.Text; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; /// <summary> /// Renders contents of the specified file. /// </summary> [LayoutRenderer("file-contents")] public class FileContentsLayoutRenderer : LayoutRenderer { private readonly object _lockObject = new object(); private string _lastFileName; private string _currentFileContents; /// <summary> /// Initializes a new instance of the <see cref="FileContentsLayoutRenderer" /> class. /// </summary> public FileContentsLayoutRenderer() { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 Encoding = Encoding.Default; #else Encoding = Encoding.UTF8; #endif _lastFileName = string.Empty; } /// <summary> /// Gets or sets the name of the file. /// </summary> /// <docgen category='File Options' order='10' /> [DefaultParameter] public Layout FileName { get; set; } /// <summary> /// Gets or sets the encoding used in the file. /// </summary> /// <value>The encoding.</value> /// <docgen category='File Options' order='10' /> public Encoding Encoding { get; set; } /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { lock (_lockObject) { string fileName = FileName.Render(logEvent); if (fileName != _lastFileName) { _currentFileContents = ReadFileContents(fileName); _lastFileName = fileName; } } builder.Append(_currentFileContents); } private string ReadFileContents(string fileName) { try { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 using (var reader = new StreamReader(fileName, Encoding)) { return reader.ReadToEnd(); } #else return File.ReadAllText(fileName, Encoding); #endif } catch (Exception exception) { InternalLogger.Error(exception, "Cannot read file contents of '{0}'.", fileName); if (exception.MustBeRethrown()) { throw; } return string.Empty; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests { using NLog.MessageTemplates; using Xunit; public class LogMessageFormatterTests : NLogTestBase { [Fact] public void ExtensionsLoggingFormatTest() { LogEventInfo logEventInfo = new LogEventInfo(LogLevel.Info, "MyLogger", "Login request from {Username} for {Application}", new[] { new MessageTemplateParameter("Username", "John", null, CaptureType.Normal), new MessageTemplateParameter("Application", "BestApplicationEver", null, CaptureType.Normal) }); logEventInfo.Parameters = new object[] { "Login request from John for BestApplicationEver" }; logEventInfo.MessageFormatter = (logEvent) => { if (logEvent.Parameters != null && logEvent.Parameters.Length > 0) { return logEvent.Parameters[logEvent.Parameters.Length - 1] as string ?? logEvent.Message; } return logEvent.Message; }; var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' > <layout type='JsonLayout' IncludeAllProperties='true'> <attribute name='LogMessage' layout='${message:raw=true}' /> </layout> </target> </targets> <rules> <logger name='*' levels='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Log(logEventInfo); logFactory.AssertDebugLastMessage("{ \"LogMessage\": \"Login request from {Username} for {Application}\", \"Username\": \"John\", \"Application\": \"BestApplicationEver\" }"); Assert.Equal("Login request from John for BestApplicationEver", logEventInfo.FormattedMessage); AssertContainsInDictionary(logEventInfo.Properties, "Username", "John"); AssertContainsInDictionary(logEventInfo.Properties, "Application", "BestApplicationEver"); Assert.Contains(new MessageTemplateParameter("Username", "John", null, CaptureType.Normal), logEventInfo.MessageTemplateParameters); Assert.Contains(new MessageTemplateParameter("Application", "BestApplicationEver", null, CaptureType.Normal), logEventInfo.MessageTemplateParameters); } [Fact] public void ExtensionsLoggingPreFormatTest() { LogEventInfo logEventInfo = new LogEventInfo(LogLevel.Info, "MyLogger", "Login request from John for BestApplicationEver", "Login request from {Username} for {Application}", new[] { new MessageTemplateParameter("Username", "John", null, CaptureType.Normal), new MessageTemplateParameter("Application", "BestApplicationEver", null, CaptureType.Normal) }); var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' > <layout type='JsonLayout' IncludeAllProperties='true'> <attribute name='LogMessage' layout='${message:raw=true}' /> </layout> </target> </targets> <rules> <logger name='*' levels='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Log(logEventInfo); logFactory.AssertDebugLastMessage("{ \"LogMessage\": \"Login request from {Username} for {Application}\", \"Username\": \"John\", \"Application\": \"BestApplicationEver\" }"); Assert.Equal("Login request from John for BestApplicationEver", logEventInfo.FormattedMessage); AssertContainsInDictionary(logEventInfo.Properties, "Username", "John"); AssertContainsInDictionary(logEventInfo.Properties, "Application", "BestApplicationEver"); Assert.Contains(new MessageTemplateParameter("Username", "John", null, CaptureType.Normal), logEventInfo.MessageTemplateParameters); Assert.Contains(new MessageTemplateParameter("Application", "BestApplicationEver", null, CaptureType.Normal), logEventInfo.MessageTemplateParameters); } [Fact] public void NormalStringFormatTest() { LogEventInfo logEventInfo = new LogEventInfo(LogLevel.Info, "MyLogger", null, "{0:X} - Login request from {1} for {2} with userid {0}", new object[] { 42, "John", "BestApplicationEver" }); var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' > <layout type='JsonLayout' IncludeAllProperties='true'> <attribute name='LogMessage' layout='${message:raw=true}' /> </layout> </target> </targets> <rules> <logger name='*' levels='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Log(logEventInfo); logFactory.AssertDebugLastMessage("{ \"LogMessage\": \"{0:X} - Login request from {1} for {2} with userid {0}\" }"); Assert.Equal("2A - Login request from John for BestApplicationEver with userid 42", logEventInfo.FormattedMessage); Assert.Contains(new MessageTemplateParameter("0", 42, "X", CaptureType.Normal), logEventInfo.MessageTemplateParameters); Assert.Contains(new MessageTemplateParameter("1", "John", null, CaptureType.Normal), logEventInfo.MessageTemplateParameters); Assert.Contains(new MessageTemplateParameter("2", "BestApplicationEver", null, CaptureType.Normal), logEventInfo.MessageTemplateParameters); Assert.Contains(new MessageTemplateParameter("0", 42, null, CaptureType.Normal), logEventInfo.MessageTemplateParameters); } [Fact] public void MessageTemplateFormatTest() { LogEventInfo logEventInfo = new LogEventInfo(LogLevel.Info, "MyLogger", null, "Login request from {@Username} for {Application:l}", new object[] { "John", "BestApplicationEver" }); var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' > <layout type='JsonLayout' IncludeAllProperties='true'> <attribute name='LogMessage' layout='${message:raw=true}' /> </layout> </target> </targets> <rules> <logger name='*' levels='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Log(logEventInfo); logFactory.AssertDebugLastMessage("{ \"LogMessage\": \"Login request from {@Username} for {Application:l}\", \"Username\": \"John\", \"Application\": \"BestApplicationEver\" }"); Assert.Equal("Login request from \"John\" for BestApplicationEver", logEventInfo.FormattedMessage); AssertContainsInDictionary(logEventInfo.Properties, "Username", "John"); AssertContainsInDictionary(logEventInfo.Properties, "Application", "BestApplicationEver"); Assert.Contains(new MessageTemplateParameter("Username", "John", null, CaptureType.Serialize), logEventInfo.MessageTemplateParameters); Assert.Contains(new MessageTemplateParameter("Application", "BestApplicationEver", "l", CaptureType.Normal), logEventInfo.MessageTemplateParameters); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #if !NET35 && !NET40 && !NETSTANDARD1_3 && !NETSTANDARD1_5 using System.Dynamic; #endif using System.Linq; using System.Reflection; using NLog.Common; using NLog.Config; /// <summary> /// Converts object into a List of property-names and -values using reflection /// </summary> internal class ObjectReflectionCache : IObjectTypeTransformer { private MruCache<Type, ObjectPropertyInfos> ObjectTypeCache => _objectTypeCache ?? System.Threading.Interlocked.CompareExchange(ref _objectTypeCache, new MruCache<Type, ObjectPropertyInfos>(10000), null) ?? _objectTypeCache; private MruCache<Type, ObjectPropertyInfos> _objectTypeCache; private readonly IServiceProvider _serviceProvider; private IObjectTypeTransformer ObjectTypeTransformation => _objectTypeTransformation ?? (_objectTypeTransformation = _serviceProvider?.GetService<IObjectTypeTransformer>() ?? this); private IObjectTypeTransformer _objectTypeTransformation; public ObjectReflectionCache(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } object IObjectTypeTransformer.TryTransformObject(object obj) { return null; } public ObjectPropertyList LookupObjectProperties(object value) { if (TryLookupExpandoObject(value, out var propertyValues)) { return propertyValues; } if (!ReferenceEquals(ObjectTypeTransformation, this)) { var result = ObjectTypeTransformation.TryTransformObject(value); if (result != null) { if (result is IConvertible) { return new ObjectPropertyList(result, ObjectPropertyInfos.SimpleToString.Properties, ObjectPropertyInfos.SimpleToString.FastLookup); } if (TryLookupExpandoObject(result, out propertyValues)) { return propertyValues; } value = result; } } var objectType = value.GetType(); var propertyInfos = ConvertSimpleToString(objectType) ? ObjectPropertyInfos.SimpleToString : BuildObjectPropertyInfos(value); ObjectTypeCache.TryAddValue(objectType, propertyInfos); return new ObjectPropertyList(value, propertyInfos.Properties, propertyInfos.FastLookup); } /// <summary> /// Try get value from <paramref name="value"/>, using <paramref name="objectPath"/>, and set into <paramref name="foundValue"/> /// </summary> public bool TryGetObjectProperty(object value, string[] objectPath, out object foundValue) { foundValue = null; if (objectPath is null) { return false; } for (int i = 0; i < objectPath.Length; ++i) { if (value is null) { return false; } var propertyList = LookupObjectProperties(value); if (propertyList.TryGetPropertyValue(objectPath[i], out var propertyValue)) { value = propertyValue.Value; } else { foundValue = null; return false; //Wrong, but done } } foundValue = value; return true; } [UnconditionalSuppressMessage("Trimming - Allow reflection of message args", "IL2072")] [UnconditionalSuppressMessage("Trimming - Allow reflection of message args", "IL2075")] public bool TryLookupExpandoObject(object value, out ObjectPropertyList objectPropertyList) { if (value is IDictionary<string, object> expando) { objectPropertyList = new ObjectPropertyList(expando); return true; } #if !NET35 && !NET40 && !NETSTANDARD1_3 && !NETSTANDARD1_5 if (value is DynamicObject d) { var dictionary = DynamicObjectToDict(d); objectPropertyList = new ObjectPropertyList(dictionary); return true; } #endif Type objectType = value.GetType(); if (ObjectTypeCache.TryGetValue(objectType, out var propertyInfos)) { if (!propertyInfos.HasFastLookup) { var fastLookup = BuildFastLookup(propertyInfos.Properties, false); propertyInfos = new ObjectPropertyInfos(propertyInfos.Properties, fastLookup); ObjectTypeCache.TryAddValue(objectType, propertyInfos); } objectPropertyList = new ObjectPropertyList(value, propertyInfos.Properties, propertyInfos.FastLookup); return true; } foreach (var interfaceType in value.GetType().GetInterfaces()) { if (IsGenericDictionaryEnumeratorType(interfaceType)) { var dictionaryEnumerator = (IDictionaryEnumerator)Activator.CreateInstance(typeof(DictionaryEnumerator<,>).MakeGenericType(interfaceType.GetGenericArguments())); propertyInfos = new ObjectPropertyInfos(null, new[] { new FastPropertyLookup(string.Empty, TypeCode.Object, (o, p) => dictionaryEnumerator.GetEnumerator(o)) }); ObjectTypeCache.TryAddValue(objectType, propertyInfos); objectPropertyList = new ObjectPropertyList(value, propertyInfos.Properties, propertyInfos.FastLookup); return true; } } objectPropertyList = default(ObjectPropertyList); return false; } [UnconditionalSuppressMessage("Trimming - Allow reflection of message args", "IL2072")] private static ObjectPropertyInfos BuildObjectPropertyInfos(object value) { var properties = GetPublicProperties(value.GetType()); if (value is Exception) { // Special handling of Exception (Include Exception-Type as artificial first property) var fastLookup = BuildFastLookup(properties, true); return new ObjectPropertyInfos(properties, fastLookup); } else if (properties.Length == 0) { return ObjectPropertyInfos.SimpleToString; } else { return new ObjectPropertyInfos(properties, null); } } private static bool ConvertSimpleToString(Type objectType) { if (typeof(IFormattable).IsAssignableFrom(objectType)) return true; if (typeof(Uri).IsAssignableFrom(objectType)) return true; if (typeof(Delegate).IsAssignableFrom(objectType)) return true; // Skip serializing all types in the application if (typeof(MemberInfo).IsAssignableFrom(objectType)) return true; // Skip serializing all types in the application if (typeof(Assembly).IsAssignableFrom(objectType)) return true; // Skip serializing all types in the application if (typeof(Module).IsAssignableFrom(objectType)) return true; // Skip serializing all types in the application if (typeof(System.IO.Stream).IsAssignableFrom(objectType)) return true; // Skip serializing properties that often throws exceptions if (typeof(System.Net.IPAddress).IsAssignableFrom(objectType)) return true; // Skip serializing properties that often throws exceptions return false; } private static PropertyInfo[] GetPublicProperties([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] Type type) { PropertyInfo[] properties = null; try { properties = type.GetProperties(PublicProperties); } catch (Exception ex) { InternalLogger.Warn(ex, "Failed to get object properties for type: {0}", type); } // Skip Index-Item-Properties (Ex. public string this[int Index]) if (properties != null) { foreach (var prop in properties) { if (!prop.IsValidPublicProperty()) { properties = properties.Where(p => p.IsValidPublicProperty()).ToArray(); break; } } } return properties ?? ArrayHelper.Empty<PropertyInfo>(); } private static FastPropertyLookup[] BuildFastLookup(PropertyInfo[] properties, bool includeType) { int fastAccessIndex = includeType ? 1 : 0; FastPropertyLookup[] fastLookup = new FastPropertyLookup[properties.Length + fastAccessIndex]; if (includeType) { fastLookup[0] = new FastPropertyLookup("Type", TypeCode.String, (o, p) => o.GetType().ToString()); } foreach (var prop in properties) { var getterMethod = prop.GetGetMethod(); Type propertyType = getterMethod.ReturnType; ReflectionHelpers.LateBoundMethod valueLookup = ReflectionHelpers.CreateLateBoundMethod(getterMethod); #if NETSTANDARD1_3 TypeCode typeCode = propertyType == typeof(string) ? TypeCode.String : (propertyType == typeof(int) ? TypeCode.Int32 : TypeCode.Object); #else TypeCode typeCode = Type.GetTypeCode(propertyType); // Skip cyclic-reference checks when not TypeCode.Object #endif fastLookup[fastAccessIndex++] = new FastPropertyLookup(prop.Name, typeCode, valueLookup); } return fastLookup; } private const BindingFlags PublicProperties = BindingFlags.Instance | BindingFlags.Public; internal struct ObjectPropertyList : IEnumerable<ObjectPropertyList.PropertyValue> { internal static readonly StringComparer NameComparer = StringComparer.Ordinal; private static readonly FastPropertyLookup[] CreateIDictionaryEnumerator = new[] { new FastPropertyLookup(string.Empty, TypeCode.Object, (o, p) => ((IDictionary<string, object>)o).GetEnumerator()) }; private readonly object _object; private readonly PropertyInfo[] _properties; private readonly FastPropertyLookup[] _fastLookup; public struct PropertyValue { public readonly string Name; public readonly object Value; public TypeCode TypeCode => Value is null ? TypeCode.Empty : _typecode; private readonly TypeCode _typecode; public bool HasNameAndValue => Name != null && Value != null; public PropertyValue(string name, object value, TypeCode typeCode) { Name = name; Value = value; _typecode = typeCode; } public PropertyValue(object owner, PropertyInfo propertyInfo) { Name = propertyInfo.Name; Value = propertyInfo.GetValue(owner, null); _typecode = TypeCode.Object; } public PropertyValue(object owner, FastPropertyLookup fastProperty) { Name = fastProperty.Name; Value = fastProperty.ValueLookup(owner, null); _typecode = fastProperty.TypeCode; } } public bool IsSimpleValue => _properties?.Length == 0; public object ObjectValue => _object; internal ObjectPropertyList(object value, PropertyInfo[] properties, FastPropertyLookup[] fastLookup) { _object = value; _properties = properties; _fastLookup = fastLookup; } public ObjectPropertyList(IDictionary<string, object> value) { _object = value; // Expando objects _properties = null; _fastLookup = CreateIDictionaryEnumerator; } public bool TryGetPropertyValue(string name, out PropertyValue propertyValue) { if (_properties != null) { if (_fastLookup != null) { return TryFastLookupPropertyValue(name, out propertyValue); } else { return TrySlowLookupPropertyValue(name, out propertyValue); } } else if (_object is IDictionary<string, object> expandoObject) { if (expandoObject.TryGetValue(name, out var objectValue)) { propertyValue = new PropertyValue(name, objectValue, TypeCode.Object); return true; } propertyValue = default(PropertyValue); return false; } else { return TryListLookupPropertyValue(name, out propertyValue); } } /// <summary> /// Scans properties for name (Skips string-compare and value-lookup until finding match) /// </summary> private bool TryFastLookupPropertyValue(string name, out PropertyValue propertyValue) { int nameHashCode = NameComparer.GetHashCode(name); foreach (var fastProperty in _fastLookup) { if (fastProperty.NameHashCode == nameHashCode && NameComparer.Equals(fastProperty.Name, name)) { propertyValue = new PropertyValue(_object, fastProperty); return true; } } propertyValue = default(PropertyValue); return false; } /// <summary> /// Scans properties for name (Skips property value lookup until finding match) /// </summary> private bool TrySlowLookupPropertyValue(string name, out PropertyValue propertyValue) { foreach (var propInfo in _properties) { if (NameComparer.Equals(propInfo.Name, name)) { propertyValue = new PropertyValue(_object, propInfo); return true; } } propertyValue = default(PropertyValue); return false; } /// <summary> /// Scans properties for name /// </summary> private bool TryListLookupPropertyValue(string name, out PropertyValue propertyValue) { foreach (var item in this) { if (NameComparer.Equals(item.Name, name)) { propertyValue = item; return true; } } propertyValue = default(PropertyValue); return false; } public override string ToString() { return _object?.ToString() ?? "null"; } public Enumerator GetEnumerator() { if (_properties != null) return new Enumerator(_object, _properties, _fastLookup); else return new Enumerator((IEnumerator<KeyValuePair<string, object>>)_fastLookup[0].ValueLookup(_object, null)); } IEnumerator<PropertyValue> IEnumerable<PropertyValue>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public struct Enumerator : IEnumerator<PropertyValue> { private readonly object _owner; private readonly PropertyInfo[] _properties; private readonly FastPropertyLookup[] _fastLookup; private readonly IEnumerator<KeyValuePair<string, object>> _enumerator; private int _index; internal Enumerator(object owner, PropertyInfo[] properties, FastPropertyLookup[] fastLookup) { _owner = owner; _properties = properties; _fastLookup = fastLookup; _index = -1; _enumerator = null; } internal Enumerator(IEnumerator<KeyValuePair<string, object>> enumerator) { _owner = enumerator; _properties = null; _fastLookup = null; _index = 0; _enumerator = enumerator; } public PropertyValue Current { get { try { if (_fastLookup != null) return new PropertyValue(_owner, _fastLookup[_index]); else if (_properties != null) return new PropertyValue(_owner, _properties[_index]); else return new PropertyValue(_enumerator.Current.Key, _enumerator.Current.Value, TypeCode.Object); } catch (Exception ex) { InternalLogger.Debug(ex, "Failed to get property value for object: {0}", _owner); return default(PropertyValue); } } } object IEnumerator.Current => Current; public void Dispose() { _enumerator?.Dispose(); } public bool MoveNext() { if (_properties != null) return ++_index < (_fastLookup?.Length ?? _properties.Length); else return _enumerator.MoveNext(); } public void Reset() { if (_properties != null) _index = -1; else _enumerator.Reset(); } } } internal struct FastPropertyLookup { public readonly string Name; public readonly ReflectionHelpers.LateBoundMethod ValueLookup; public readonly TypeCode TypeCode; public readonly int NameHashCode; public FastPropertyLookup(string name, TypeCode typeCode, ReflectionHelpers.LateBoundMethod valueLookup) { Name = name; ValueLookup = valueLookup; TypeCode = typeCode; NameHashCode = ObjectPropertyList.NameComparer.GetHashCode(name); } } private struct ObjectPropertyInfos : IEquatable<ObjectPropertyInfos> { public readonly PropertyInfo[] Properties; public readonly FastPropertyLookup[] FastLookup; public static readonly ObjectPropertyInfos SimpleToString = new ObjectPropertyInfos(ArrayHelper.Empty<PropertyInfo>(), ArrayHelper.Empty<FastPropertyLookup>()); public ObjectPropertyInfos(PropertyInfo[] properties, FastPropertyLookup[] fastLookup) { Properties = properties; FastLookup = fastLookup; } public bool HasFastLookup => FastLookup != null; public bool Equals(ObjectPropertyInfos other) { return ReferenceEquals(Properties, other.Properties) && FastLookup?.Length == other.FastLookup?.Length; } } #if !NET35 && !NET40 && !NETSTANDARD1_3 && !NETSTANDARD1_5 private static Dictionary<string, object> DynamicObjectToDict(DynamicObject d) { var newVal = new Dictionary<string, object>(); foreach (var propName in d.GetDynamicMemberNames()) { if (d.TryGetMember(new GetBinderAdapter(propName), out var result)) { newVal[propName] = result; } } return newVal; } /// <summary> /// Binder for retrieving value of <see cref="DynamicObject"/> /// </summary> private sealed class GetBinderAdapter : GetMemberBinder { internal GetBinderAdapter(string name) : base(name, false) { } /// <inheritdoc/> public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { return target; } } #endif private static bool IsGenericDictionaryEnumeratorType(Type interfaceType) { if (interfaceType.IsGenericType()) { if (interfaceType.GetGenericTypeDefinition() == typeof(IDictionary<,>) #if !NET35 || interfaceType.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<,>) #endif ) { if (interfaceType.GetGenericArguments()[0] == typeof(string)) { return true; } } } return false; } private interface IDictionaryEnumerator { IEnumerator<KeyValuePair<string,object>> GetEnumerator(object value); } internal sealed class DictionaryEnumerator<TKey, TValue> : IDictionaryEnumerator { public IEnumerator<KeyValuePair<string, object>> GetEnumerator(object value) { if (value is IDictionary<TKey, TValue> dictionary) { if (dictionary.Count > 0) return YieldEnumerator(dictionary); } #if !NET35 else if (value is IReadOnlyDictionary<TKey, TValue> readonlyDictionary) { if (readonlyDictionary.Count > 0) return YieldEnumerator(readonlyDictionary); } #endif return EmptyDictionaryEnumerator.Default; } private IEnumerator<KeyValuePair<string, object>> YieldEnumerator(IDictionary<TKey,TValue> dictionary) { foreach (var item in dictionary) yield return new KeyValuePair<string, object>(item.Key.ToString(), item.Value); } #if !NET35 private IEnumerator<KeyValuePair<string, object>> YieldEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary) { foreach (var item in dictionary) yield return new KeyValuePair<string, object>(item.Key.ToString(), item.Value); } #endif private sealed class EmptyDictionaryEnumerator : IEnumerator<KeyValuePair<string, object>> { public static readonly EmptyDictionaryEnumerator Default = new EmptyDictionaryEnumerator(); KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current => default(KeyValuePair<string, object>); object IEnumerator.Current => default(KeyValuePair<string, object>); bool IEnumerator.MoveNext() => false; void IDisposable.Dispose() { // Nothing here on purpose } void IEnumerator.Reset() { // Nothing here on purpose } } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal.FileAppenders { using System; using System.IO; using System.Threading; using NLog.Common; /// <summary> /// Maintains a collection of file appenders usually associated with file targets. /// </summary> internal sealed class FileAppenderCache : IFileAppenderCache { private readonly BaseFileAppender[] _appenders; private Timer _autoClosingTimer; #if !NETSTANDARD1_3 private string _archiveFilePatternToWatch; private readonly MultiFileWatcher _externalFileArchivingWatcher = new MultiFileWatcher(NotifyFilters.DirectoryName | NotifyFilters.FileName); private bool _logFileWasArchived; #endif /// <summary> /// An "empty" instance of the <see cref="FileAppenderCache"/> class with zero size and empty list of appenders. /// </summary> public static readonly FileAppenderCache Empty = new FileAppenderCache(); /// <summary> /// Initializes a new "empty" instance of the <see cref="FileAppenderCache"/> class with zero size and empty /// list of appenders. /// </summary> private FileAppenderCache() : this(0, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="FileAppenderCache"/> class. /// </summary> /// <remarks> /// The size of the list should be positive. No validations are performed during initialization as it is an /// internal class. /// </remarks> /// <param name="size">Total number of appenders allowed in list.</param> /// <param name="appenderFactory">Factory used to create each appender.</param> /// <param name="createFileParams">Parameters used for creating a file.</param> public FileAppenderCache(int size, IFileAppenderFactory appenderFactory, ICreateFileParameters createFileParams) { Size = size; Factory = appenderFactory; CreateFileParameters = createFileParams; _appenders = new BaseFileAppender[Size]; _autoClosingTimer = new Timer(AutoClosingTimerCallback, null, Timeout.Infinite, Timeout.Infinite); #if !NETSTANDARD1_3 _externalFileArchivingWatcher.FileChanged += ExternalFileArchivingWatcher_OnFileChanged; #endif } #if !NETSTANDARD1_3 private void ExternalFileArchivingWatcher_OnFileChanged(object sender, FileSystemEventArgs e) { if (_logFileWasArchived || CheckCloseAppenders is null || _autoClosingTimer is null) { return; } if ((e.ChangeType & (WatcherChangeTypes.Deleted | WatcherChangeTypes.Renamed)) != 0) { _logFileWasArchived = true; // File Appender file deleted/renamed } else if ((e.ChangeType & (WatcherChangeTypes.Created)) != 0) { if (FileArchiveFolderChanged(e.FullPath)) { _logFileWasArchived = true; // Something was created in the archive folder } } if (_logFileWasArchived) { _autoClosingTimer?.Change(50, Timeout.Infinite); } } private bool FileArchiveFolderChanged(string fullPath) { if (!string.IsNullOrEmpty(_archiveFilePatternToWatch) && !string.IsNullOrEmpty(fullPath)) { string archiveFolderPath = Path.GetDirectoryName(_archiveFilePatternToWatch); string currentFolderPath = Path.GetDirectoryName(fullPath); if (!string.IsNullOrEmpty(archiveFolderPath) && !string.IsNullOrEmpty(currentFolderPath)) { return string.Equals(Path.GetFullPath(archiveFolderPath), Path.GetFullPath(currentFolderPath), StringComparison.OrdinalIgnoreCase); } } return false; } /// <summary> /// The archive file path pattern that is used to detect when archiving occurs. /// </summary> public string ArchiveFilePatternToWatch { get => _archiveFilePatternToWatch; set { if (_archiveFilePatternToWatch != value) { if (!string.IsNullOrEmpty(_archiveFilePatternToWatch)) { _externalFileArchivingWatcher.StopWatching(_archiveFilePatternToWatch); } _archiveFilePatternToWatch = value; _logFileWasArchived = false; } } } /// <summary> /// Invalidates appenders for all files that were archived. /// </summary> public void InvalidateAppendersForArchivedFiles() { if (_logFileWasArchived) { _logFileWasArchived = false; InternalLogger.Trace("{0}: Invalidate archived files", CreateFileParameters); CloseAppenders("Cleanup Archive"); } } #endif private void AutoClosingTimerCallback(object state) { var checkCloseAppenders = CheckCloseAppenders; if (checkCloseAppenders != null) { checkCloseAppenders(this, EventArgs.Empty); } } /// <summary> /// Gets the parameters which will be used for creating a file. /// </summary> public ICreateFileParameters CreateFileParameters { get; private set; } /// <summary> /// Gets the file appender factory used by all the appenders in this list. /// </summary> public IFileAppenderFactory Factory { get; private set; } /// <summary> /// Gets the number of appenders which the list can hold. /// </summary> public int Size { get; private set; } /// <summary> /// Subscribe to background monitoring of active file appenders /// </summary> public event EventHandler CheckCloseAppenders; /// <summary> /// It allocates the first slot in the list when the file name does not already in the list and clean up any /// unused slots. /// </summary> /// <param name="fileName">File name associated with a single appender.</param> /// <returns>The allocated appender.</returns> public BaseFileAppender AllocateAppender(string fileName) { // // BaseFileAppender.Write is the most expensive operation here // so the in-memory data structure doesn't have to be // very sophisticated. It's a table-based LRU, where we move // the used element to become the first one. // The number of items is usually very limited so the // performance should be equivalent to the one of the hashtable. // BaseFileAppender appenderToWrite = null; int freeSpot = _appenders.Length - 1; for (int i = 0; i < _appenders.Length; ++i) { // Use empty slot in recent appender list, if there is one. if (_appenders[i] is null) { freeSpot = i; break; } if (string.Equals(_appenders[i].FileName, fileName, StringComparison.OrdinalIgnoreCase)) { // found it, move it to the first place on the list // (MRU) BaseFileAppender app = _appenders[i]; if (i > 0) { // file open has a chance of failure // if it fails in the constructor, we won't modify any data structures for (int j = i; j > 0; --j) { _appenders[j] = _appenders[j - 1]; } _appenders[0] = app; } appenderToWrite = app; break; } } if (appenderToWrite is null) { appenderToWrite = CreateAppender(fileName, freeSpot); } return appenderToWrite; } private BaseFileAppender CreateAppender(string fileName, int freeSpot) { BaseFileAppender appenderToWrite; try { InternalLogger.Debug("{0}: Creating file appender: '{1}'", CreateFileParameters, fileName); BaseFileAppender newAppender = Factory.Open(fileName, CreateFileParameters); if (_appenders[freeSpot] != null) { CloseAppender(_appenders[freeSpot], "Stale", false); _appenders[freeSpot] = null; } for (int j = freeSpot; j > 0; --j) { _appenders[j] = _appenders[j - 1]; } _appenders[0] = newAppender; appenderToWrite = newAppender; #if !NETSTANDARD1_3 if (CheckCloseAppenders != null) { if (freeSpot == 0) _logFileWasArchived = false; if (!string.IsNullOrEmpty(_archiveFilePatternToWatch)) { string directoryPath = Path.GetDirectoryName(_archiveFilePatternToWatch); if (!string.IsNullOrEmpty(directoryPath)) { if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath); _externalFileArchivingWatcher.Watch(_archiveFilePatternToWatch); // Always monitor the archive-folder } } _externalFileArchivingWatcher.Watch(appenderToWrite.FileName); // Monitor the active file-appender } #endif } catch (Exception ex) { InternalLogger.Warn(ex, "{0}: Failed to create file appender: {1}", CreateFileParameters, fileName); throw; } return appenderToWrite; } /// <summary> /// Close all the allocated appenders. /// </summary> public void CloseAppenders(string reason) { CloseAllAppenders(0, reason); } private void CloseAllAppenders(int startIndex, string reason) { for (int i = startIndex; i < _appenders.Length; ++i) { var oldAppender = _appenders[i]; if (oldAppender is null) { break; } CloseAppender(oldAppender, reason, i == 0); _appenders[i] = null; oldAppender.Dispose(); // Dispose of Archive Mutex } } /// <summary> /// Close the allocated appenders initialized before the supplied time. /// </summary> /// <param name="expireTimeUtc">The time which prior the appenders considered expired</param> public void CloseExpiredAppenders(DateTime expireTimeUtc) { #if !NETSTANDARD1_3 if (_logFileWasArchived) { _logFileWasArchived = false; CloseAppenders("Cleanup Timer"); } else #endif { if (expireTimeUtc != DateTime.MinValue) { for (int i = 0; i < _appenders.Length; ++i) { if (_appenders[i] is null) { break; } if (_appenders[i].OpenTimeUtc < expireTimeUtc) { CloseAllAppenders(i, "Expired"); break; } } } } } /// <summary> /// Flush all the allocated appenders. /// </summary> public void FlushAppenders() { foreach (BaseFileAppender appender in _appenders) { if (appender is null) { break; } try { appender.Flush(); } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed to flush file '{1}'.", CreateFileParameters, appender.FileName); InvalidateAppender(appender.FileName)?.Dispose(); throw; } } } private BaseFileAppender GetAppender(string fileName) { for (int i = 0; i < _appenders.Length; ++i) { BaseFileAppender appender = _appenders[i]; if (appender is null) break; if (string.Equals(appender.FileName, fileName, StringComparison.OrdinalIgnoreCase)) return appender; } return null; } public DateTime? GetFileCreationTimeSource(string filePath, DateTime? fallbackTimeSource = null) { var appender = GetAppender(filePath); DateTime? result = null; if (appender != null) { try { result = appender.GetFileCreationTimeUtc(); if (result.HasValue) { // Check if cached value is still valid, and update if not (Will automatically update CreationTimeSource) DateTime cachedTimeUtc = appender.CreationTimeUtc; if (result.Value != cachedTimeUtc) { appender.CreationTimeUtc = result.Value; } return appender.CreationTimeSource; } } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed to get file creation time for file '{1}'.", CreateFileParameters, appender.FileName); InvalidateAppender(appender.FileName)?.Dispose(); throw; } } var fileInfo = new FileInfo(filePath); if (fileInfo.Exists) { result = fileInfo.LookupValidFileCreationTimeUtc(fallbackTimeSource); return Time.TimeSource.Current.FromSystemTime(result.Value); } return result; } /// <summary> /// File Archive Logic uses the File-Creation-TimeStamp to detect if time to archive, and the File-LastWrite-Timestamp to name the archive-file. /// </summary> /// <remarks> /// NLog always closes all relevant appenders during archive operation, so no need to lookup file-appender /// </remarks> public DateTime? GetFileLastWriteTimeUtc(string filePath) { var fileInfo = new FileInfo(filePath); if (fileInfo.Exists) { return fileInfo.GetLastWriteTimeUtc(); } return null; } public long? GetFileLength(string filePath) { var appender = GetAppender(filePath); if (appender != null) { try { var result = appender.GetFileLength(); if (result.HasValue) { return result; } } catch (IOException ex) { InternalLogger.Error(ex, "{0}: Failed to get length for file '{1}'.", CreateFileParameters, appender.FileName); InvalidateAppender(appender.FileName)?.Dispose(); // Do not rethrow as failed archive-file-size check should not drop logevents } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed to get length for file '{1}'.", CreateFileParameters, appender.FileName); InvalidateAppender(appender.FileName)?.Dispose(); throw; } } var fileInfo = new FileInfo(filePath); if (fileInfo.Exists) { return fileInfo.Length; } return null; } /// <summary> /// Closes the specified appender and removes it from the list. /// </summary> /// <param name="filePath">File name of the appender to be closed.</param> /// <returns>File Appender that matched the filePath (null if none found)</returns> public BaseFileAppender InvalidateAppender(string filePath) { for (int i = 0; i < _appenders.Length; ++i) { var oldAppender = _appenders[i]; if (oldAppender is null) { break; } if (string.Equals(oldAppender.FileName, filePath, StringComparison.OrdinalIgnoreCase)) { for (int j = i; j < _appenders.Length - 1; ++j) { _appenders[j] = _appenders[j + 1]; } _appenders[_appenders.Length - 1] = null; CloseAppender(oldAppender, "Invalidate", _appenders[0] is null); return oldAppender; // Return without Dispose of Archive Mutex } } return null; } private void CloseAppender(BaseFileAppender appender, string reason, bool lastAppender) { InternalLogger.Debug("{0}: FileAppender {1} Closing File: '{2}'", CreateFileParameters, reason, appender.FileName); if (lastAppender) { // No active appenders, deactivate background tasks _autoClosingTimer.Change(Timeout.Infinite, Timeout.Infinite); #if !NETSTANDARD1_3 _externalFileArchivingWatcher.StopWatching(); _logFileWasArchived = false; } else { _externalFileArchivingWatcher.StopWatching(appender.FileName); #endif } appender.Close(); } public void Dispose() { CheckCloseAppenders = null; #if !NETSTANDARD1_3 _externalFileArchivingWatcher.Dispose(); _logFileWasArchived = false; #endif var currentTimer = _autoClosingTimer; if (currentTimer != null) { _autoClosingTimer = null; currentTimer.WaitForDispose(TimeSpan.Zero); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal.NetworkSenders { using System; using System.IO; using System.Net.Sockets; using NLog.Common; /// <summary> /// Sends messages over a TCP network connection. /// </summary> internal class TcpNetworkSender : QueuedNetworkSender { private static bool? EnableKeepAliveSuccessful; private ISocket _socket; private readonly EventHandler<SocketAsyncEventArgs> _socketOperationCompletedAsync; private AsyncHelpersTask? _asyncBeginRequest; /// <summary> /// Initializes a new instance of the <see cref="TcpNetworkSender"/> class. /// </summary> /// <param name="url">URL. Must start with tcp://.</param> /// <param name="addressFamily">The address family.</param> public TcpNetworkSender(string url, AddressFamily addressFamily) : base(url) { AddressFamily = addressFamily; _socketOperationCompletedAsync = SocketOperationCompletedAsync; } internal AddressFamily AddressFamily { get; set; } internal System.Security.Authentication.SslProtocols SslProtocols { get; set; } internal TimeSpan KeepAliveTime { get; set; } /// <summary> /// Creates the socket with given parameters. /// </summary> /// <param name="host">The host address.</param> /// <param name="addressFamily">The address family.</param> /// <param name="socketType">Type of the socket.</param> /// <param name="protocolType">Type of the protocol.</param> /// <returns>Instance of <see cref="ISocket" /> which represents the socket.</returns> protected internal virtual ISocket CreateSocket(string host, AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { var socketProxy = new SocketProxy(addressFamily, socketType, protocolType); if (KeepAliveTime.TotalSeconds >= 1.0 && EnableKeepAliveSuccessful != false) { EnableKeepAliveSuccessful = TryEnableKeepAlive(socketProxy.UnderlyingSocket, (int)KeepAliveTime.TotalSeconds); } #if !NETSTANDARD1_3 && !NETSTANDARD1_5 if (SslProtocols != System.Security.Authentication.SslProtocols.None) { return new SslSocketProxy(host, SslProtocols, socketProxy); } #endif return socketProxy; } private static bool TryEnableKeepAlive(Socket underlyingSocket, int keepAliveTimeSeconds) { if (TrySetSocketOption(underlyingSocket, SocketOptionName.KeepAlive, true)) { // SOCKET OPTION NAME CONSTANT // Ws2ipdef.h (Windows SDK) // #define TCP_KEEPALIVE 3 // #define TCP_KEEPINTVL 17 SocketOptionName TcpKeepAliveTime = (SocketOptionName)0x3; SocketOptionName TcpKeepAliveInterval = (SocketOptionName)0x11; if (PlatformDetector.CurrentOS == RuntimeOS.Linux) { // https://github.com/torvalds/linux/blob/v4.16/include/net/tcp.h // #define TCP_KEEPIDLE 4 /* Start keepalives after this period */ // #define TCP_KEEPINTVL 5 /* Interval between keepalives */ TcpKeepAliveTime = (SocketOptionName)0x4; TcpKeepAliveInterval = (SocketOptionName)0x5; } else if (PlatformDetector.CurrentOS == RuntimeOS.MacOSX) { // https://opensource.apple.com/source/xnu/xnu-4570.41.2/bsd/netinet/tcp.h.auto.html // #define TCP_KEEPALIVE 0x10 /* idle time used when SO_KEEPALIVE is enabled */ // #define TCP_KEEPINTVL 0x101 /* interval between keepalives */ TcpKeepAliveTime = (SocketOptionName)0x10; TcpKeepAliveInterval = (SocketOptionName)0x101; } if (TrySetTcpOption(underlyingSocket, TcpKeepAliveTime, keepAliveTimeSeconds)) { // Configure retransmission interval when missing acknowledge of keep-alive-probe TrySetTcpOption(underlyingSocket, TcpKeepAliveInterval, 1); // Default 1 sec on Windows (75 sec on Linux) return true; } } return false; } private static bool TrySetSocketOption(Socket underlyingSocket, SocketOptionName socketOption, bool value) { try { underlyingSocket.SetSocketOption(SocketOptionLevel.Socket, socketOption, value); return true; } catch (Exception ex) { InternalLogger.Warn(ex, "NetworkTarget: Failed to configure Socket-option {0} = {1}", socketOption, value); return false; } } private static bool TrySetTcpOption(Socket underlyingSocket, SocketOptionName socketOption, int value) { try { underlyingSocket.SetSocketOption(SocketOptionLevel.Tcp, socketOption, value); return true; } catch (Exception ex) { InternalLogger.Warn(ex, "NetworkTarget: Failed to configure TCP-option {0} = {1}", socketOption, value); return false; } } protected override void DoInitialize() { var uri = new Uri(Address); var args = new MySocketAsyncEventArgs(); var ipAddress = ResolveIpAddress(uri, AddressFamily); args.RemoteEndPoint = new System.Net.IPEndPoint(ipAddress, uri.Port); args.Completed += _socketOperationCompletedAsync; args.UserToken = <PASSWORD>; _socket = CreateSocket(uri.Host, args.RemoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); base.BeginInitialize(); bool asyncOperation = false; try { asyncOperation = _socket.ConnectAsync(args); } catch (SocketException ex) { args.SocketError = ex.SocketErrorCode; } catch (Exception ex) { if (ex.InnerException is SocketException socketException) args.SocketError = socketException.SocketErrorCode; else args.SocketError = SocketError.OperationAborted; } if (!asyncOperation) { SocketOperationCompletedAsync(_socket, args); } } protected override void DoClose(AsyncContinuation continuation) { base.DoClose(ex => CloseSocket(continuation, ex)); } private void CloseSocket(AsyncContinuation continuation, Exception pendingException) { try { var sock = _socket; _socket = null; sock?.Close(); continuation(pendingException); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } continuation(exception); } } protected override void BeginRequest(NetworkRequestArgs eventArgs) { var socketEventArgs = new MySocketAsyncEventArgs(); socketEventArgs.Completed += _socketOperationCompletedAsync; SetSocketNetworkRequest(socketEventArgs, eventArgs); // Schedule async network operation to avoid blocking socket-operation (Allow adding more request) if (_asyncBeginRequest is null) _asyncBeginRequest = new AsyncHelpersTask(BeginRequestAsync); AsyncHelpers.StartAsyncTask(_asyncBeginRequest.Value, socketEventArgs); } private void BeginRequestAsync(object state) { BeginSocketRequest((SocketAsyncEventArgs)state); } private void BeginSocketRequest(SocketAsyncEventArgs args) { bool asyncOperation = false; do { try { asyncOperation = _socket.SendAsync(args); } catch (SocketException ex) { InternalLogger.Error(ex, "NetworkTarget: Error sending tcp request"); args.SocketError = ex.SocketErrorCode; } catch (Exception ex) { InternalLogger.Error(ex, "NetworkTarget: Error sending tcp request"); if (ex.InnerException is SocketException socketException) args.SocketError = socketException.SocketErrorCode; else args.SocketError = SocketError.OperationAborted; } args = asyncOperation ? null : SocketOperationCompleted(args); } while (args != null); } private void SetSocketNetworkRequest(SocketAsyncEventArgs socketEventArgs, NetworkRequestArgs networkRequest) { socketEventArgs.SetBuffer(networkRequest.RequestBuffer, networkRequest.RequestBufferOffset, networkRequest.RequestBufferLength); socketEventArgs.UserToken = networkRequest.AsyncContinuation; } private void SocketOperationCompletedAsync(object sender, SocketAsyncEventArgs args) { var nextRequest = SocketOperationCompleted(args); if (nextRequest != null) { BeginSocketRequest(nextRequest); } } private SocketAsyncEventArgs SocketOperationCompleted(SocketAsyncEventArgs args) { Exception socketException = null; if (args.SocketError != SocketError.Success) { socketException = new IOException($"Error: {args.SocketError.ToString()}, Address: {Address}"); } var asyncContinuation = args.UserToken as AsyncContinuation; var nextRequest = EndRequest(asyncContinuation, socketException); if (nextRequest.HasValue) { SetSocketNetworkRequest(args, nextRequest.Value); return args; } else { args.Completed -= _socketOperationCompletedAsync; args.Dispose(); return null; } } public override ISocket CheckSocket() { if (_socket is null) { DoInitialize(); } return _socket; } /// <summary> /// Facilitates mocking of <see cref="SocketAsyncEventArgs"/> class. /// </summary> internal class MySocketAsyncEventArgs : SocketAsyncEventArgs { /// <summary> /// Raises the Completed event. /// </summary> public void RaiseCompleted() { OnCompleted(this); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Database.Tests { using System; using System.Collections; using System.Collections.Generic; #if !NETSTANDARD using System.Configuration; #endif using System.Data; using System.Data.Common; using System.Globalization; using System.IO; using NLog.Config; using NLog.Targets; using Xunit; #if MONO using Mono.Data.Sqlite; using System.Data.SqlClient; #elif NETSTANDARD using Microsoft.Data.SqlClient; using Microsoft.Data.Sqlite; #else using System.Data.SqlClient; using System.Data.SQLite; #endif public class DatabaseTargetTests { public DatabaseTargetTests() { LogManager.ThrowExceptions = true; } #if !NETSTANDARD static DatabaseTargetTests() { var data = (DataSet)ConfigurationManager.GetSection("system.data"); var providerFactories = data.Tables["DBProviderFactories"]; providerFactories.Rows.Add("MockDb Provider", "MockDb Provider", "MockDb", typeof(MockDbFactory).AssemblyQualifiedName); providerFactories.AcceptChanges(); } #endif [Fact] public void SimpleDatabaseTest() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES('${message}')", ConnectionString = "FooBar", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, }; new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)); Assert.Same(typeof(MockDbConnection), dt.ConnectionType); List<Exception> exceptions = new List<Exception>(); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add)); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add)); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add)); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('FooBar'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1') Close() Dispose() Open('FooBar'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2') Close() Dispose() Open('FooBar'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3') Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void SimpleBatchedDatabaseTest() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES('${message}')", ConnectionString = "FooBar", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, }; new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)); Assert.Same(typeof(MockDbConnection), dt.ConnectionType); List<Exception> exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add), }; dt.WriteAsyncLogEvents(events); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('FooBar'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3') Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void KeepConnectionOpenTest() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES('${message}')", ConnectionString = "FooBar", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)).LogFactory; Assert.Same(typeof(MockDbConnection), dt.ConnectionType); List<Exception> exceptions = new List<Exception>(); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add)); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add)); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add)); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('FooBar'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3') "; AssertLog(expectedLog); MockDbConnection.ClearLog(); logFactory.Shutdown(); expectedLog = @"Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void KeepConnectionOpenBatchedTest() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES('${message}')", ConnectionString = "FooBar", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)).LogFactory; Assert.Same(typeof(MockDbConnection), dt.ConnectionType); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add), }; dt.WriteAsyncLogEvents(events); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('FooBar'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3') "; AssertLog(expectedLog); MockDbConnection.ClearLog(); logFactory.Shutdown(); expectedLog = @"Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void KeepConnectionOpenBatchedIsolationLevelTest() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES('${message}')", ConnectionString = "FooBar", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, IsolationLevel = IsolationLevel.ReadCommitted, }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)).LogFactory; Assert.Same(typeof(MockDbConnection), dt.ConnectionType); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add), }; dt.WriteAsyncLogEvents(events); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('FooBar'). DbTransaction.Begin(ReadCommitted) ExecuteNonQuery (DbTransaction=Active): INSERT INTO FooBar VALUES('msg1') ExecuteNonQuery (DbTransaction=Active): INSERT INTO FooBar VALUES('msg2') ExecuteNonQuery (DbTransaction=Active): INSERT INTO FooBar VALUES('msg3') DbTransaction.Commit() DbTransaction.Dispose() "; AssertLog(expectedLog); MockDbConnection.ClearLog(); logFactory.Shutdown(); expectedLog = @"Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void KeepConnectionOpenTest2() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES('${message}')", ConnectionString = "Database=${logger}", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)).LogFactory; Assert.Same(typeof(MockDbConnection), dt.ConnectionType); List<Exception> exceptions = new List<Exception>(); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add)); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add)); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger2", "msg3").WithContinuation(exceptions.Add)); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg4").WithContinuation(exceptions.Add)); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('Database=MyLogger'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2') Close() Dispose() Open('Database=MyLogger2'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3') Close() Dispose() Open('Database=MyLogger'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg4') "; AssertLog(expectedLog); MockDbConnection.ClearLog(); logFactory.Shutdown(); expectedLog = @"Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void KeepConnectionOpenBatchedTest2() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES('${message}')", ConnectionString = "Database=${logger}", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)).LogFactory; Assert.Same(typeof(MockDbConnection), dt.ConnectionType); // when we pass multiple log events in an array, the target will bucket-sort them by // connection string and group all commands for the same connection string together // to minimize number of db open/close operations // in this case msg1, msg2 and msg4 will be written together to MyLogger database // and msg3 will be written to MyLogger2 database List<Exception> exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger2", "msg3").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg4").WithContinuation(exceptions.Add), }; dt.WriteAsyncLogEvents(events); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('Database=MyLogger'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg4') Close() Dispose() Open('Database=MyLogger2'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3') "; AssertLog(expectedLog); MockDbConnection.ClearLog(); logFactory.Shutdown(); expectedLog = @"Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void InstallParameterTest() { MockDbConnection.ClearLog(); DatabaseCommandInfo installDbCommand = new DatabaseCommandInfo { Text = $"INSERT INTO dbo.SomeTable(SomeColumn) SELECT @paramOne WHERE NOT EXISTS(SELECT 1 FROM dbo.SomeOtherTable WHERE SomeColumn = @paramOne);" }; installDbCommand.Parameters.Add(new DatabaseParameterInfo("paramOne", "SomeValue")); DatabaseTarget dt = new DatabaseTarget() { DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, CommandText = "not_important" }; dt.InstallDdlCommands.Add(installDbCommand); new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)); Assert.Same(typeof(MockDbConnection), dt.ConnectionType); dt.Install(new InstallationContext()); string expectedLog = @"Open('Server=.;Trusted_Connection=SSPI;'). CreateParameter(0) Parameter #0 Direction=Input Parameter #0 Name=paramOne Parameter #0 Value=""SomeValue"" Add Parameter Parameter #0 ExecuteNonQuery: INSERT INTO dbo.SomeTable(SomeColumn) SELECT @paramOne WHERE NOT EXISTS(SELECT 1 FROM dbo.SomeOtherTable WHERE SomeColumn = @paramOne); Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void ParameterTest() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES(@msg, @lvl, @lg)", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, Parameters = { new DatabaseParameterInfo("msg", "${message}"), new DatabaseParameterInfo("lvl", "${level}"), new DatabaseParameterInfo("lg", "${logger}") } }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)).LogFactory; Assert.Same(typeof(MockDbConnection), dt.ConnectionType); // when we pass multiple log events in an array, the target will bucket-sort them by // connection string and group all commands for the same connection string together // to minimize number of db open/close operations // in this case msg1, msg2 and msg4 will be written together to MyLogger database // and msg3 will be written to MyLogger2 database List<Exception> exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "msg3").WithContinuation(exceptions.Add), }; dt.WriteAsyncLogEvents(events); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('Server=.;Trusted_Connection=SSPI;'). CreateParameter(0) Parameter #0 Direction=Input Parameter #0 Name=msg Parameter #0 Value=""msg1"" Add Parameter Parameter #0 CreateParameter(1) Parameter #1 Direction=Input Parameter #1 Name=lvl Parameter #1 Value=""Info"" Add Parameter Parameter #1 CreateParameter(2) Parameter #2 Direction=Input Parameter #2 Name=lg Parameter #2 Value=""MyLogger"" Add Parameter Parameter #2 ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg) CreateParameter(0) Parameter #0 Direction=Input Parameter #0 Name=msg Parameter #0 Value=""msg3"" Add Parameter Parameter #0 CreateParameter(1) Parameter #1 Direction=Input Parameter #1 Name=lvl Parameter #1 Value=""Debug"" Add Parameter Parameter #1 CreateParameter(2) Parameter #2 Direction=Input Parameter #2 Name=lg Parameter #2 Value=""MyLogger2"" Add Parameter Parameter #2 ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg) "; AssertLog(expectedLog); MockDbConnection.ClearLog(); logFactory.Shutdown(); expectedLog = @"Close() Dispose() "; AssertLog(expectedLog); } [Theory] [InlineData(null, true, @"""2""")] [InlineData(null, false, @"""2""")] [InlineData(DbType.Int32, true, "2")] [InlineData(DbType.Int32, false, "2")] [InlineData(DbType.Object, true, @"""2""")] [InlineData(DbType.Object, false, "Info")] public void LevelParameterTest(DbType? dbType, bool noRawValue, string expectedValue) { string lvlLayout = noRawValue ? "${level:format=Ordinal:norawvalue=true}" : "${level:format=Ordinal}"; MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES(@lvl, @msg)", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, Parameters = { new DatabaseParameterInfo("lvl", lvlLayout) { DbType = dbType?.ToString() }, new DatabaseParameterInfo("msg", "${message}") } }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)).LogFactory; Assert.Same(typeof(MockDbConnection), dt.ConnectionType); List<Exception> exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add), }; dt.WriteAsyncLogEvents(events); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = string.Format(@"Open('Server=.;Trusted_Connection=SSPI;'). CreateParameter(0) Parameter #0 Direction=Input Parameter #0 Name=lvl{0} Parameter #0 Value={1} Add Parameter Parameter #0 CreateParameter(1) Parameter #1 Direction=Input Parameter #1 Name=msg Parameter #1 Value=""msg1"" Add Parameter Parameter #1 ExecuteNonQuery: INSERT INTO FooBar VALUES(@lvl, @msg) ", dbType.HasValue ? $"\r\nParameter #0 DbType={dbType.Value}" : "", expectedValue); AssertLog(expectedLog); MockDbConnection.ClearLog(); logFactory.Shutdown(); expectedLog = @"Close() Dispose() "; AssertLog(expectedLog); } [Theory] [InlineData("${counter}", DbType.Int16, (short)1)] [InlineData("${counter}", DbType.Int32, 1)] [InlineData("${counter}", DbType.Int64, (long)1)] [InlineData("${counter:norawvalue=true}", DbType.Int16, (short)1)] //fallback [InlineData("${counter}", DbType.VarNumeric, 1, false, true)] [InlineData("${counter}", DbType.AnsiString, "1")] [InlineData("${level}", DbType.AnsiString, "Debug")] [InlineData("${level}", DbType.Int32, 1)] [InlineData("${level}", DbType.UInt16, (ushort)1)] [InlineData("${event-properties:boolprop}", DbType.Boolean, true)] [InlineData("${event-properties:intprop}", DbType.Int32, 123)] [InlineData("${event-properties:intprop}", DbType.AnsiString, "123")] [InlineData("${event-properties:intprop}", DbType.AnsiStringFixedLength, "123")] [InlineData("${event-properties:intprop}", DbType.String, "123")] [InlineData("${event-properties:intprop}", DbType.StringFixedLength, "123")] [InlineData("${event-properties:almostAsIntProp}", DbType.Int16, (short)124)] [InlineData("${event-properties:almostAsIntProp:norawvalue=true}", DbType.Int16, (short)124)] [InlineData("${event-properties:almostAsIntProp}", DbType.Int32, 124)] [InlineData("${event-properties:almostAsIntProp}", DbType.Int64, (long)124)] [InlineData("${event-properties:almostAsIntProp}", DbType.AnsiString, " 124 ")] [InlineData("${event-properties:emptyprop}", DbType.AnsiString, "")] [InlineData("${event-properties:emptyprop}", DbType.AnsiString, null, true)] [InlineData("${event-properties:NullRawValue}", DbType.AnsiString, "")] [InlineData("${event-properties:NullRawValue}", DbType.Int32, 0)] [InlineData("${event-properties:NullRawValue}", DbType.AnsiString, null, true)] [InlineData("${event-properties:NullRawValue}", DbType.Int32, null, true)] [InlineData("${event-properties:NullRawValue}", DbType.Guid, null, true)] [InlineData("", DbType.AnsiString, null, true)] [InlineData("", DbType.Int32, null, true)] [InlineData("", DbType.Guid, null, true)] public void GetParameterValueTest(string layout, DbType dbtype, object expected, bool allowDbNull = false, bool convertToDecimal = false) { // Arrange var logEventInfo = new LogEventInfo(LogLevel.Debug, "logger1", "message 2"); logEventInfo.Properties["intprop"] = 123; logEventInfo.Properties["boolprop"] = true; logEventInfo.Properties["emptyprop"] = ""; logEventInfo.Properties["almostAsIntProp"] = " 124 "; logEventInfo.Properties["dateprop"] = new DateTime(2018, 12, 30, 13, 34, 56); var parameterName = "@param1"; var databaseParameterInfo = new DatabaseParameterInfo { DbType = dbtype.ToString(), Layout = layout, Name = parameterName, AllowDbNull = allowDbNull, }; databaseParameterInfo.SetDbType(new MockDbConnection().CreateCommand().CreateParameter()); // Act var result = new DatabaseTarget().GetDatabaseParameterValue(logEventInfo, databaseParameterInfo); //Assert if (convertToDecimal) { //fix that we can't pass decimals into attributes (InlineData) expected = (decimal)(int)expected; } Assert.Equal(expected ?? DBNull.Value, result); } [Theory] [MemberData(nameof(ConvertFromStringTestCases))] public void GetParameterValueFromStringTest(string value, DbType dbType, object expected, string format = null, CultureInfo cultureInfo = null, bool? allowDbNull = null) { var culture = System.Threading.Thread.CurrentThread.CurrentCulture; try { System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("NL-nl"); // Arrange var databaseParameterInfo = new DatabaseParameterInfo("@test", value) { Format = format, DbType = dbType.ToString(), Culture = cultureInfo, AllowDbNull = allowDbNull ?? false, }; databaseParameterInfo.SetDbType(new MockDbConnection().CreateCommand().CreateParameter()); // Act var result = new DatabaseTarget().GetDatabaseParameterValue(LogEventInfo.CreateNullEvent(), databaseParameterInfo); // Assert Assert.Equal(expected, result); } finally { // Restore System.Threading.Thread.CurrentThread.CurrentCulture = culture; } } public static IEnumerable<object[]> ConvertFromStringTestCases() { yield return new object[] { "true", DbType.Boolean, true }; yield return new object[] { "True", DbType.Boolean, true }; yield return new object[] { "1,2", DbType.VarNumeric, (decimal)1.2 }; yield return new object[] { "1,2", DbType.Currency, (decimal)1.2 }; yield return new object[] { "1,2", DbType.Decimal, (decimal)1.2 }; yield return new object[] { "1,2", DbType.Double, (double)1.2 }; yield return new object[] { "1,2", DbType.Single, (Single)1.2 }; yield return new object[] { "2:30", DbType.Time, new TimeSpan(0, 2, 30, 0), }; yield return new object[] { "2018-12-23 22:56", DbType.DateTime, new DateTime(2018, 12, 23, 22, 56, 0), }; yield return new object[] { "2018-12-23 22:56", DbType.DateTime2, new DateTime(2018, 12, 23, 22, 56, 0), }; yield return new object[] { "23-12-2018 22:56", DbType.DateTime, new DateTime(2018, 12, 23, 22, 56, 0), "dd-MM-yyyy HH:mm" }; yield return new object[] { new DateTime(2018, 12, 23, 22, 56, 0).ToString(CultureInfo.InvariantCulture), DbType.DateTime, new DateTime(2018, 12, 23, 22, 56, 0), null, CultureInfo.InvariantCulture }; yield return new object[] { "2018-12-23", DbType.Date, new DateTime(2018, 12, 23, 0, 0, 0), }; yield return new object[] { "2018-12-23 +2:30", DbType.DateTimeOffset, new DateTimeOffset(2018, 12, 23, 0, 0, 0, new TimeSpan(2, 30, 0)) }; yield return new object[] { "23-12-2018 22:56 +2:30", DbType.DateTimeOffset, new DateTimeOffset(2018, 12, 23, 22, 56, 0, new TimeSpan(2, 30, 0)), "dd-MM-yyyy HH:mm zzz" }; yield return new object[] { "3888CCA3-D11D-45C9-89A5-E6B72185D287", DbType.Guid, Guid.Parse("3888CCA3-D11D-45C9-89A5-E6B72185D287") }; yield return new object[] { "3888CCA3D11D45C989A5E6B72185D287", DbType.Guid, Guid.Parse("3888CCA3-D11D-45C9-89A5-E6B72185D287") }; yield return new object[] { "3888CCA3D11D45C989A5E6B72185D287", DbType.Guid, Guid.Parse("3888CCA3-D11D-45C9-89A5-E6B72185D287"), "N" }; yield return new object[] { "3", DbType.Byte, (byte)3 }; yield return new object[] { "3", DbType.SByte, (sbyte)3 }; yield return new object[] { "3", DbType.Int16, (short)3 }; yield return new object[] { " 3 ", DbType.Int16, (short)3 }; yield return new object[] { "3", DbType.Int32, 3 }; yield return new object[] { "3", DbType.Int64, (long)3 }; yield return new object[] { "3", DbType.UInt16, (ushort)3 }; yield return new object[] { "3", DbType.UInt32, (uint)3 }; yield return new object[] { "3", DbType.UInt64, (ulong)3 }; yield return new object[] { "3", DbType.AnsiString, "3" }; yield return new object[] { "${db-null}", DbType.DateTime, DBNull.Value }; yield return new object[] { "${event-properties:userid}", DbType.Int32, 0 }; yield return new object[] { "${date:universalTime=true:format=yyyy-MM:norawvalue=true}", DbType.DateTime, DateTime.SpecifyKind(DateTime.UtcNow.Date.AddDays(-DateTime.UtcNow.Day + 1), DateTimeKind.Unspecified) }; yield return new object[] { "${shortdate:universalTime=true}", DbType.DateTime, DateTime.UtcNow.Date, null, null, true }; yield return new object[] { "${shortdate:universalTime=true}", DbType.DateTime, DateTime.UtcNow.Date, null, null, false }; yield return new object[] { "${shortdate:universalTime=true}", DbType.String, DateTime.UtcNow.Date.ToString("yyyy-MM-dd"), null, null, true }; yield return new object[] { "${shortdate:universalTime=true}", DbType.String, DateTime.UtcNow.Date.ToString("yyyy-MM-dd"), null, null, false }; } [Fact] public void ParameterFacetTest() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES(@msg, @lvl, @lg)", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, Parameters = { new DatabaseParameterInfo("msg", "${message}") { Precision = 3, Scale = 7, Size = 9, }, new DatabaseParameterInfo("lvl", "${level}") { Scale = 7 }, new DatabaseParameterInfo("lg", "${logger}") { Precision = 0 }, } }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)).LogFactory; Assert.Same(typeof(MockDbConnection), dt.ConnectionType); // when we pass multiple log events in an array, the target will bucket-sort them by // connection string and group all commands for the same connection string together // to minimize number of db open/close operations // in this case msg1, msg2 and msg4 will be written together to MyLogger database // and msg3 will be written to MyLogger2 database var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "msg3").WithContinuation(exceptions.Add), }; dt.WriteAsyncLogEvents(events); logFactory.Shutdown(); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('Server=.;Trusted_Connection=SSPI;'). CreateParameter(0) Parameter #0 Direction=Input Parameter #0 Name=msg Parameter #0 Size=9 Parameter #0 Precision=3 Parameter #0 Scale=7 Parameter #0 Value=""msg1"" Add Parameter Parameter #0 CreateParameter(1) Parameter #1 Direction=Input Parameter #1 Name=lvl Parameter #1 Scale=7 Parameter #1 Value=""Info"" Add Parameter Parameter #1 CreateParameter(2) Parameter #2 Direction=Input Parameter #2 Name=lg Parameter #2 Value=""MyLogger"" Add Parameter Parameter #2 ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg) CreateParameter(0) Parameter #0 Direction=Input Parameter #0 Name=msg Parameter #0 Size=9 Parameter #0 Precision=3 Parameter #0 Scale=7 Parameter #0 Value=""msg3"" Add Parameter Parameter #0 CreateParameter(1) Parameter #1 Direction=Input Parameter #1 Name=lvl Parameter #1 Scale=7 Parameter #1 Value=""Debug"" Add Parameter Parameter #1 CreateParameter(2) Parameter #2 Direction=Input Parameter #2 Name=lg Parameter #2 Value=""MyLogger2"" Add Parameter Parameter #2 ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg) Close() Dispose() "; AssertLog(expectedLog); } [Theory] [InlineData(nameof(DbType.AnsiString), typeof(string))] [InlineData(nameof(DbType.Byte), typeof(byte))] [InlineData(nameof(DbType.Boolean), typeof(bool))] [InlineData(nameof(DbType.Currency), typeof(decimal))] [InlineData(nameof(DbType.Date), typeof(DateTime))] [InlineData(nameof(DbType.DateTime), typeof(DateTime))] [InlineData(nameof(DbType.Decimal), typeof(decimal))] [InlineData(nameof(DbType.Double), typeof(double))] [InlineData(nameof(DbType.Guid), typeof(Guid))] [InlineData(nameof(DbType.Int16), typeof(short))] [InlineData(nameof(DbType.Int32), typeof(int))] [InlineData(nameof(DbType.Int64), typeof(long))] [InlineData(nameof(DbType.Object), typeof(object))] [InlineData(nameof(DbType.SByte), typeof(sbyte))] [InlineData(nameof(DbType.Single), typeof(float))] [InlineData(nameof(DbType.String), typeof(string))] [InlineData(nameof(DbType.Time), typeof(TimeSpan))] [InlineData(nameof(DbType.UInt16), typeof(ushort))] [InlineData(nameof(DbType.UInt32), typeof(uint))] [InlineData(nameof(DbType.UInt64), typeof(ulong))] [InlineData(nameof(DbType.VarNumeric), typeof(decimal))] [InlineData(nameof(DbType.AnsiStringFixedLength), typeof(string))] [InlineData(nameof(DbType.StringFixedLength), typeof(string))] [InlineData(nameof(DbType.Xml), typeof(string))] [InlineData(nameof(DbType.DateTime2), typeof(DateTime))] [InlineData(nameof(DbType.DateTimeOffset), typeof(DateTimeOffset))] [InlineData(".Int32.", null)] [InlineData(" . Int32 . ", null)] [InlineData("MockSql.Int32", typeof(int))] public void ParameterDbTypeParsingTest(string dbType, Type expectedParameterType) { var dataBaseParameterInfo = new DatabaseParameterInfo("", null) { DbType = dbType }; var actualParameterType = dataBaseParameterInfo.ParameterType; Assert.Equal(expectedParameterType, actualParameterType); } [Fact] public void ParameterDbTypePropertyNameTest() { MockDbConnection.ClearLog(); var dbProvider = typeof(MockDbConnection).AssemblyQualifiedName; var logFactory = new LogFactory().Setup().SetupExtensions(ext => ext.RegisterAssembly(typeof(DatabaseTarget).Assembly)).LoadConfigurationFromXml($@" <nlog> <targets> <target name='dt' type='Database'> <DBProvider>{dbProvider}</DBProvider> <ConnectionString>FooBar</ConnectionString> <CommandText>INSERT INTO FooBar VALUES(@message,@level,@date)</CommandText> <parameter name='@message' layout='${{message}}'/> <parameter name='@level' dbType=' MockDbType.int32 ' layout='${{level:format=Ordinal}}'/> <parameter name='@date' dbType='MockDbType.DateTime' format='yyyy-MM-dd HH:mm:ss.fff' layout='${{date:format=yyyy-MM-dd HH\:mm\:ss.fff}}'/> </target> </targets> </nlog>").LogFactory; DatabaseTarget dt = logFactory.Configuration.FindTargetByName("dt") as DatabaseTarget; Assert.NotNull(dt); List<Exception> exceptions = new List<Exception>(); var alogEvent = new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add); dt.WriteAsyncLogEvent(alogEvent); dt.WriteAsyncLogEvent(alogEvent); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('FooBar'). CreateParameter(0) Parameter #0 Direction=Input Parameter #0 Name=@message Parameter #0 Value=""msg1"" Add Parameter Parameter #0 CreateParameter(1) Parameter #1 Direction=Input Parameter #1 Name=@level Parameter #1 MockDbType=Int32 Parameter #1 Value={0} Add Parameter Parameter #1 CreateParameter(2) Parameter #2 Direction=Input Parameter #2 Name=@date Parameter #2 MockDbType=DateTime Parameter #2 Value={1} Add Parameter Parameter #2 ExecuteNonQuery: INSERT INTO FooBar VALUES(@message,@level,@date) Close() Dispose() "; expectedLog = string.Format(expectedLog + expectedLog, LogLevel.Info.Ordinal, alogEvent.LogEvent.TimeStamp.ToString(CultureInfo.InvariantCulture)); AssertLog(expectedLog); } [Fact] public void ConnectionStringBuilderTest1() { DatabaseTarget dt; dt = new DatabaseTarget(); Assert.Equal("Server=.;Trusted_Connection=SSPI;", GetConnectionString(dt)); dt = new DatabaseTarget(); dt.DBHost = "${logger}"; Assert.Equal("Server=Logger1;Trusted_Connection=SSPI;", GetConnectionString(dt)); dt = new DatabaseTarget(); dt.DBHost = "HOST1"; dt.DBDatabase = "${logger}"; Assert.Equal("Server=HOST1;Trusted_Connection=SSPI;Database=Logger1", GetConnectionString(dt)); dt = new DatabaseTarget(); dt.DBHost = "HOST1"; dt.DBDatabase = "${logger}"; dt.DBUserName = "user1"; dt.DBPassword = "<PASSWORD>"; Assert.Equal("Server=HOST1;User id=user1;Password=<PASSWORD>;Database=Logger1", GetConnectionString(dt)); dt = new DatabaseTarget(); dt.ConnectionString = "customConnectionString42"; dt.DBHost = "HOST1"; dt.DBDatabase = "${logger}"; dt.DBUserName = "user1"; dt.DBPassword = "<PASSWORD>"; Assert.Equal("customConnectionString42", GetConnectionString(dt)); } [Fact] public void DatabaseExceptionTest1() { MockDbConnection.ClearLog(); var exceptions = new List<Exception>(); var db = new DatabaseTarget(); db.CommandText = "not important"; db.ConnectionString = "cannotconnect"; db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(db)).LogFactory; try { LogManager.ThrowExceptions = false; db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } finally { LogManager.ThrowExceptions = true; logFactory.Shutdown(); } Assert.Single(exceptions); Assert.NotNull(exceptions[0]); Assert.Equal("Cannot open fake database.", exceptions[0].Message); Assert.Equal("Open('cannotconnect').\r\n", MockDbConnection.Log); } [Fact] public void DatabaseExceptionTest2() { MockDbConnection.ClearLog(); var exceptions = new List<Exception>(); var db = new DatabaseTarget(); db.CommandText = "not important"; db.ConnectionString = "cannotexecute"; db.KeepConnection = true; db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(db)).LogFactory; try { LogManager.ThrowExceptions = false; db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } finally { LogManager.ThrowExceptions = true; logFactory.Shutdown(); } Assert.Equal(3, exceptions.Count); Assert.NotNull(exceptions[0]); Assert.NotNull(exceptions[1]); Assert.NotNull(exceptions[2]); Assert.Equal("Failure during ExecuteNonQuery", exceptions[0].Message); Assert.Equal("Failure during ExecuteNonQuery", exceptions[1].Message); Assert.Equal("Failure during ExecuteNonQuery", exceptions[2].Message); string expectedLog = @"Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void DatabaseBatchExceptionTest() { MockDbConnection.ClearLog(); var exceptions = new List<Exception>(); var db = new DatabaseTarget(); db.CommandText = "not important"; db.ConnectionString = "cannotexecute"; db.KeepConnection = true; db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(db)).LogFactory; try { LogManager.ThrowExceptions = false; var events = new[] { LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), }; db.WriteAsyncLogEvents(events); } finally { LogManager.ThrowExceptions = true; logFactory.Shutdown(); } Assert.Equal(3, exceptions.Count); Assert.NotNull(exceptions[0]); Assert.NotNull(exceptions[1]); Assert.NotNull(exceptions[2]); Assert.Equal("Failure during ExecuteNonQuery", exceptions[0].Message); Assert.Equal("Failure during ExecuteNonQuery", exceptions[1].Message); Assert.Equal("Failure during ExecuteNonQuery", exceptions[2].Message); string expectedLog = @"Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void DatabaseBatchIsolationLevelExceptionTest() { MockDbConnection.ClearLog(); var exceptions = new List<Exception>(); var db = new DatabaseTarget(); db.CommandText = "not important"; db.ConnectionString = "cannotexecute"; db.KeepConnection = true; db.IsolationLevel = IsolationLevel.Serializable; db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(db)).LogFactory; try { LogManager.ThrowExceptions = false; var events = new[] { LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), }; db.WriteAsyncLogEvents(events); } finally { LogManager.ThrowExceptions = true; logFactory.Shutdown(); } Assert.Equal(3, exceptions.Count); Assert.NotNull(exceptions[0]); Assert.NotNull(exceptions[1]); Assert.NotNull(exceptions[2]); Assert.Equal("Failure during ExecuteNonQuery", exceptions[0].Message); Assert.Equal("Failure during ExecuteNonQuery", exceptions[1].Message); Assert.Equal("Failure during ExecuteNonQuery", exceptions[2].Message); string expectedLog = @"Open('cannotexecute'). DbTransaction.Begin(Serializable) ExecuteNonQuery (DbTransaction=Active): not important DbTransaction.Rollback() DbTransaction.Dispose() Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void DatabaseExceptionTest3() { MockDbConnection.ClearLog(); var exceptions = new List<Exception>(); var db = new DatabaseTarget(); db.CommandText = "not important"; db.ConnectionString = "cannotexecute"; db.KeepConnection = true; db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(db)).LogFactory; try { LogManager.ThrowExceptions = false; db.WriteAsyncLogEvents( LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } finally { LogManager.ThrowExceptions = true; logFactory.Shutdown(); } Assert.Equal(3, exceptions.Count); Assert.NotNull(exceptions[0]); Assert.NotNull(exceptions[1]); Assert.NotNull(exceptions[2]); Assert.Equal("Failure during ExecuteNonQuery", exceptions[0].Message); Assert.Equal("Failure during ExecuteNonQuery", exceptions[1].Message); Assert.Equal("Failure during ExecuteNonQuery", exceptions[2].Message); string expectedLog = @"Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() "; AssertLog(expectedLog); } #if !MONO && !NETSTANDARD [Fact] public void ConnectionStringNameInitTest() { var dt = new DatabaseTarget { ConnectionStringName = "MyConnectionString", CommandText = "notimportant", }; Assert.Same(ConfigurationManager.ConnectionStrings, dt.ConnectionStringsSettings); dt.ConnectionStringsSettings = new ConnectionStringSettingsCollection() { new ConnectionStringSettings("MyConnectionString", "cs1", "MockDb"), }; new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)); Assert.Same(MockDbFactory.Instance, dt.ProviderFactory); Assert.Equal("cs1", dt.ConnectionString.Render(LogEventInfo.CreateNullEvent())); } [Fact] public void ConnectionStringNameNegativeTest_if_ThrowConfigExceptions() { LogManager.ThrowConfigExceptions = true; var dt = new DatabaseTarget { ConnectionStringName = "MyConnectionString", CommandText = "notimportant", ConnectionStringsSettings = new ConnectionStringSettingsCollection(), }; try { new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)); Assert.True(false, "Exception expected."); } catch (NLogConfigurationException configurationException) { Assert.Equal( "Connection string 'MyConnectionString' is not declared in <connectionStrings /> section.", configurationException.Message); } } [Fact] public void ProviderFactoryInitTest() { var dt = new DatabaseTarget(); dt.DBProvider = "MockDb"; dt.CommandText = "Notimportant"; new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)); Assert.Same(MockDbFactory.Instance, dt.ProviderFactory); dt.OpenConnection("myConnectionString", null); Assert.Equal(1, MockDbConnection2.OpenCount); Assert.Equal("myConnectionString", MockDbConnection2.LastOpenConnectionString); } #endif [Fact] public void AccessTokenShouldBeSet() { // Arrange var accessToken = "123"; MockDbConnection.ClearLog(); var databaseTarget = new DatabaseTarget { DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, CommandText = "command1", }; databaseTarget.ConnectionProperties.Add(new DatabaseObjectPropertyInfo() { Name = "AccessToken", Layout = accessToken }); new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(databaseTarget)); // Act var connection1 = databaseTarget.OpenConnection(".", null); var connection2 = databaseTarget.OpenConnection(".", null); // Twice because we use compiled method on 2nd attempt // Assert var sqlConnection1 = Assert.IsType<MockDbConnection>(connection1); Assert.Equal(accessToken, sqlConnection1.AccessToken); // Verify dynamic setter method invoke assigns correctly var sqlConnection2 = Assert.IsType<MockDbConnection>(connection2); Assert.Equal(accessToken, sqlConnection2.AccessToken); // Verify compiled method also assigns correctly } [Fact] public void AccessTokenWithInvalidTypeCannotBeSet() { // Arrange MockDbConnection.ClearLog(); var databaseTarget = new DatabaseTarget { DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, CommandText = "command1", }; databaseTarget.ConnectionProperties.Add(new DatabaseObjectPropertyInfo() { Name = "AccessToken", Layout = "${eventProperty:accessToken}", PropertyType = typeof(int) }); var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(databaseTarget)).LogFactory; // Act + Assert Assert.Throws<InvalidCastException>(() => logFactory.GetCurrentClassLogger().WithProperty("accessToken", "abc").Info("Hello")); } [Fact] public void CommandTimeoutShouldBeSet() { // Arrange var commandTimeout = "123"; MockDbConnection.ClearLog(); var databaseTarget = new DatabaseTarget { DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, CommandText = "command1", }; databaseTarget.CommandProperties.Add(new DatabaseObjectPropertyInfo() { Name = "CommandTimeout", Layout = commandTimeout, PropertyType = typeof(int) }); new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(databaseTarget)); // Act var connection = databaseTarget.OpenConnection(".", null); var command1 = databaseTarget.CreateDbCommand(LogEventInfo.CreateNullEvent(), connection); var command2 = databaseTarget.CreateDbCommand(LogEventInfo.CreateNullEvent(), connection); // Twice because we use compiled method on 2nd attempt // Assert var sqlCommand1 = Assert.IsType<MockDbCommand>(command1); Assert.Equal(commandTimeout, sqlCommand1.CommandTimeout.ToString()); // Verify dynamic setter method invoke assigns correctly var sqlCommand2 = Assert.IsType<MockDbCommand>(command2); Assert.Equal(commandTimeout, sqlCommand2.CommandTimeout.ToString()); // Verify compiled method also assigns correctly } [Fact] public void SqlServerShorthandNotationTest() { foreach (string provName in new[] { "microsoft", "msde", "mssql", "sqlserver" }) { var dt = new DatabaseTarget() { Name = "myTarget", DBProvider = provName, ConnectionString = "notimportant", CommandText = "notimportant", }; new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)); Assert.Equal(typeof(SqlConnection), dt.ConnectionType); } } #if !NETSTANDARD [Fact] public void OleDbShorthandNotationTest() { var dt = new DatabaseTarget() { Name = "myTarget", DBProvider = "oledb", ConnectionString = "notimportant", CommandText = "notimportant", }; new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)); Assert.Equal(typeof(System.Data.OleDb.OleDbConnection), dt.ConnectionType); } [Fact] public void OdbcShorthandNotationTest() { var dt = new DatabaseTarget() { Name = "myTarget", DBProvider = "odbc", ConnectionString = "notimportant", CommandText = "notimportant", }; new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)); Assert.Equal(typeof(System.Data.Odbc.OdbcConnection), dt.ConnectionType); } #endif [Fact] public void SQLite_InstallAndLogMessageProgrammatically() { SQLiteTest sqlLite = new SQLiteTest("TestLogProgram.sqlite"); // delete database if it for some reason already exists sqlLite.TryDropDatabase(); LogManager.ThrowExceptions = true; try { sqlLite.CreateDatabase(); var connectionString = sqlLite.GetConnectionString(); DatabaseTarget testTarget = new DatabaseTarget("TestSqliteTarget"); testTarget.ConnectionString = connectionString; testTarget.DBProvider = GetSQLiteDbProvider(); testTarget.InstallDdlCommands.Add(new DatabaseCommandInfo() { CommandType = CommandType.Text, Text = $@" CREATE TABLE NLogTestTable ( Id int PRIMARY KEY, Message varchar(100) NULL)" }); using (var context = new InstallationContext()) { testTarget.Install(context); } // check so table is created var tableName = sqlLite.IssueScalarQuery("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'NLogTestTable'"); Assert.Equal("NLogTestTable", tableName); testTarget.CommandText = "INSERT INTO NLogTestTable (Message) VALUES (@message)"; testTarget.Parameters.Add(new DatabaseParameterInfo("@message", new NLog.Layouts.SimpleLayout("${message}"))); // setup logging var config = new LoggingConfiguration(); config.AddTarget("dbTarget", testTarget); var rule = new LoggingRule("*", LogLevel.Debug, testTarget); config.LoggingRules.Add(rule); // try to log LogManager.Configuration = config; var logger = LogManager.GetLogger("testLog"); logger.Debug("Test debug message"); logger.Error("Test error message"); // will return long var logcount = sqlLite.IssueScalarQuery("SELECT count(1) FROM NLogTestTable"); Assert.Equal((long)2, logcount); } finally { sqlLite.TryDropDatabase(); } } private static string GetSQLiteDbProvider() { #if MONO return "Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite"; #elif NETSTANDARD return "Microsoft.Data.Sqlite.SqliteConnection, Microsoft.Data.Sqlite"; #else return "System.Data.SQLite.SQLiteConnection, System.Data.SQLite"; #endif } [Fact] public void SQLite_InstallAndLogMessage() { SQLiteTest sqlLite = new SQLiteTest("TestLogXml.sqlite"); // delete database just in case sqlLite.TryDropDatabase(); LogManager.ThrowExceptions = true; try { sqlLite.CreateDatabase(); var connectionString = sqlLite.GetConnectionString(); string dbProvider = GetSQLiteDbProvider(); // Create log with xml config var logFactory = new LogFactory().Setup().SetupExtensions(ext => ext.RegisterAssembly(typeof(DatabaseTarget).Assembly)).LoadConfigurationFromXml(@" <nlog xmlns='http://www.nlog-project.org/schemas/NLog.xsd' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' throwExceptions='true'> <targets> <target name='database' xsi:type='Database' dbProvider=""" + dbProvider + @""" connectionstring=""" + connectionString + @""" commandText='insert into NLogSqlLiteTest (Message) values (@message);'> <parameter name='@message' layout='${message}' /> <install-command ignoreFailures=""false"" text=""CREATE TABLE NLogSqlLiteTest ( Id int PRIMARY KEY, Message varchar(100) NULL );""/> </target> </targets> <rules> <logger name='*' writeTo='database' /> </rules> </nlog>").LogFactory; //install InstallationContext context = new InstallationContext(); logFactory.Configuration.Install(context); // check so table is created var tableName = sqlLite.IssueScalarQuery("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'NLogSqlLiteTest'"); Assert.Equal("NLogSqlLiteTest", tableName); // start to log var logger = logFactory.GetLogger("SQLite"); logger.Debug("Test"); logger.Error("Test2"); logger.Info("Final test row"); // returns long var logcount = sqlLite.IssueScalarQuery("SELECT count(1) FROM NLogSqlLiteTest"); Assert.Equal((long)3, logcount); } finally { sqlLite.TryDropDatabase(); } } [Fact] public void SQLite_InstallTest() { SQLiteTest sqlLite = new SQLiteTest("TestInstallXml.sqlite"); // delete database just in case sqlLite.TryDropDatabase(); LogManager.ThrowExceptions = true; try { sqlLite.CreateDatabase(); var connectionString = sqlLite.GetConnectionString(); string dbProvider = GetSQLiteDbProvider(); // Create log with xml config var logFactory = new LogFactory().Setup().SetupExtensions(ext => ext.RegisterAssembly(typeof(DatabaseTarget).Assembly)).LoadConfigurationFromXml(@" <nlog xmlns='http://www.nlog-project.org/schemas/NLog.xsd' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' throwExceptions='true'> <targets> <target name='database' xsi:type='Database' dbProvider=""" + dbProvider + @""" connectionstring=""" + connectionString + @""" commandText='not_important'> <install-command ignoreFailures=""false"" text=""CREATE TABLE NLogSqlLiteTestAppNames ( Id int PRIMARY KEY, Name varchar(100) NULL ); INSERT INTO NLogSqlLiteTestAppNames(Id, Name) VALUES (1, @appName);""> <parameter name='@appName' layout='MyApp' /> </install-command> </target> </targets> <rules> <logger name='*' writeTo='database' /> </rules> </nlog>").LogFactory; //install InstallationContext context = new InstallationContext(); logFactory.Configuration.Install(context); // check so table is created var tableName = sqlLite.IssueScalarQuery("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'NLogSqlLiteTestAppNames'"); Assert.Equal("NLogSqlLiteTestAppNames", tableName); // returns long var logcount = sqlLite.IssueScalarQuery("SELECT count(*) FROM NLogSqlLiteTestAppNames"); Assert.Equal((long)1, logcount); // check if entry was correct var entryValue = sqlLite.IssueScalarQuery("SELECT Name FROM NLogSqlLiteTestAppNames WHERE ID = 1"); Assert.Equal("MyApp", entryValue); } finally { sqlLite.TryDropDatabase(); } } [Fact] public void SQLite_InstallProgramaticallyTest() { SQLiteTest sqlLite = new SQLiteTest("TestInstallProgram.sqlite"); // delete database just in case sqlLite.TryDropDatabase(); LogManager.ThrowExceptions = true; try { sqlLite.CreateDatabase(); var connectionString = sqlLite.GetConnectionString(); string dbProvider = GetSQLiteDbProvider(); DatabaseTarget testTarget = new DatabaseTarget("TestSqliteTargetInstallProgram"); testTarget.ConnectionString = connectionString; testTarget.DBProvider = dbProvider; DatabaseCommandInfo installDbCommand = new DatabaseCommandInfo { Text = "CREATE TABLE NLogSqlLiteTestAppNames (Id int PRIMARY KEY, Name varchar(100) NULL); " + "INSERT INTO NLogSqlLiteTestAppNames(Id, Name) SELECT 1, @paramOne WHERE NOT EXISTS(SELECT 1 FROM NLogSqlLiteTestAppNames WHERE Name = @paramOne);" }; installDbCommand.Parameters.Add(new DatabaseParameterInfo("@paramOne", "MyApp")); testTarget.InstallDdlCommands.Add(installDbCommand); //install InstallationContext context = new InstallationContext(); testTarget.Install(context); // check so table is created var tableName = sqlLite.IssueScalarQuery("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'NLogSqlLiteTestAppNames'"); Assert.Equal("NLogSqlLiteTestAppNames", tableName); // returns long var logcount = sqlLite.IssueScalarQuery("SELECT count(*) FROM NLogSqlLiteTestAppNames"); Assert.Equal((long)1, logcount); // check if entry was correct var entryValue = sqlLite.IssueScalarQuery("SELECT Name FROM NLogSqlLiteTestAppNames WHERE ID = 1"); Assert.Equal("MyApp", entryValue); } finally { sqlLite.TryDropDatabase(); } } private static LogFactory SetupSqliteConfigWithInvalidInstallCommand(string databaseName) { var nlogXmlConfig = @" <nlog xmlns='http://www.nlog-project.org/schemas/NLog.xsd' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' throwExceptions='false'> <targets> <target name='database' xsi:type='Database' dbProvider='{0}' connectionstring='{1}' commandText='insert into RethrowingInstallExceptionsTable (Message) values (@message);'> <parameter name='@message' layout='${{message}}' /> <install-command text='THIS IS NOT VALID SQL;' /> </target> </targets> <rules> <logger name='*' writeTo='database' /> </rules> </nlog>"; // Use an in memory SQLite database // See https://www.sqlite.org/inmemorydb.html #if NETSTANDARD var connectionString = "Data Source=:memory:"; #else var connectionString = "Uri=file::memory:;Version=3"; #endif return new LogFactory().Setup().SetupExtensions(ext => ext.RegisterAssembly(typeof(DatabaseTarget).Assembly)).LoadConfigurationFromXml(String.Format(nlogXmlConfig, GetSQLiteDbProvider(), connectionString)).LogFactory; } [Fact] public void NotRethrowingInstallExceptions() { try { LogManager.ThrowExceptions = false; var logFactory = SetupSqliteConfigWithInvalidInstallCommand("not_rethrowing_install_exceptions"); // Default InstallationContext should not rethrow exceptions InstallationContext context = new InstallationContext(); Assert.False(context.IgnoreFailures, "Failures should not be ignored by default"); Assert.False(context.ThrowExceptions, "Exceptions should not be thrown by default"); var exRecorded = Record.Exception(() => logFactory.Configuration.Install(context)); Assert.Null(exRecorded); } finally { LogManager.ThrowExceptions = true; } } [Fact] public void RethrowingInstallExceptions() { try { LogManager.ThrowExceptions = false; var logFactory = SetupSqliteConfigWithInvalidInstallCommand("rethrowing_install_exceptions"); InstallationContext context = new InstallationContext() { ThrowExceptions = true }; Assert.True(context.ThrowExceptions); // Sanity check #if MONO || NETSTANDARD Assert.Throws<SqliteException>(() => logFactory.Configuration.Install(context)); #else Assert.Throws<SQLiteException>(() => logFactory.Configuration.Install(context)); #endif } finally { LogManager.ThrowExceptions = true; } } [Fact] public void SqlServer_NoTargetInstallException() { if (IsLinux()) { Console.WriteLine("skipping test SqlServer_NoTargetInstallException because we are running in Travis"); return; } bool isAppVeyor = IsAppVeyor(); SqlServerTest.TryDropDatabase(isAppVeyor); try { SqlServerTest.CreateDatabase(isAppVeyor); var connectionString = SqlServerTest.GetConnectionString(isAppVeyor); DatabaseTarget testTarget = new DatabaseTarget("TestDbTarget"); testTarget.ConnectionString = connectionString; testTarget.InstallDdlCommands.Add(new DatabaseCommandInfo() { CommandType = CommandType.Text, Text = $@" IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'NLogTestTable') RETURN CREATE TABLE [Dbo].[NLogTestTable] ( [ID] [int] IDENTITY(1,1) NOT NULL, [MachineName] [nvarchar](200) NULL)" }); using (var context = new InstallationContext()) { testTarget.Install(context); } var tableCatalog = SqlServerTest.IssueScalarQuery(isAppVeyor, @"SELECT TABLE_NAME FROM NLogTest.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'NLogTestTable' "); //check if table exists Assert.Equal("NLogTestTable", tableCatalog); } finally { SqlServerTest.TryDropDatabase(isAppVeyor); } } [Fact] public void SqlServer_InstallAndLogMessage() { if (IsLinux()) { Console.WriteLine("skipping test SqlServer_InstallAndLogMessage because we are running in Travis"); return; } bool isAppVeyor = IsAppVeyor(); SqlServerTest.TryDropDatabase(isAppVeyor); try { SqlServerTest.CreateDatabase(isAppVeyor); var connectionString = SqlServerTest.GetConnectionString(IsAppVeyor()); var logFactory = new LogFactory().Setup().SetupExtensions(ext => ext.RegisterAssembly(typeof(DatabaseTarget).Assembly)).LoadConfigurationFromXml(@" <nlog xmlns='http://www.nlog-project.org/schemas/NLog.xsd' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' throwExceptions='true'> <targets> <target name='database' xsi:type='Database' connectionstring=""" + connectionString + @""" commandText='insert into dbo.NLogSqlServerTest (Uid, LogDate) values (@uid, @logdate);'> <parameter name='@uid' layout='${event-properties:uid}' /> <parameter name='@logdate' layout='${date}' /> <install-command ignoreFailures=""false"" text=""CREATE TABLE dbo.NLogSqlServerTest ( Id int NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED, Uid uniqueidentifier NULL, LogDate date NULL );""/> </target> </targets> <rules> <logger name='*' writeTo='database' /> </rules> </nlog>").LogFactory; //install InstallationContext context = new InstallationContext(); logFactory.Configuration.Install(context); var tableCatalog = SqlServerTest.IssueScalarQuery(isAppVeyor, @"SELECT TABLE_CATALOG FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Dbo' AND TABLE_NAME = 'NLogSqlServerTest'"); //check if table exists Assert.Equal("NLogTest", tableCatalog); var logger = logFactory.GetLogger("A"); var target = logFactory.Configuration.FindTargetByName<DatabaseTarget>("database"); var uid = new Guid("e7c648b4-3508-4df2-b001-753148659d6d"); var logEvent = new LogEventInfo(LogLevel.Info, null, null); logEvent.Properties["uid"] = uid; logger.Log(logEvent); var count = SqlServerTest.IssueScalarQuery(isAppVeyor, "SELECT count(1) FROM dbo.NLogSqlServerTest"); Assert.Equal(1, count); var result = SqlServerTest.IssueScalarQuery(isAppVeyor, "SELECT Uid FROM dbo.NLogSqlServerTest"); Assert.Equal(uid, result); var result2 = SqlServerTest.IssueScalarQuery(isAppVeyor, "SELECT LogDate FROM dbo.NLogSqlServerTest"); Assert.Equal(DateTime.Today, result2); } finally { SqlServerTest.TryDropDatabase(isAppVeyor); } } #if !NETSTANDARD [Fact] public void GetProviderNameFromAppConfig() { LogManager.ThrowExceptions = true; var databaseTarget = new DatabaseTarget() { Name = "myTarget", ConnectionStringName = "test_connectionstring_with_providerName", CommandText = "notimportant", }; databaseTarget.ConnectionStringsSettings = new ConnectionStringSettingsCollection() { new ConnectionStringSettings("test_connectionstring_without_providerName", "some connectionstring"), new ConnectionStringSettings("test_connectionstring_with_providerName", "some connectionstring", "System.Data.SqlClient"), }; new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(databaseTarget)); Assert.NotNull(databaseTarget.ProviderFactory); Assert.Equal(typeof(SqlClientFactory), databaseTarget.ProviderFactory.GetType()); } [Fact] public void DontRequireProviderNameInAppConfig() { LogManager.ThrowExceptions = true; var databaseTarget = new DatabaseTarget() { Name = "myTarget", ConnectionStringName = "test_connectionstring_without_providerName", CommandText = "notimportant", DBProvider = "System.Data.SqlClient" }; databaseTarget.ConnectionStringsSettings = new ConnectionStringSettingsCollection() { new ConnectionStringSettings("test_connectionstring_without_providerName", "some connectionstring"), new ConnectionStringSettings("test_connectionstring_with_providerName", "some connectionstring", "System.Data.SqlClient"), }; new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(databaseTarget)); Assert.NotNull(databaseTarget.ProviderFactory); Assert.Equal(typeof(SqlClientFactory), databaseTarget.ProviderFactory.GetType()); } [Fact] public void GetProviderNameFromConnectionString() { LogManager.ThrowExceptions = true; var databaseTarget = new DatabaseTarget() { Name = "myTarget", ConnectionStringName = "test_connectionstring_with_providerName", CommandText = "notimportant", }; databaseTarget.ConnectionStringsSettings = new ConnectionStringSettingsCollection() { new ConnectionStringSettings("test_connectionstring_with_providerName", "metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string=\"data source=192.168.0.100;initial catalog=TEST_DB;user id=myUser;password=<PASSWORD>;multipleactiveresultsets=True;application name=EntityFramework\"", "System.Data.EntityClient"), }; new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(databaseTarget)); Assert.NotNull(databaseTarget.ProviderFactory); Assert.Equal(typeof(SqlClientFactory), databaseTarget.ProviderFactory.GetType()); Assert.Equal("data source=192.168.0.100;initial catalog=TEST_DB;user id=myUser;password=<PASSWORD>;multipleactiveresultsets=True;application name=EntityFramework", ((NLog.Layouts.SimpleLayout)databaseTarget.ConnectionString).FixedText); } #endif [Theory] [InlineData("localhost", "MyDatabase", "user", "password", "Server=localhost;User id=user;Password=<PASSWORD>;Database=MyDatabase")] [InlineData("localhost", null, "user", "password", "Server=localhost;User id=user;Password=<PASSWORD>;")] [InlineData("localhost", "MyDatabase", "user", "'password'", "Server=localhost;User id=user;Password='<PASSWORD>';Database=MyDatabase")] [InlineData("localhost", "MyDatabase", "user", "\"password\"", "Server=localhost;User id=user;Password=\"<PASSWORD>\";Database=MyDatabase")] [InlineData("localhost", "MyDatabase", "user", "pa;ssword", "Server=localhost;User id=user;Password='<PASSWORD>';Database=MyDatabase")] [InlineData("localhost", "MyDatabase", "user", "pa'ssword", "Server=localhost;User id=user;Password=\"<PASSWORD>\";Database=MyDatabase")] [InlineData("localhost", "MyDatabase", "user", "pa'\"ssword", "Server=localhost;User id=user;Password=\"pa'\"\"ssword\";Database=MyDatabase")] [InlineData("localhost", "MyDatabase", "user", "pa\"ssword", "Server=localhost;User id=user;Password='<PASSWORD>';Database=MyDatabase")] [InlineData("localhost", "MyDatabase", "user", "", "Server=localhost;User id=user;Password=;Database=MyDatabase")] [InlineData("localhost", "MyDatabase", null, "password", "Server=localhost;Trusted_Connection=SSPI;Database=MyDatabase")] public void DatabaseConnectionStringTest(string host, string database, string username, string password, string expected) { // Arrange var databaseTarget = new NonLoggingDatabaseTarget() { CommandText = "DoSomething", Name = "myTarget", DBHost = host, DBDatabase = database, DBUserName = username, DBPassword = <PASSWORD> }; var logEventInfo = LogEventInfo.CreateNullEvent(); // Act var result = databaseTarget.GetRenderedConnectionString(logEventInfo); // Assert Assert.Equal(expected, result); } [Theory] [InlineData("password", "<PASSWORD>")] [InlineData("", "")] [InlineData("password'", "\"password'\"")] public void DatabaseConnectionStringViaVariableTest(string password, string expectedPassword) { // Arrange var databaseTarget = new NonLoggingDatabaseTarget() { CommandText = "DoSomething", Name = "myTarget", DBHost = "localhost", DBDatabase = "MyDatabase", DBUserName = "user", DBPassword = "${event-properties:myPassword}" }; var logEventInfo = LogEventInfo.Create(LogLevel.Debug, "logger1", "message1"); logEventInfo.Properties["myPassword"] = password; // Act var result = databaseTarget.GetRenderedConnectionString(logEventInfo); // Assert var expected = $"Server=localhost;User id=user;Password={<PASSWORD>};Database=MyDatabase"; Assert.Equal(expected, result); } private static void AssertLog(string expectedLog) { Assert.Equal(expectedLog.Replace("\r", ""), MockDbConnection.Log.Replace("\r", "")); } private string GetConnectionString(DatabaseTarget dt) { MockDbConnection.ClearLog(); dt.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName; dt.CommandText = "NotImportant"; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => cfg.Configuration.AddRuleForAllLevels(dt)).LogFactory; var exceptions = new List<Exception>(); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "msg1").WithContinuation(exceptions.Add)); logFactory.Shutdown(); return MockDbConnection.LastConnectionString; } public sealed class MockDbConnection : IDbConnection { public static string Log { get; private set; } public static string LastConnectionString { get; private set; } public MockDbConnection() { } public MockDbConnection(string connectionString) { ConnectionString = connectionString; } public IDbTransaction BeginTransaction(IsolationLevel il) { AddToLog("DbTransaction.Begin({0})", il); return new MockDbTransaction(this, il); } public IDbTransaction BeginTransaction() { return BeginTransaction(IsolationLevel.ReadCommitted); } public void ChangeDatabase(string databaseName) { throw new NotImplementedException(); } public void Close() { AddToLog("Close()"); } public string ConnectionString { get; set; } public int ConnectionTimeout => throw new NotImplementedException(); public IDbCommand CreateCommand() { return new MockDbCommand() { Connection = this }; } public string Database => throw new NotImplementedException(); public void Open() { LastConnectionString = ConnectionString; AddToLog("Open('{0}').", ConnectionString); if (ConnectionString == "cannotconnect") { throw new ApplicationException("Cannot open fake database."); } } public ConnectionState State => throw new NotImplementedException(); public string AccessToken { get; set; } public void Dispose() { AddToLog("Dispose()"); } public static void ClearLog() { Log = string.Empty; } public void AddToLog(string message, params object[] args) { if (args.Length > 0) { message = string.Format(CultureInfo.InvariantCulture, message, args); } Log += message + "\r\n"; } } private class NonLoggingDatabaseTarget : DatabaseTarget { public string GetRenderedConnectionString(LogEventInfo logEventInfo) { return base.BuildConnectionString(logEventInfo); } } private class MockDbCommand : IDbCommand { private int paramCount; private IDataParameterCollection parameters; public MockDbCommand() { parameters = new MockParameterCollection(this); } public void Cancel() { throw new NotImplementedException(); } public string CommandText { get; set; } public int CommandTimeout { get; set; } public CommandType CommandType { get; set; } public IDbConnection Connection { get; set; } public IDbTransaction Transaction { get; set; } public IDbDataParameter CreateParameter() { ((MockDbConnection)Connection).AddToLog("CreateParameter({0})", paramCount); return new MockDbParameter(this, paramCount++); } public int ExecuteNonQuery() { if (Transaction != null) ((MockDbConnection)Connection).AddToLog("ExecuteNonQuery (DbTransaction={0}): {1}", Transaction.Connection != null ? "Active" : "Disposed", CommandText); else ((MockDbConnection)Connection).AddToLog("ExecuteNonQuery: {0}", CommandText); if (Connection.ConnectionString == "cannotexecute") { throw new ApplicationException("Failure during ExecuteNonQuery"); } return 0; } public IDataReader ExecuteReader(CommandBehavior behavior) { throw new NotImplementedException(); } public IDataReader ExecuteReader() { throw new NotImplementedException(); } public object ExecuteScalar() { throw new NotImplementedException(); } public IDataParameterCollection Parameters => parameters; public void Prepare() { throw new NotImplementedException(); } public UpdateRowSource UpdatedRowSource { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public void Dispose() { Transaction = null; Connection = null; } } private class MockDbParameter : IDbDataParameter { private readonly MockDbCommand mockDbCommand; private readonly int paramId; private string parameterName; private object parameterValue; private DbType parameterType; public MockDbParameter(MockDbCommand mockDbCommand, int paramId) { this.mockDbCommand = mockDbCommand; this.paramId = paramId; } public DbType DbType { get { return parameterType; } set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} DbType={1}", paramId, value); parameterType = value; } } public DbType MockDbType { get { return parameterType; } set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} MockDbType={1}", paramId, value); parameterType = value; } } public ParameterDirection Direction { get => throw new NotImplementedException(); set => ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Direction={1}", paramId, value); } public bool IsNullable => throw new NotImplementedException(); public string ParameterName { get => parameterName; set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Name={1}", paramId, value); parameterName = value; } } public string SourceColumn { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public DataRowVersion SourceVersion { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public object Value { get => parameterValue; set { object valueOutput = value is string valueString ? $"\"{valueString}\"" : value; ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Value={1}", paramId, valueOutput); parameterValue = value; } } public byte Precision { get => throw new NotImplementedException(); set => ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Precision={1}", paramId, value); } public byte Scale { get => throw new NotImplementedException(); set => ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Scale={1}", paramId, value); } public int Size { get => throw new NotImplementedException(); set => ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Size={1}", paramId, value); } public override string ToString() { return "Parameter #" + paramId; } } private class MockParameterCollection : IDataParameterCollection { private readonly MockDbCommand command; public MockParameterCollection(MockDbCommand command) { this.command = command; } public IEnumerator GetEnumerator() { throw new NotImplementedException(); } public void CopyTo(Array array, int index) { throw new NotImplementedException(); } public int Count => throw new NotImplementedException(); public object SyncRoot => throw new NotImplementedException(); public bool IsSynchronized => throw new NotImplementedException(); public int Add(object value) { ((MockDbConnection)command.Connection).AddToLog("Add Parameter {0}", value); return 0; } public bool Contains(object value) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public int IndexOf(object value) { throw new NotImplementedException(); } public void Insert(int index, object value) { throw new NotImplementedException(); } public void Remove(object value) { throw new NotImplementedException(); } public void RemoveAt(int index) { throw new NotImplementedException(); } object IList.this[int index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public bool IsReadOnly => throw new NotImplementedException(); public bool IsFixedSize => throw new NotImplementedException(); public bool Contains(string parameterName) { throw new NotImplementedException(); } public int IndexOf(string parameterName) { throw new NotImplementedException(); } public void RemoveAt(string parameterName) { throw new NotImplementedException(); } object IDataParameterCollection.this[string parameterName] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } } public sealed class MockDbTransaction : IDbTransaction { public IDbConnection Connection { get; private set; } public IsolationLevel IsolationLevel { get; } public MockDbTransaction(IDbConnection connection, IsolationLevel isolationLevel) { Connection = connection; IsolationLevel = isolationLevel; } public void Commit() { if (Connection is null) throw new NotSupportedException(); ((MockDbConnection)Connection).AddToLog("DbTransaction.Commit()"); } public void Dispose() { ((MockDbConnection)Connection).AddToLog("DbTransaction.Dispose()"); Connection = null; } public void Rollback() { if (Connection is null) throw new NotSupportedException(); ((MockDbConnection)Connection).AddToLog("DbTransaction.Rollback()"); } } public class MockDbFactory : DbProviderFactory { public static readonly MockDbFactory Instance = new MockDbFactory(); public override DbConnection CreateConnection() { return new MockDbConnection2(); } } public class MockDbConnection2 : DbConnection { public static int OpenCount { get; private set; } public static string LastOpenConnectionString { get; private set; } protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { throw new NotImplementedException(); } public override void ChangeDatabase(string databaseName) { throw new NotImplementedException(); } public override void Close() { throw new NotImplementedException(); } public override string ConnectionString { get; set; } protected override DbCommand CreateDbCommand() { throw new NotImplementedException(); } public override string DataSource => throw new NotImplementedException(); public override string Database => throw new NotImplementedException(); public override void Open() { LastOpenConnectionString = ConnectionString; OpenCount++; } public override string ServerVersion => throw new NotImplementedException(); public override ConnectionState State => throw new NotImplementedException(); } private class SQLiteTest { private string dbName = "NLogTest.sqlite"; private string connectionString; public SQLiteTest(string dbName) { this.dbName = dbName; #if NETSTANDARD connectionString = "Data Source=" + this.dbName; #else connectionString = "Data Source=" + this.dbName + ";Version=3;"; #endif } public string GetConnectionString() { return connectionString; } public void CreateDatabase() { if (DatabaseExists()) { TryDropDatabase(); } SQLiteHandler.CreateDatabase(dbName); } public bool DatabaseExists() { return File.Exists(dbName); } public void TryDropDatabase() { try { if (DatabaseExists()) { File.Delete(dbName); } } catch { } } public void IssueCommand(string commandString) { using (DbConnection connection = SQLiteHandler.GetConnection(connectionString)) { connection.Open(); using (DbCommand command = SQLiteHandler.CreateCommand(commandString, connection)) { command.ExecuteNonQuery(); } } } public object IssueScalarQuery(string commandString) { using (DbConnection connection = SQLiteHandler.GetConnection(connectionString)) { connection.Open(); using (DbCommand command = SQLiteHandler.CreateCommand(commandString, connection)) { var scalar = command.ExecuteScalar(); return scalar; } } } } private static class SQLiteHandler { public static void CreateDatabase(string dbName) { #if NETSTANDARD // Using ConnectionString Mode=ReadWriteCreate #elif MONO SqliteConnection.CreateFile(dbName); #else SQLiteConnection.CreateFile(dbName); #endif } public static DbConnection GetConnection(string connectionString) { #if NETSTANDARD return new SqliteConnection(connectionString + ";Mode=ReadWriteCreate;"); #elif MONO return new SqliteConnection(connectionString); #else return new SQLiteConnection(connectionString); #endif } public static DbCommand CreateCommand(string commandString, DbConnection connection) { #if MONO || NETSTANDARD return new SqliteCommand(commandString, (SqliteConnection)connection); #else return new SQLiteCommand(commandString, (SQLiteConnection)connection); #endif } } private static class SqlServerTest { static SqlServerTest() { } public static string GetConnectionString(bool isAppVeyor) { string connectionString = string.Empty; #if !NETSTANDARD connectionString = ConfigurationManager.AppSettings["SqlServerTestConnectionString"]; #endif if (String.IsNullOrWhiteSpace(connectionString)) { connectionString = isAppVeyor ? AppVeyorConnectionStringNLogTest : LocalConnectionStringNLogTest; } return connectionString; } /// <summary> /// AppVeyor connectionstring for SQL 2019, see https://www.appveyor.com/docs/services-databases/ /// </summary> private const string AppVeyorConnectionStringMaster = @"Server=(local)\SQL2019;Database=master;User ID=sa;Password=<PASSWORD>!"; private const string AppVeyorConnectionStringNLogTest = @"Server=(local)\SQL2019;Database=NLogTest;User ID=sa;Password=<PASSWORD>!"; private const string LocalConnectionStringMaster = @"Data Source=(localdb)\MSSQLLocalDB; Database=master; Integrated Security=True;"; private const string LocalConnectionStringNLogTest = @"Data Source=(localdb)\MSSQLLocalDB; Database=NLogTest; Integrated Security=True;"; public static void CreateDatabase(bool isAppVeyor) { var connectionString = GetMasterConnectionString(isAppVeyor); IssueCommand(IsAppVeyor(), "CREATE DATABASE NLogTest", connectionString); } public static bool NLogTestDatabaseExists(bool isAppVeyor) { var connectionString = GetMasterConnectionString(isAppVeyor); var dbId = IssueScalarQuery(IsAppVeyor(), "select db_id('NLogTest')", connectionString); return dbId != null && dbId != DBNull.Value; } private static string GetMasterConnectionString(bool isAppVeyor) { return isAppVeyor ? AppVeyorConnectionStringMaster : LocalConnectionStringMaster; } public static void IssueCommand(bool isAppVeyor, string commandString, string connectionString = null) { using (var connection = new SqlConnection(connectionString ?? GetConnectionString(isAppVeyor))) { connection.Open(); if (connectionString is null) connection.ChangeDatabase("NLogTest"); using (var command = new SqlCommand(commandString, connection)) { command.ExecuteNonQuery(); } } } public static object IssueScalarQuery(bool isAppVeyor, string commandString, string connectionString = null) { using (var connection = new SqlConnection(connectionString ?? GetConnectionString(isAppVeyor))) { connection.Open(); if (connectionString is null) connection.ChangeDatabase("NLogTest"); using (var command = new SqlCommand(commandString, connection)) { var scalar = command.ExecuteScalar(); return scalar; } } } /// <summary> /// Try dropping. IF fail, not exception /// </summary> public static bool TryDropDatabase(bool isAppVeyor) { try { if (NLogTestDatabaseExists(isAppVeyor)) { var connectionString = GetMasterConnectionString(isAppVeyor); IssueCommand(isAppVeyor, "ALTER DATABASE [NLogTest] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE NLogTest;", connectionString); return true; } return false; } catch (Exception) { //ignore return false; } } } protected static bool IsAppVeyor() { var val = Environment.GetEnvironmentVariable("APPVEYOR"); return val != null && val.Equals("true", StringComparison.OrdinalIgnoreCase); } protected static bool IsLinux() { var val = Environment.GetEnvironmentVariable("WINDIR"); return string.IsNullOrEmpty(val); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Text; using NLog.Targets; using Xunit; namespace NLog.UnitTests.Targets { /// <summary> /// Test via <see cref="IJsonConverter" /> path /// </summary> public class DefaultJsonSerializerClassTests : NLogTestBase { private static readonly object _testSyncObject = new object(); private interface IExcludedInterface { } private class ExcludedClass : IExcludedInterface { public string ExcludedString { get; set; } public override string ToString() { return "Skipped"; } } private class IncludedClass { public string IncludedString { get; set; } } private class ContainerClass { public string S { get; set; } public ExcludedClass Excluded { get; set; } public IncludedClass Included { get; set; } } private static ContainerClass BuildSampleObject() { var testObject = new ContainerClass { S = "sample", Excluded = new ExcludedClass { ExcludedString = "shouldn't be serialized" }, Included = new IncludedClass { IncludedString = "serialized" } }; return testObject; } [Fact] public void SimpleValue_RegistersSerializeAsToString_ConvertsValue() { var logFactory = new LogFactory(); logFactory.Setup().SetupSerialization(s => s.RegisterObjectTransformation<System.IO.MemoryStream>(o => o.Capacity)); var testObject = new System.IO.MemoryStream(42); var sb = new StringBuilder(); var options = new JsonSerializeOptions(); var jsonSerializer = new DefaultJsonSerializer(logFactory.ServiceRepository); jsonSerializer.SerializeObject(testObject, sb, options); Assert.Equal($"{testObject.Capacity}", sb.ToString()); } [Fact] public void IExcludedInterfaceSerializer_RegistersSerializeAsToString_InvokesToString() { var testObject = BuildSampleObject(); var sb = new StringBuilder(); var options = new JsonSerializeOptions(); var logFactory = new LogFactory(); logFactory.Setup().SetupSerialization(s => s.RegisterObjectTransformation<IExcludedInterface>(o => o.ToString())); var jsonSerializer = new DefaultJsonSerializer(logFactory.ServiceRepository); jsonSerializer.SerializeObject(testObject, sb, options); const string expectedValue = @"{""S"":""sample"", ""Excluded"":""Skipped"", ""Included"":{""IncludedString"":""serialized""}}"; Assert.Equal(expectedValue, sb.ToString()); } [Fact] public void ExcludedClassSerializer_RegistersSerializeAsToString_InvokesToString() { var testObject = BuildSampleObject(); var sb = new StringBuilder(); var options = new JsonSerializeOptions(); var logFactory = new LogFactory(); logFactory.Setup().SetupSerialization(s => s.RegisterObjectTransformation(typeof(ExcludedClass), o => o.ToString())); var jsonSerializer = new DefaultJsonSerializer(logFactory.ServiceRepository); jsonSerializer.SerializeObject(testObject, sb, options); const string expectedValue = @"{""S"":""sample"", ""Excluded"":""Skipped"", ""Included"":{""IncludedString"":""serialized""}}"; Assert.Equal(expectedValue, sb.ToString()); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Reflection; using NLog.Internal; /// <summary> /// Default implementation of <see cref="IPropertyTypeConverter"/> /// </summary> internal class PropertyTypeConverter : IPropertyTypeConverter { /// <summary> /// Singleton instance of the serializer. /// </summary> public static PropertyTypeConverter Instance { get; } = new PropertyTypeConverter(); private static Dictionary<Type, Func<string, string, IFormatProvider, object>> StringConverterLookup => _stringConverters ?? (_stringConverters = BuildStringConverterLookup()); private static Dictionary<Type, Func<string, string, IFormatProvider, object>> _stringConverters; private static Dictionary<Type, Func<string, string, IFormatProvider, object>> BuildStringConverterLookup() { return new Dictionary<Type, Func<string, string, IFormatProvider, object>>() { { typeof(System.Text.Encoding), (stringvalue, format, formatProvider) => ConvertToEncoding(stringvalue) }, { typeof(System.Globalization.CultureInfo), (stringvalue, format, formatProvider) => new System.Globalization.CultureInfo(stringvalue) }, { typeof(Type), (stringvalue, format, formatProvider) => ConvertToType(stringvalue, true) }, { typeof(NLog.Targets.LineEndingMode), (stringvalue, format, formatProvider) => NLog.Targets.LineEndingMode.FromString(stringvalue) }, { typeof(LogLevel), (stringvalue, format, formatProvider) => LogLevel.FromString(stringvalue) }, { typeof(Uri), (stringvalue, format, formatProvider) => new Uri(stringvalue) }, { typeof(DateTime), (stringvalue, format, formatProvider) => ConvertToDateTime(format, formatProvider, stringvalue) }, { typeof(DateTimeOffset), (stringvalue, format, formatProvider) => ConvertToDateTimeOffset(format, formatProvider, stringvalue) }, { typeof(TimeSpan), (stringvalue, format, formatProvider) => ConvertToTimeSpan(format, formatProvider, stringvalue) }, { typeof(Guid), (stringvalue, format, formatProvider) => ConvertGuid(format, stringvalue) }, }; } [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2057")] internal static Type ConvertToType(string stringvalue, bool throwOnError) { return Type.GetType(stringvalue, throwOnError); } internal static bool IsComplexType(Type type) { return !type.IsValueType() && !typeof(IConvertible).IsAssignableFrom(type) && !StringConverterLookup.ContainsKey(type) && type.GetFirstCustomAttribute<System.ComponentModel.TypeConverterAttribute>() is null; } /// <inheritdoc/> public object Convert(object propertyValue, Type propertyType, string format, IFormatProvider formatProvider) { if (propertyValue is null || propertyType is null || propertyType == typeof(object)) { return propertyValue; // No type conversion required } var propertyValueType = propertyValue.GetType(); if (propertyType.Equals(propertyValueType)) { return propertyValue; // Same type } var nullableType = Nullable.GetUnderlyingType(propertyType); if (nullableType != null) { if (nullableType.Equals(propertyValueType)) { return propertyValue; // Same type } if (propertyValue is string propertyString && StringHelpers.IsNullOrWhiteSpace(propertyString)) { return null; } propertyType = nullableType; } return ChangeObjectType(propertyValue, propertyType, format, formatProvider); } private static bool TryConvertFromString(string propertyString, Type propertyType, string format, IFormatProvider formatProvider, out object propertyValue) { propertyValue = propertyString = propertyString.Trim(); if (StringConverterLookup.TryGetValue(propertyType, out var converter)) { propertyValue = converter.Invoke(propertyString, format, formatProvider); return true; } if (propertyType.IsEnum()) { return NLog.Common.ConversionHelpers.TryParseEnum(propertyString, propertyType, out propertyValue); } if (PropertyHelper.TryTypeConverterConversion(propertyType, propertyString, out var convertedValue)) { propertyValue = convertedValue; return true; } return false; } private static object ChangeObjectType(object propertyValue, Type propertyType, string format, IFormatProvider formatProvider) { if (propertyValue is string propertyString && TryConvertFromString(propertyString, propertyType, format, formatProvider, out propertyValue)) { return propertyValue; } if (propertyValue is IConvertible convertibleValue) { var typeCode = convertibleValue.GetTypeCode(); #if !NETSTANDARD1_3 && !NETSTANDARD1_5 if (typeCode == TypeCode.DBNull) return convertibleValue; #endif if (typeCode == TypeCode.Empty) return null; } else if (TryConvertToType(propertyValue, propertyType, out var convertedValue)) { return convertedValue; } if (!string.IsNullOrEmpty(format) && propertyValue is IFormattable formattableValue) { propertyValue = formattableValue.ToString(format, formatProvider); } return System.Convert.ChangeType(propertyValue, propertyType, formatProvider); } [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2026")] [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2067")] [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2072")] private static bool TryConvertToType(object propertyValue, Type propertyType, out object convertedValue) { if (propertyValue is null || propertyType.IsAssignableFrom(propertyValue.GetType())) { convertedValue = null; return false; } var typeConverter = System.ComponentModel.TypeDescriptor.GetConverter(propertyValue.GetType()); if (typeConverter != null && typeConverter.CanConvertTo(propertyType)) { convertedValue = typeConverter.ConvertTo(propertyValue, propertyType); return true; } convertedValue = null; return false; } private static object ConvertGuid(string format, string propertyString) { #if !NET35 return string.IsNullOrEmpty(format) ? Guid.Parse(propertyString) : Guid.ParseExact(propertyString, format); #else return new Guid(propertyString); #endif } private static object ConvertToEncoding(string stringValue) { stringValue = stringValue.Trim(); if (string.Equals(stringValue, nameof(System.Text.Encoding.UTF8), StringComparison.OrdinalIgnoreCase)) stringValue = System.Text.Encoding.UTF8.WebName; // Support utf8 without hyphen (And not just Utf-8) return System.Text.Encoding.GetEncoding(stringValue); } private static object ConvertToTimeSpan(string format, IFormatProvider formatProvider, string propertyString) { #if !NET35 if (!string.IsNullOrEmpty(format)) return TimeSpan.ParseExact(propertyString, format, formatProvider); return TimeSpan.Parse(propertyString, formatProvider); #else return TimeSpan.Parse(propertyString); #endif } private static object ConvertToDateTimeOffset(string format, IFormatProvider formatProvider, string propertyString) { if (!string.IsNullOrEmpty(format)) return DateTimeOffset.ParseExact(propertyString, format, formatProvider); return DateTimeOffset.Parse(propertyString, formatProvider); } private static object ConvertToDateTime(string format, IFormatProvider formatProvider, string propertyString) { if (!string.IsNullOrEmpty(format)) return DateTime.ParseExact(propertyString, format, formatProvider); return DateTime.Parse(propertyString, formatProvider); } } } <file_sep>using System; using NLog; using NLog.Targets; using NLog.Targets.Wrappers; class Example { static void Main(string[] args) { try { NLog.Internal.InternalLogger.LogToConsole = true; NLog.Internal.InternalLogger.LogLevel = LogLevel.Trace; Console.WriteLine("Setting up the target..."); MailTarget target = new MailTarget(); target.SmtpServer = "192.168.0.15"; target.From = "<EMAIL>"; target.To = "<EMAIL>"; target.Subject = "sample subject"; target.Body = "${message}${newline}"; BufferingTargetWrapper buffer = new BufferingTargetWrapper(target, 5); NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(buffer, LogLevel.Debug); Console.WriteLine("Sending..."); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message 1"); logger.Debug("log message 2"); logger.Debug("log message 3"); logger.Debug("log message 4"); logger.Debug("log message 5"); logger.Debug("log message 6"); logger.Debug("log message 7"); logger.Debug("log message 8"); // this should send 2 mails - one with messages 1..5, the other with messages 6..8 Console.WriteLine("Sent."); } catch (Exception ex) { Console.WriteLine("EX: {0}", ex); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.IO; using System.Linq; using System.Reflection; using NLog.Common; /// <summary> /// Helpers for <see cref="Assembly"/>. /// </summary> internal static class AssemblyHelpers { /// <summary> /// Gets all usable exported types from the given assembly. /// </summary> /// <param name="assembly">Assembly to scan.</param> /// <returns>Usable types from the given assembly.</returns> /// <remarks>Types which cannot be loaded are skipped.</remarks> [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming - Allow extension loading from config", "IL2026")] [Obsolete("Instead use NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public static Type[] SafeGetTypes(Assembly assembly) { try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException typeLoadException) { var result = typeLoadException.Types?.Where(t => t != null)?.ToArray() ?? ArrayHelper.Empty<Type>(); InternalLogger.Warn(typeLoadException, "Loaded {0} valid types from Assembly: {1}", result.Length, assembly.FullName); foreach (var ex in typeLoadException.LoaderExceptions ?? ArrayHelper.Empty<Exception>()) { InternalLogger.Warn(ex, "Type load exception."); } return result; } catch (Exception ex) { InternalLogger.Warn(ex, "Failed to load types from Assembly: {0}", assembly.FullName); return ArrayHelper.Empty<Type>(); } } #if !NETSTANDARD1_3 [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] public static string GetAssemblyFileLocation(Assembly assembly) { string assemblyFullName = string.Empty; try { if (assembly is null) { return string.Empty; } assemblyFullName = assembly.FullName; #if NETSTANDARD if (string.IsNullOrEmpty(assembly.Location)) { // Assembly with no actual location should be skipped (Avoid PlatformNotSupportedException) InternalLogger.Debug("Ignoring assembly location because location is empty: {0}", assemblyFullName); return string.Empty; } #endif Uri assemblyCodeBase; if (!Uri.TryCreate(assembly.CodeBase, UriKind.RelativeOrAbsolute, out assemblyCodeBase)) { InternalLogger.Debug("Ignoring assembly location because code base is unknown: '{0}' ({1})", assembly.CodeBase, assemblyFullName); return string.Empty; } var assemblyLocation = Path.GetDirectoryName(assemblyCodeBase.LocalPath); if (string.IsNullOrEmpty(assemblyLocation)) { InternalLogger.Debug("Ignoring assembly location because it is not a valid directory: '{0}' ({1})", assemblyCodeBase.LocalPath, assemblyFullName); return string.Empty; } DirectoryInfo directoryInfo = new DirectoryInfo(assemblyLocation); if (!directoryInfo.Exists) { InternalLogger.Debug("Ignoring assembly location because directory doesn't exists: '{0}' ({1})", assemblyLocation, assemblyFullName); return string.Empty; } InternalLogger.Debug("Found assembly location directory: '{0}' ({1})", directoryInfo.FullName, assemblyFullName); return directoryInfo.FullName; } catch (System.PlatformNotSupportedException ex) { InternalLogger.Warn(ex, "Ignoring assembly location because assembly lookup is not supported: {0}", assemblyFullName); if (ex.MustBeRethrown()) { throw; } return string.Empty; } catch (System.Security.SecurityException ex) { InternalLogger.Warn(ex, "Ignoring assembly location because assembly lookup is not allowed: {0}", assemblyFullName); if (ex.MustBeRethrown()) { throw; } return string.Empty; } catch (UnauthorizedAccessException ex) { InternalLogger.Warn(ex, "Ignoring assembly location because assembly lookup is not allowed: {0}", assemblyFullName); if (ex.MustBeRethrown()) { throw; } return string.Empty; } } #endif } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.ComponentModel; using System.Globalization; using System.Text; using JetBrains.Annotations; using NLog.Common; using NLog.Config; using NLog.Internal; namespace NLog.Layouts { /// <summary> /// Typed Layout for easy conversion from NLog Layout logic to a simple value (ex. integer or enum) /// </summary> /// <typeparam name="T"></typeparam> [ThreadAgnostic] [AppDomainFixedOutput] public sealed class Layout<T> : Layout, ITypedLayout, IEquatable<T> { private readonly Layout _innerLayout; private readonly CultureInfo _parseFormatCulture; private readonly string _parseFormat; private string _previousStringValue; private object _previousValue; private readonly T _fixedValue; /// <summary> /// Is fixed value? /// </summary> public bool IsFixed => _innerLayout is null; /// <summary> /// Fixed value /// </summary> public T FixedValue => _fixedValue; private object FixedObjectValue => IsFixed ? (_previousValue ?? (_previousValue = _fixedValue)) : null; object ITypedLayout.FixedObjectValue => FixedObjectValue; Layout ITypedLayout.InnerLayout => _innerLayout; Type ITypedLayout.ValueType => typeof(T); private IPropertyTypeConverter ValueTypeConverter => _valueTypeConverter ?? (_valueTypeConverter = ResolveService<IPropertyTypeConverter>()); IPropertyTypeConverter _valueTypeConverter; /// <summary> /// Initializes a new instance of the <see cref="Layout{T}" /> class. /// </summary> /// <param name="layout">Dynamic NLog Layout</param> public Layout(Layout layout) :this(layout, null, CultureInfo.InvariantCulture) { } /// <summary> /// Initializes a new instance of the <see cref="Layout{T}" /> class. /// </summary> /// <param name="layout">Dynamic NLog Layout</param> /// <param name="parseValueFormat">Format used for parsing string-value into result value type</param> /// <param name="parseValueCulture">Culture used for parsing string-value into result value type</param> public Layout(Layout layout, string parseValueFormat, CultureInfo parseValueCulture) { if (PropertyTypeConverter.IsComplexType(typeof(T))) { throw new NLogConfigurationException($"Layout<{typeof(T).ToString()}> not supported. Immutable value type is recommended"); } if (!TryParseFixedValue(layout, parseValueFormat, parseValueCulture, ref _fixedValue)) { _innerLayout = layout; _parseFormat = parseValueFormat; _parseFormatCulture = parseValueCulture; } } /// <summary> /// Initializes a new instance of the <see cref="Layout{T}" /> class. /// </summary> /// <param name="value">Fixed value</param> public Layout(T value) { _fixedValue = value; } /// <summary> /// Render Value /// </summary> /// <param name="logEvent">Log event for rendering</param> /// <param name="defaultValue">Fallback value when no value available</param> /// <returns>Result value when available, else fallback to defaultValue</returns> internal T RenderTypedValue([CanBeNull] LogEventInfo logEvent, T defaultValue = default(T)) { return RenderTypedValue(logEvent, null, defaultValue); } internal T RenderTypedValue([CanBeNull] LogEventInfo logEvent, [CanBeNull] StringBuilder stringBuilder, T defaultValue) { if (IsFixed) return _fixedValue; else return RenderTypedValue<T>(logEvent, stringBuilder, defaultValue); } object ITypedLayout.RenderValue(LogEventInfo logEvent, object defaultValue) { var value = IsFixed ? FixedObjectValue : RenderTypedValue(logEvent, null, defaultValue); if (ReferenceEquals(value, defaultValue) && ReferenceEquals(defaultValue, string.Empty) && typeof(T) != typeof(string)) return default(T); // Translate defaultValue = string.Empty into unspecified defaultValue else return value; } /// <summary> /// Renders the value and converts the value into string format /// </summary> /// <remarks> /// Only to implement abstract method from <see cref="Layout"/>, and only used when calling <see cref="Layout.Render(LogEventInfo)"/> /// </remarks> protected override string GetFormattedMessage(LogEventInfo logEvent) { var value = IsFixed ? FixedObjectValue : RenderTypedValue<object>(logEvent, null, null); var formatProvider = logEvent.FormatProvider ?? LoggingConfiguration?.DefaultCultureInfo; return Convert.ToString(value, formatProvider); } /// <inheritdoc/> protected override void InitializeLayout() { base.InitializeLayout(); _innerLayout?.Initialize(LoggingConfiguration ?? _innerLayout.LoggingConfiguration); ThreadAgnostic = _innerLayout?.ThreadAgnostic ?? true; MutableUnsafe = _innerLayout?.MutableUnsafe ?? false; StackTraceUsage = _innerLayout?.StackTraceUsage ?? StackTraceUsage.None; _valueTypeConverter = null; _previousStringValue = null; _previousValue = null; } /// <inheritdoc/> protected override void CloseLayout() { _innerLayout?.Close(); _valueTypeConverter = null; _previousStringValue = null; _previousValue = null; base.CloseLayout(); } /// <inheritdoc/> public override void Precalculate(LogEventInfo logEvent) { PrecalculateInnerLayout(logEvent, null); } /// <inheritdoc/> internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { PrecalculateInnerLayout(logEvent, target); } private void PrecalculateInnerLayout(LogEventInfo logEvent, StringBuilder target) { if (IsFixed || (_innerLayout.ThreadAgnostic && !_innerLayout.MutableUnsafe)) return; if (TryRenderObjectValue(logEvent, target, out var cachedValue)) { logEvent.AddCachedLayoutValue(this, cachedValue); } } private TValueType RenderTypedValue<TValueType>(LogEventInfo logEvent, StringBuilder stringBuilder, TValueType defaultValue) { if (logEvent is null) return defaultValue; if (logEvent.TryGetCachedLayoutValue(this, out var cachedValue)) { if (cachedValue is null) return defaultValue; else return (TValueType)cachedValue; } if (TryRenderObjectValue(logEvent, stringBuilder, out var value)) { if (value is null) return defaultValue; else return (TValueType)value; } return defaultValue; } private bool TryRenderObjectValue(LogEventInfo logEvent, StringBuilder stringBuilder, out object value) { if (!IsInitialized) { Initialize(LoggingConfiguration ?? _innerLayout?.LoggingConfiguration); } if (_innerLayout.TryGetRawValue(logEvent, out var rawValue)) { if (rawValue is string rawStringValue) { if (string.IsNullOrEmpty(rawStringValue)) { return TryParseValueFromString(rawStringValue, _parseFormat, _parseFormatCulture, out value); } } else { if (rawValue is null) { value = null; return true; } return TryParseValueFromObject(rawValue, _parseFormat, _parseFormatCulture, out value); } } var previousStringValue = _previousStringValue; var previousValue = _previousValue; var stringValue = RenderStringValue(logEvent, stringBuilder, previousStringValue); if (previousStringValue != null && previousStringValue == stringValue) { value = previousValue; return true; } if (TryParseValueFromString(stringValue, _parseFormat, _parseFormatCulture, out value)) { if (string.IsNullOrEmpty(previousStringValue) || stringValue?.Length < 3) { // Only cache initial value to avoid constantly changing values like CorrelationId (Guid) or DateTime.UtcNow _previousValue = value; _previousStringValue = stringValue; } return true; } return false; } private string RenderStringValue(LogEventInfo logEvent, StringBuilder stringBuilder, string previousStringValue) { if (_innerLayout is SimpleLayout simpleLayout && simpleLayout.IsSimpleStringText) { return simpleLayout.Render(logEvent); } if (stringBuilder?.Length == 0) { _innerLayout.Render(logEvent, stringBuilder); if (stringBuilder.Length == 0) return string.Empty; else if (!string.IsNullOrEmpty(previousStringValue) && stringBuilder.EqualTo(previousStringValue)) return previousStringValue; else return stringBuilder.ToString(); } else { return _innerLayout.Render(logEvent); } } private bool TryParseFixedValue(Layout layout, string parseValueFormat, CultureInfo parseValueCulture, ref T fixedValue) { if (layout is SimpleLayout simpleLayout && simpleLayout.IsFixedText) { if (!string.IsNullOrEmpty(simpleLayout.FixedText)) { try { fixedValue = (T)ParseValueFromObject(simpleLayout.FixedText, parseValueFormat, parseValueCulture); return true; } catch (Exception ex) { var configException = new NLogConfigurationException($"Failed converting into type {typeof(T)}. Value='{simpleLayout.FixedText}'", ex); if (configException.MustBeRethrown()) throw configException; } } else if (typeof(T) == typeof(string)) { fixedValue = (T)(object)simpleLayout.FixedText; return true; } else if (Nullable.GetUnderlyingType(typeof(T)) != null) { fixedValue = default(T); return true; } } else if (layout is null) { fixedValue = default(T); return true; } fixedValue = default(T); return false; } private bool TryParseValueFromString(string stringValue, string parseValueFormat, CultureInfo parseValueCulture, out object parsedValue) { if (string.IsNullOrEmpty(stringValue)) { parsedValue = typeof(T) == typeof(string) ? stringValue : null; return true; } return TryParseValueFromObject(stringValue, parseValueFormat, parseValueCulture, out parsedValue); } bool ITypedLayout.TryParseValueFromString(string stringValue, out object parsedValue) { return TryParseValueFromString(stringValue, _parseFormat, _parseFormatCulture, out parsedValue); } bool TryParseValueFromObject(object rawValue, string parseValueFormat, CultureInfo parseValueCulture, out object parsedValue) { try { parsedValue = ParseValueFromObject(rawValue, parseValueFormat, parseValueCulture); return true; } catch (Exception ex) { parsedValue = null; InternalLogger.Warn(ex, "Failed converting object '{0}' of type {1} into type {2}", rawValue, rawValue?.GetType(), typeof(T)); return false; } } private object ParseValueFromObject(object rawValue, string parseValueFormat, CultureInfo parseValueCulture) { return ValueTypeConverter.Convert(rawValue, typeof(T), parseValueFormat, parseValueCulture); } /// <inheritdoc/> public override string ToString() { return IsFixed ? (FixedObjectValue?.ToString() ?? "null") : (_innerLayout?.ToString() ?? base.ToString()); } /// <inheritdoc/> public override bool Equals(object obj) { if (IsFixed) { // Support property-compare if (obj is Layout<T> other) return other.IsFixed && object.Equals(FixedObjectValue, other.FixedObjectValue); else if (obj is T) return object.Equals(FixedObjectValue, obj); else return ReferenceEquals(obj, FixedObjectValue); } else { return ReferenceEquals(this, obj); // Support LogEventInfo.LayoutCache } } /// <summary> /// Implements Equals using <see cref="FixedValue"/> /// </summary> public bool Equals(T other) { // Support property-compare return IsFixed && object.Equals(FixedObjectValue, other); } /// <inheritdoc/> public override int GetHashCode() { if (IsFixed) return FixedObjectValue?.GetHashCode() ?? typeof(T).GetHashCode(); // Support property-compare else return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(this); // Support LogEventInfo.LayoutCache } /// <summary> /// Converts a given value to a <see cref="Layout{T}" />. /// </summary> /// <param name="value">Text to be converted.</param> public static implicit operator Layout<T>(T value) { if (object.Equals(value, default(T)) && !typeof(T).IsValueType()) return null; return new Layout<T>(value); } /// <summary> /// Converts a given text to a <see cref="Layout{T}" />. /// </summary> /// <param name="layout">Text to be converted.</param> public static implicit operator Layout<T>([Localizable(false)] string layout) { if (layout is null) return null; return new Layout<T>(layout); } /// <summary> /// Implements the operator == using <see cref="FixedValue"/> /// </summary> public static bool operator ==(Layout<T> left, T right) { return left?.Equals(right) == true || (left is null && object.Equals(right, default(T))); } /// <summary> /// Implements the operator != using <see cref="FixedValue"/> /// </summary> public static bool operator !=(Layout<T> left, T right) { return left?.Equals(right) != true && !(left is null && object.Equals(right, default(T))); } } /// <summary> /// Provides access to untyped value without knowing underlying generic type /// </summary> internal interface ITypedLayout { Layout InnerLayout { get; } Type ValueType { get; } bool IsFixed { get; } object FixedObjectValue { get; } object RenderValue(LogEventInfo logEvent, object defaultValue); bool TryParseValueFromString(string stringValue, out object parsedValue); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Contexts { using System; using System.Collections.Generic; using System.Text; using System.Threading; using Xunit; [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public class MappedDiagnosticsContextTests { /// <summary> /// Same as <see cref="MappedDiagnosticsContext" />, but there is one <see cref="MappedDiagnosticsContext"/> per each thread. /// </summary> [Fact] public void MDCTest1() { List<Exception> exceptions = new List<Exception>(); ManualResetEvent mre = new ManualResetEvent(false); int counter = 100; int remaining = counter; for (int i = 0; i < counter; ++i) { ThreadPool.QueueUserWorkItem( s => { try { MappedDiagnosticsContext.Clear(); Assert.False(MappedDiagnosticsContext.Contains("foo")); Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo")); Assert.False(MappedDiagnosticsContext.Contains("foo2")); Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo2")); Assert.Equal(0, MappedDiagnosticsContext.GetNames().Count); MappedDiagnosticsContext.Set("foo", "bar"); MappedDiagnosticsContext.Set("foo2", "bar2"); Assert.True(MappedDiagnosticsContext.Contains("foo")); Assert.Equal("bar", MappedDiagnosticsContext.Get("foo")); Assert.Equal(2, MappedDiagnosticsContext.GetNames().Count); MappedDiagnosticsContext.Remove("foo"); Assert.False(MappedDiagnosticsContext.Contains("foo")); Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo")); Assert.True(MappedDiagnosticsContext.Contains("foo2")); Assert.Equal("bar2", MappedDiagnosticsContext.Get("foo2")); Assert.Equal(1, MappedDiagnosticsContext.GetNames().Count); Assert.True(MappedDiagnosticsContext.GetNames().Contains("foo2")); Assert.Null(MappedDiagnosticsContext.GetObject("foo3")); MappedDiagnosticsContext.Set("foo3", new { One = 1 }); } catch (Exception exception) { lock (exceptions) { exceptions.Add(exception); } } finally { if (Interlocked.Decrement(ref remaining) == 0) { mre.Set(); } } }); } mre.WaitOne(); StringBuilder exceptionsMessage = new StringBuilder(); foreach (var ex in exceptions) { if (exceptionsMessage.Length > 0) { exceptionsMessage.Append("\r\n"); } exceptionsMessage.Append(ex.ToString()); } Assert.True(exceptions.Count == 0, exceptionsMessage.ToString()); } [Fact] public void MDCTest2() { List<Exception> exceptions = new List<Exception>(); ManualResetEvent mre = new ManualResetEvent(false); int counter = 100; int remaining = counter; for (int i = 0; i < counter; ++i) { ThreadPool.QueueUserWorkItem( s => { try { MappedDiagnosticsContext.Clear(); Assert.False(MappedDiagnosticsContext.Contains("foo")); Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo")); Assert.False(MappedDiagnosticsContext.Contains("foo2")); Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo2")); MappedDiagnosticsContext.Set("foo", "bar"); MappedDiagnosticsContext.Set("foo2", "bar2"); Assert.True(MappedDiagnosticsContext.Contains("foo")); Assert.Equal("bar", MappedDiagnosticsContext.Get("foo")); MappedDiagnosticsContext.Remove("foo"); Assert.False(MappedDiagnosticsContext.Contains("foo")); Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo")); Assert.True(MappedDiagnosticsContext.Contains("foo2")); Assert.Equal("bar2", MappedDiagnosticsContext.Get("foo2")); Assert.Null(MappedDiagnosticsContext.GetObject("foo3")); } catch (Exception ex) { lock (exceptions) { exceptions.Add(ex); } } finally { if (Interlocked.Decrement(ref remaining) == 0) { mre.Set(); } } }); } mre.WaitOne(); StringBuilder exceptionsMessage = new StringBuilder(); foreach (var ex in exceptions) { if (exceptionsMessage.Length > 0) { exceptionsMessage.Append("\r\n"); } exceptionsMessage.Append(ex.ToString()); } Assert.True(exceptions.Count == 0, exceptionsMessage.ToString()); } [Fact] public void timer_cannot_inherit_mappedcontext() { object getObject = null; string getValue = null; var mre = new ManualResetEvent(false); Timer thread = new Timer((s) => { try { getObject = MappedDiagnosticsContext.GetObject("DoNotExist"); getValue = MappedDiagnosticsContext.Get("DoNotExistEither"); } finally { mre.Set(); } }); thread.Change(0, Timeout.Infinite); mre.WaitOne(); Assert.Null(getObject); Assert.Empty(getValue); } [Fact] public void disposable_removes_item() { const string itemNotRemovedKey = "itemNotRemovedKey"; const string itemRemovedKey = "itemRemovedKey"; MappedDiagnosticsContext.Clear(); MappedDiagnosticsContext.Set(itemNotRemovedKey, "itemNotRemoved"); using (MappedDiagnosticsContext.SetScoped(itemRemovedKey, "itemRemoved")) { Assert.Equal(MappedDiagnosticsContext.GetNames(), new[] { itemNotRemovedKey, itemRemovedKey }); } Assert.Equal(MappedDiagnosticsContext.GetNames(), new[] { itemNotRemovedKey }); } [Fact] public void dispose_is_idempotent() { const string itemKey = "itemKey"; MappedDiagnosticsContext.Clear(); IDisposable disposable = MappedDiagnosticsContext.SetScoped(itemKey, "item1"); disposable.Dispose(); Assert.False(MappedDiagnosticsContext.Contains(itemKey)); //This item shouldn't be removed since it is not the disposable one MappedDiagnosticsContext.Set(itemKey, "item2"); disposable.Dispose(); Assert.True(MappedDiagnosticsContext.Contains(itemKey)); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Contexts { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using NLog.Internal; using Xunit; [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public class MappedDiagnosticsLogicalContextTests { public MappedDiagnosticsLogicalContextTests() { MappedDiagnosticsLogicalContext.Clear(); } [Fact] public void given_item_exists_when_getting_item_should_return_item_for_objecttype_2() { string key = "testKey1"; object value = 5; MappedDiagnosticsLogicalContext.Set(key, value); string expected = "5"; string actual = MappedDiagnosticsLogicalContext.Get(key); Assert.Equal(expected, actual); } [Fact] public void given_item_exists_when_getting_item_should_return_item_for_objecttype() { string key = "testKey2"; object value = DateTime.Now; MappedDiagnosticsLogicalContext.Set(key, value); object actual = MappedDiagnosticsLogicalContext.GetObject(key); Assert.Equal(value, actual); } [Fact] public void given_no_item_exists_when_getting_item_should_return_null() { Assert.Null(MappedDiagnosticsLogicalContext.GetObject("itemThatShouldNotExist")); } [Fact] public void given_no_item_exists_when_getting_item_should_return_empty_string() { Assert.Empty(MappedDiagnosticsLogicalContext.Get("itemThatShouldNotExist")); } [Fact] public void given_item_exists_when_getting_item_should_return_item() { const string key = "Key"; const string item = "Item"; MappedDiagnosticsLogicalContext.Set(key, item); Assert.Equal(item, MappedDiagnosticsLogicalContext.Get(key)); } [Fact] public void given_item_does_not_exist_when_setting_item_should_contain_item() { const string key = "Key"; const string item = "Item"; MappedDiagnosticsLogicalContext.Set(key, item); Assert.True(MappedDiagnosticsLogicalContext.Contains(key)); } [Fact] public void given_item_exists_when_setting_item_should_not_throw() { const string key = "Key"; const string item = "Item"; MappedDiagnosticsLogicalContext.Set(key, item); var exRecorded = Record.Exception(() => MappedDiagnosticsLogicalContext.Set(key, item)); Assert.Null(exRecorded); } [Fact] public void given_item_exists_when_setting_item_should_update_item() { const string key = "Key"; const string item = "Item"; const string newItem = "NewItem"; MappedDiagnosticsLogicalContext.Set(key, item); MappedDiagnosticsLogicalContext.Set(key, newItem); Assert.Equal(newItem, MappedDiagnosticsLogicalContext.Get(key)); } [Fact] public void given_no_item_exists_when_getting_items_should_return_empty_collection() { Assert.Equal(0, MappedDiagnosticsLogicalContext.GetNames().Count); } [Fact] public void given_item_exists_when_getting_items_should_return_that_item() { const string key = "Key"; MappedDiagnosticsLogicalContext.Set(key, "Item"); Assert.Equal(1, MappedDiagnosticsLogicalContext.GetNames().Count); Assert.True(MappedDiagnosticsLogicalContext.GetNames().Contains("Key")); } [Fact] public void given_item_exists_after_removing_item_when_getting_items_should_not_contain_item() { const string keyThatRemains1 = "Key1"; const string keyThatRemains2 = "Key2"; const string keyThatIsRemoved = "KeyR"; MappedDiagnosticsLogicalContext.Set(keyThatRemains1, "7"); MappedDiagnosticsLogicalContext.Set(keyThatIsRemoved, 7); MappedDiagnosticsLogicalContext.Set(keyThatRemains2, 8); MappedDiagnosticsLogicalContext.Remove(keyThatIsRemoved); Assert.Equal(2, MappedDiagnosticsLogicalContext.GetNames().Count); Assert.False(MappedDiagnosticsLogicalContext.GetNames().Contains(keyThatIsRemoved)); } [Fact] public void given_item_does_not_exist_when_checking_if_context_contains_should_return_false() { Assert.False(MappedDiagnosticsLogicalContext.Contains("keyForItemThatDoesNotExist")); } [Fact] public void given_item_exists_when_checking_if_context_contains_should_return_true() { const string key = "Key"; MappedDiagnosticsLogicalContext.Set(key, "Item"); Assert.True(MappedDiagnosticsLogicalContext.Contains(key)); } [Fact] public void given_item_exists_when_removing_item_should_not_contain_item() { const string keyForItemThatShouldExist = "Key"; const string itemThatShouldExist = "Item"; MappedDiagnosticsLogicalContext.Set(keyForItemThatShouldExist, itemThatShouldExist); MappedDiagnosticsLogicalContext.Remove(keyForItemThatShouldExist); Assert.False(MappedDiagnosticsLogicalContext.Contains(keyForItemThatShouldExist)); } [Fact] public void given_item_does_not_exist_when_removing_item_should_not_throw() { const string keyForItemThatShouldExist = "Key"; var exRecorded = Record.Exception(() => MappedDiagnosticsLogicalContext.Remove(keyForItemThatShouldExist)); Assert.Null(exRecorded); } [Fact] public void given_item_does_not_exist_when_clearing_should_not_throw() { var exRecorded = Record.Exception(() => MappedDiagnosticsLogicalContext.Clear()); Assert.Null(exRecorded); } [Fact] public void given_item_exists_when_clearing_should_not_contain_item() { const string key = "Key"; MappedDiagnosticsLogicalContext.Set(key, "Item"); MappedDiagnosticsLogicalContext.Clear(); Assert.False(MappedDiagnosticsLogicalContext.Contains(key)); } [Fact] public void given_multiple_threads_running_asynchronously_when_setting_and_getting_values_should_return_thread_specific_values() { const string key = "Key"; const string valueForLogicalThread1 = "ValueForTask1"; const string valueForLogicalThread2 = "ValueForTask2"; const string valueForLogicalThread3 = "ValueForTask3"; MappedDiagnosticsLogicalContext.Clear(true); var task1 = Task.Factory.StartNew(() => { MappedDiagnosticsLogicalContext.Set(key, valueForLogicalThread1); return MappedDiagnosticsLogicalContext.Get(key); }); var task2 = Task.Factory.StartNew(() => { MappedDiagnosticsLogicalContext.Set(key, valueForLogicalThread2); return MappedDiagnosticsLogicalContext.Get(key); }); var task3 = Task.Factory.StartNew(() => { MappedDiagnosticsLogicalContext.Set(key, valueForLogicalThread3); return MappedDiagnosticsLogicalContext.Get(key); }); Task.WaitAll(task1, task2, task3); Assert.Equal(valueForLogicalThread1, task1.Result); Assert.Equal(valueForLogicalThread2, task2.Result); Assert.Equal(valueForLogicalThread3, task3.Result); } [Fact] public void parent_thread_assigns_different_values_to_childs() { const string parentKey = "ParentKey"; const string parentValueForLogicalThread1 = "Parent1"; const string parentValueForLogicalThread2 = "Parent2"; const string childKey = "ChildKey"; const string valueForChildThread1 = "Child1"; const string valueForChildThread2 = "Child2"; MappedDiagnosticsLogicalContext.Clear(true); var exitAllTasks = new ManualResetEvent(false); MappedDiagnosticsLogicalContext.Set(parentKey, parentValueForLogicalThread1); var task1 = Task.Factory.StartNew(() => { MappedDiagnosticsLogicalContext.Set(childKey, valueForChildThread1); exitAllTasks.WaitOne(); return MappedDiagnosticsLogicalContext.Get(parentKey) + "," + MappedDiagnosticsLogicalContext.Get(childKey); }); MappedDiagnosticsLogicalContext.Set(parentKey, parentValueForLogicalThread2); var task2 = Task.Factory.StartNew(() => { MappedDiagnosticsLogicalContext.Set(childKey, valueForChildThread2); exitAllTasks.WaitOne(); return MappedDiagnosticsLogicalContext.Get(parentKey) + "," + MappedDiagnosticsLogicalContext.Get(childKey); }); exitAllTasks.Set(); Task.WaitAll(task1, task2); Assert.Equal(parentValueForLogicalThread1 + "," + valueForChildThread1, task1.Result); Assert.Equal(parentValueForLogicalThread2 + "," + valueForChildThread2, task2.Result); } [Fact] public void timer_cannot_inherit_mappedcontext() { const string parentKey = nameof(timer_cannot_inherit_mappedcontext); const string parentValueForLogicalThread1 = "Parent1"; object getObject = null; string getValue = null; var mre = new ManualResetEvent(false); Timer thread = new Timer((s) => { try { getObject = MappedDiagnosticsLogicalContext.GetObject(parentKey); getValue = MappedDiagnosticsLogicalContext.Get(parentKey); } finally { mre.Set(); } }); MappedDiagnosticsLogicalContext.Clear(true); MappedDiagnosticsLogicalContext.Set(parentKey, parentValueForLogicalThread1); thread.Change(0, Timeout.Infinite); mre.WaitOne(); Assert.Null(getObject); Assert.Empty(getValue); } [Fact] public void disposable_removes_item() { const string itemNotRemovedKey = "itemNotRemovedKey"; const string itemRemovedKey = "itemRemovedKey"; MappedDiagnosticsLogicalContext.Clear(); MappedDiagnosticsLogicalContext.Set(itemNotRemovedKey, "itemNotRemoved"); using (MappedDiagnosticsLogicalContext.SetScoped(itemRemovedKey, "itemRemoved")) { Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey, itemRemovedKey }); } Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey }); } [Fact] public void dispose_is_idempotent() { const string itemKey = "itemKey"; MappedDiagnosticsLogicalContext.Clear(); IDisposable disposable = MappedDiagnosticsLogicalContext.SetScoped(itemKey, "item1"); disposable.Dispose(); Assert.False(MappedDiagnosticsLogicalContext.Contains(itemKey)); //This item shouldn't be removed since it is not the disposable one MappedDiagnosticsLogicalContext.Set(itemKey, "item2"); disposable.Dispose(); Assert.True(MappedDiagnosticsLogicalContext.Contains(itemKey)); } #if !NET35 && !NET40 [Fact] public void disposable_multiple_items() { const string itemNotRemovedKey = "itemNotRemovedKey"; const string item1Key = "item1Key"; const string item2Key = "item2Key"; const string item3Key = "item3Key"; const string item4Key = "item4Key"; MappedDiagnosticsLogicalContext.Clear(); MappedDiagnosticsLogicalContext.Set(itemNotRemovedKey, "itemNotRemoved"); using (MappedDiagnosticsLogicalContext.SetScoped(new[] { new KeyValuePair<string, object>(item1Key, "1"), new KeyValuePair<string, object>(item2Key, "2") })) { Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey, item1Key, item2Key }); } Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey }); using (MappedDiagnosticsLogicalContext.SetScoped(new[] { new KeyValuePair<string, object>(item1Key, "1"), new KeyValuePair<string, object>(item2Key, "2"), new KeyValuePair<string, object>(item3Key, "3"), new KeyValuePair<string, object>(item4Key, "4") })) { Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey, item1Key, item2Key, item3Key, item4Key }); } Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey }); } [Fact] public void disposable_multiple_items_with_restore() { const string itemNotRemovedKey = "itemNotRemovedKey"; const string item1Key = "item1Key"; const string item2Key = "item2Key"; const string item3Key = "item3Key"; const string item4Key = "item4Key"; MappedDiagnosticsLogicalContext.Clear(); MappedDiagnosticsLogicalContext.Set(itemNotRemovedKey, "itemNotRemoved"); using (MappedDiagnosticsLogicalContext.SetScoped(new[] { new KeyValuePair<string, object>(item1Key, "1"), new KeyValuePair<string, object>(item2Key, "2") })) { Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey, item1Key, item2Key }); } Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey }); using (MappedDiagnosticsLogicalContext.SetScoped(new[] { new KeyValuePair<string, object>(item1Key, "1"), new KeyValuePair<string, object>(item2Key, "2"), new KeyValuePair<string, object>(item3Key, "3"), new KeyValuePair<string, object>(item4Key, "4") })) { using (var itemRemover = MappedDiagnosticsLogicalContext.SetScoped(new[] { new KeyValuePair<string, object>(item1Key, "111") })) { Assert.Equal("111", MappedDiagnosticsLogicalContext.Get(item1Key)); } using (MappedDiagnosticsLogicalContext.SetScoped(new[] { new KeyValuePair<string, object>(item1Key, "01"), new KeyValuePair<string, object>(item2Key, "02"), new KeyValuePair<string, object>(item3Key, "03"), new KeyValuePair<string, object>(item4Key, "04") })) { Assert.Equal("itemNotRemoved", MappedDiagnosticsLogicalContext.Get(itemNotRemovedKey)); Assert.Equal("01", MappedDiagnosticsLogicalContext.Get(item1Key)); Assert.Equal("02", MappedDiagnosticsLogicalContext.Get(item2Key)); Assert.Equal("03", MappedDiagnosticsLogicalContext.Get(item3Key)); Assert.Equal("04", MappedDiagnosticsLogicalContext.Get(item4Key)); } Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey, item1Key, item2Key, item3Key, item4Key }); Assert.Equal("itemNotRemoved", MappedDiagnosticsLogicalContext.Get(itemNotRemovedKey)); Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(item1Key)); Assert.Equal("2", MappedDiagnosticsLogicalContext.Get(item2Key)); Assert.Equal("3", MappedDiagnosticsLogicalContext.Get(item3Key)); Assert.Equal("4", MappedDiagnosticsLogicalContext.Get(item4Key)); } Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey }); } [Fact] public void disposable_fast_clear_multiple_items() { const string item1Key = "item1Key"; const string item2Key = "item2Key"; const string item3Key = "item3Key"; const string item4Key = "item4Key"; MappedDiagnosticsLogicalContext.Clear(); using (MappedDiagnosticsLogicalContext.SetScoped(new[] { new KeyValuePair<string, object>(item1Key, "1"), new KeyValuePair<string, object>(item2Key, "2") })) { Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { item1Key, item2Key }); } Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), ArrayHelper.Empty<string>()); using (MappedDiagnosticsLogicalContext.SetScoped(new[] { new KeyValuePair<string, object>(item1Key, "1"), new KeyValuePair<string, object>(item2Key, "2"), new KeyValuePair<string, object>(item3Key, "3"), new KeyValuePair<string, object>(item4Key, "4") })) { Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { item1Key, item2Key, item3Key, item4Key }); } Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), ArrayHelper.Empty<string>()); } #endif [Fact] public void given_multiple_set_invocations_mdlc_persists_only_last_value() { const string key = "key"; MappedDiagnosticsLogicalContext.Set(key, "1"); Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key)); MappedDiagnosticsLogicalContext.Set(key, 2); MappedDiagnosticsLogicalContext.Set(key, "3"); Assert.Equal("3", MappedDiagnosticsLogicalContext.Get(key)); MappedDiagnosticsLogicalContext.Remove(key); Assert.True(string.IsNullOrEmpty(MappedDiagnosticsLogicalContext.Get(key))); } [Fact] public void given_multiple_setscoped_with_restore_invocations_mdlc_persists_all_values() { const string key = "key"; using (MappedDiagnosticsLogicalContext.SetScoped(key, "1")) { Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key)); using (MappedDiagnosticsLogicalContext.SetScoped(key, 2)) { Assert.Equal(2.ToString(), MappedDiagnosticsLogicalContext.Get(key)); using (MappedDiagnosticsLogicalContext.SetScoped(key, null)) { Assert.True(string.IsNullOrEmpty(MappedDiagnosticsLogicalContext.Get(key))); } Assert.Equal(2.ToString(), MappedDiagnosticsLogicalContext.Get(key)); } Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key)); } Assert.True(string.IsNullOrEmpty(MappedDiagnosticsLogicalContext.Get(key))); } [Fact] public void given_multiple_multikey_setscoped_with_restore_invocations_mdlc_persists_all_values() { const string key1 = "key1"; const string key2 = "key2"; const string key3 = "key3"; using (MappedDiagnosticsLogicalContext.SetScoped(key1, "1")) { Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key1)); using (MappedDiagnosticsLogicalContext.SetScoped(key2, 2)) { using (MappedDiagnosticsLogicalContext.SetScoped(key3, 3)) { using (MappedDiagnosticsLogicalContext.SetScoped(key2, 22)) { Assert.Equal(22.ToString(), MappedDiagnosticsLogicalContext.Get(key2)); } Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key1)); Assert.Equal(2.ToString(), MappedDiagnosticsLogicalContext.Get(key2)); Assert.Equal(3.ToString(), MappedDiagnosticsLogicalContext.Get(key3)); } } Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key1)); } Assert.True(string.IsNullOrEmpty(MappedDiagnosticsLogicalContext.Get(key1))); } [Fact] public void given_multiple_multikey_setscoped_with_restore_invocations_dispose_differs_than_remove() { const string key1 = "key1"; const string key2 = "key2"; const string key3 = "key3"; var k1d = MappedDiagnosticsLogicalContext.SetScoped(key1, "1"); Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key1)); var k2d = MappedDiagnosticsLogicalContext.SetScoped(key2, 2); var k3d = MappedDiagnosticsLogicalContext.SetScoped(key3, 3); var k2d2 = MappedDiagnosticsLogicalContext.SetScoped(key2, 22); Assert.Equal(22.ToString(), MappedDiagnosticsLogicalContext.Get(key2)); MappedDiagnosticsLogicalContext.Remove(key2); Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key1)); Assert.NotEqual(2.ToString(), MappedDiagnosticsLogicalContext.Get(key2)); Assert.Equal(3.ToString(), MappedDiagnosticsLogicalContext.Get(key3)); MappedDiagnosticsLogicalContext.Remove(key3); MappedDiagnosticsLogicalContext.Remove(key2); Assert.Equal("1", MappedDiagnosticsLogicalContext.Get(key1)); MappedDiagnosticsLogicalContext.Remove(key1); Assert.True(string.IsNullOrEmpty(MappedDiagnosticsLogicalContext.Get(key1))); } [Fact] public void given_multiple_setscoped_with_restore_invocations_set_reset_value_stack() { const string key = "key"; using (MappedDiagnosticsLogicalContext.SetScoped(key, "1")) { using (MappedDiagnosticsLogicalContext.SetScoped(key, 2)) { using (MappedDiagnosticsLogicalContext.SetScoped(key, 3)) { Assert.Equal(3.ToString(), MappedDiagnosticsLogicalContext.Get(key)); } // 'Set' does not reset that history of 'SetScoped' MappedDiagnosticsLogicalContext.Set(key, "x"); Assert.Equal("x", MappedDiagnosticsLogicalContext.Get(key)); } // Disposing will bring back previous value despite being overriden by 'Set' Assert.Equal(1.ToString(), MappedDiagnosticsLogicalContext.Get(key)); } Assert.True(string.IsNullOrEmpty(MappedDiagnosticsLogicalContext.Get(key))); } [Fact] public void given_multiple_threads_running_asynchronously_when_setting_and_getting_values_setscoped_with_restore_should_return_thread_specific_values() { const string key = "Key"; const string initValue = "InitValue"; const string valueForLogicalThread1 = "ValueForTask1"; const string valueForLogicalThread1Next = "ValueForTask1Next"; const string valueForLogicalThread2 = "ValueForTask2"; const string valueForLogicalThread3 = "ValueForTask3"; MappedDiagnosticsLogicalContext.Clear(true); MappedDiagnosticsLogicalContext.Set(key, initValue); Assert.Equal(initValue, MappedDiagnosticsLogicalContext.Get(key)); var task1 = Task.Factory.StartNew(async () => { MappedDiagnosticsLogicalContext.SetScoped(key, valueForLogicalThread1); await Task.Delay(0).ConfigureAwait(false); MappedDiagnosticsLogicalContext.SetScoped(key, valueForLogicalThread1Next); return MappedDiagnosticsLogicalContext.Get(key); }); var task2 = Task.Factory.StartNew(() => { MappedDiagnosticsLogicalContext.SetScoped(key, valueForLogicalThread2); return MappedDiagnosticsLogicalContext.Get(key); }); var task3 = Task.Factory.StartNew(() => { MappedDiagnosticsLogicalContext.SetScoped(key, valueForLogicalThread3); return MappedDiagnosticsLogicalContext.Get(key); }); Task.WaitAll(task1, task2, task3); Assert.Equal(valueForLogicalThread1Next, task1.Result.Result); Assert.Equal(valueForLogicalThread2, task2.Result); Assert.Equal(valueForLogicalThread3, task3.Result); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Common { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using NLog.Common; using NLog.Time; using Xunit; public sealed class InternalLoggerTests : NLogTestBase, IDisposable { /// <summary> /// Test the return values of all Is[Level]Enabled() methods. /// </summary> [Fact] public void IsEnabledTests() { // Setup LogLevel to minimum named level. InternalLogger.LogLevel = LogLevel.Trace; Assert.True(InternalLogger.IsTraceEnabled); Assert.True(InternalLogger.IsDebugEnabled); Assert.True(InternalLogger.IsInfoEnabled); Assert.True(InternalLogger.IsWarnEnabled); Assert.True(InternalLogger.IsErrorEnabled); Assert.True(InternalLogger.IsFatalEnabled); // Setup LogLevel to maximum named level. InternalLogger.LogLevel = LogLevel.Fatal; Assert.False(InternalLogger.IsTraceEnabled); Assert.False(InternalLogger.IsDebugEnabled); Assert.False(InternalLogger.IsInfoEnabled); Assert.False(InternalLogger.IsWarnEnabled); Assert.False(InternalLogger.IsErrorEnabled); Assert.True(InternalLogger.IsFatalEnabled); // Switch off the internal logging. InternalLogger.LogLevel = LogLevel.Off; Assert.False(InternalLogger.IsTraceEnabled); Assert.False(InternalLogger.IsDebugEnabled); Assert.False(InternalLogger.IsInfoEnabled); Assert.False(InternalLogger.IsWarnEnabled); Assert.False(InternalLogger.IsErrorEnabled); Assert.False(InternalLogger.IsFatalEnabled); } [Fact] public void WriteToStringWriterTests() { try { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; { StringWriter writer1 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer1; // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, writer1); } { // // Reconfigure the LogWriter. StringWriter writer2 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer2; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, writer2); } { // // Reconfigure the LogWriter. StringWriter writer2 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer2; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, () => "WWW"); InternalLogger.Log(LogLevel.Error, () => "EEE"); InternalLogger.Log(LogLevel.Fatal, () => "FFF"); InternalLogger.Log(LogLevel.Trace, () => "TTT"); InternalLogger.Log(LogLevel.Debug, () => "DDD"); InternalLogger.Log(LogLevel.Info, () => "III"); TestWriter(expected, writer2); } } finally { InternalLogger.Reset(); } } [Fact] public void WriteToStringWriterWithArgsTests() { try { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW 0\nError EEE 0, 1\nFatal FFF 0, 1, 2\nTrace TTT 0, 1, 2\nDebug DDD 0, 1\nInfo III 0\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; { StringWriter writer1 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer1; // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW {0}", 0); InternalLogger.Error("EEE {0}, {1}", 0, 1); InternalLogger.Fatal("FFF {0}, {1}, {2}", 0, 1, 2); InternalLogger.Trace("TTT {0}, {1}, {2}", 0, 1, 2); InternalLogger.Debug("DDD {0}, {1}", 0, 1); InternalLogger.Info("III {0}", 0); TestWriter(expected, writer1); } { // // Reconfigure the LogWriter. StringWriter writer2 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer2; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW {0}", 0); InternalLogger.Log(LogLevel.Error, "EEE {0}, {1}", 0, 1); InternalLogger.Log(LogLevel.Fatal, "FFF {0}, {1}, {2}", 0, 1, 2); InternalLogger.Log(LogLevel.Trace, "TTT {0}, {1}, {2}", 0, 1, 2); InternalLogger.Log(LogLevel.Debug, "DDD {0}, {1}", 0, 1); InternalLogger.Log(LogLevel.Info, "III {0}", 0); TestWriter(expected, writer2); } } finally { InternalLogger.Reset(); } } /// <summary> /// Test output van een textwriter /// </summary> /// <param name="expected"></param> /// <param name="writer"></param> private static void TestWriter(string expected, StringWriter writer) { writer.Flush(); var writerOutput = writer.ToString(); Assert.Equal(expected, writerOutput); } [Fact] public void WriteToConsoleOutTests() { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; using (var loggerScope = new InternalLoggerScope(true)) { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; InternalLogger.LogToConsole = true; { // Named (based on LogLevel) public methods. loggerScope.ConsoleOutputWriter.Flush(); loggerScope.ConsoleOutputWriter.GetStringBuilder().Length = 0; InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, loggerScope.ConsoleOutputWriter); } { // Invoke Log(LogLevel, string) for every log level. loggerScope.ConsoleOutputWriter.Flush(); loggerScope.ConsoleOutputWriter.GetStringBuilder().Length = 0; InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, loggerScope.ConsoleOutputWriter); } //lambdas { // Named (based on LogLevel) public methods. loggerScope.ConsoleOutputWriter.Flush(); loggerScope.ConsoleOutputWriter.GetStringBuilder().Length = 0; InternalLogger.Warn(() => "WWW"); InternalLogger.Error(() => "EEE"); InternalLogger.Fatal(() => "FFF"); InternalLogger.Trace(() => "TTT"); InternalLogger.Debug(() => "DDD"); InternalLogger.Info(() => "III"); TestWriter(expected, loggerScope.ConsoleOutputWriter); } } } [Fact] public void WriteToConsoleErrorTests() { using (var loggerScope = new InternalLoggerScope(true)) { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; InternalLogger.LogToConsoleError = true; { // Named (based on LogLevel) public methods. loggerScope.ConsoleErrorWriter.Flush(); loggerScope.ConsoleErrorWriter.GetStringBuilder().Length = 0; InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, loggerScope.ConsoleErrorWriter); } { // Invoke Log(LogLevel, string) for every log level. loggerScope.ConsoleErrorWriter.Flush(); loggerScope.ConsoleErrorWriter.GetStringBuilder().Length = 0; InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, loggerScope.ConsoleErrorWriter); } //lambdas { // Named (based on LogLevel) public methods. loggerScope.ConsoleErrorWriter.Flush(); loggerScope.ConsoleErrorWriter.GetStringBuilder().Length = 0; InternalLogger.Warn(() => "WWW"); InternalLogger.Error(() => "EEE"); InternalLogger.Fatal(() => "FFF"); InternalLogger.Trace(() => "TTT"); InternalLogger.Debug(() => "DDD"); InternalLogger.Info(() => "III"); TestWriter(expected, loggerScope.ConsoleErrorWriter); } } } [Fact] public void WriteToFileTests() { string expected = "Warn WWW" + Environment.NewLine + "Error EEE" + Environment.NewLine + "Fatal FFF" + Environment.NewLine + "Trace TTT" + Environment.NewLine + "Debug DDD" + Environment.NewLine + "Info III" + Environment.NewLine; var tempFile = Path.GetTempFileName(); try { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; InternalLogger.LogFile = tempFile; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); AssertFileContents(tempFile, expected, Encoding.UTF8); } finally { InternalLogger.Reset(); if (File.Exists(tempFile)) { File.Delete(tempFile); } } } /// <summary> /// <see cref="TimeSource"/> that returns always the same time, /// passed into object constructor. /// </summary> private class FixedTimeSource : TimeSource { private readonly DateTime _time; public FixedTimeSource(DateTime time) { _time = time; } public override DateTime Time => _time; public override DateTime FromSystemTime(DateTime systemTime) { return _time; } } [Fact] public void TimestampTests() { using (new InternalLoggerScope()) { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = true; StringWriter consoleOutWriter = new StringWriter() { NewLine = ";" }; InternalLogger.LogWriter = consoleOutWriter; // Set fixed time source to test time output TimeSource.Current = new FixedTimeSource(DateTime.Now); // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); string expectedDateTime = TimeSource.Current.Time.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); var strings = consoleOutWriter.ToString().Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (var str in strings) { Assert.Contains(expectedDateTime + ".", str); } } } /// <summary> /// Test exception overloads /// </summary> [Fact] public void ExceptionTests() { using (new InternalLoggerScope()) { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; var ex1 = new Exception("e1"); var ex2 = new Exception("e2", new Exception("inner")); var ex3 = new NLogConfigurationException("config error"); var ex4 = new NLogConfigurationException("config error", ex2); var ex5 = new PathTooLongException(); ex5.Data["key1"] = "value1"; Exception ex6 = null; const string prefix = " Exception: "; { string expected = "Warn WWW1" + prefix + ex1 + Environment.NewLine + "Error EEE1" + prefix + ex2 + Environment.NewLine + "Fatal FFF1" + prefix + ex3 + Environment.NewLine + "Trace TTT1" + prefix + ex4 + Environment.NewLine + "Debug DDD1" + prefix + ex5 + Environment.NewLine + "Info III1" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Warn(ex1, "WWW1"); InternalLogger.Error(ex2, "EEE1"); InternalLogger.Fatal(ex3, "FFF1"); InternalLogger.Trace(ex4, "TTT1"); InternalLogger.Debug(ex5, "DDD1"); InternalLogger.Info(ex6, "III1"); consoleOutWriter.Flush(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } { string expected = "Warn WWW2" + prefix + ex1 + Environment.NewLine + "Error EEE2" + prefix + ex2 + Environment.NewLine + "Fatal FFF2" + prefix + ex3 + Environment.NewLine + "Trace TTT2" + prefix + ex4 + Environment.NewLine + "Debug DDD2" + prefix + ex5 + Environment.NewLine + "Info III2" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Warn(ex1, () => "WWW2"); InternalLogger.Error(ex2, () => "EEE2"); InternalLogger.Fatal(ex3, () => "FFF2"); InternalLogger.Trace(ex4, () => "TTT2"); InternalLogger.Debug(ex5, () => "DDD2"); InternalLogger.Info(ex6, () => "III2"); consoleOutWriter.Flush(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } { string expected = "Warn WWW3" + prefix + ex1 + Environment.NewLine + "Error EEE3" + prefix + ex2 + Environment.NewLine + "Fatal FFF3" + prefix + ex3 + Environment.NewLine + "Trace TTT3" + prefix + ex4 + Environment.NewLine + "Debug DDD3" + prefix + ex5 + Environment.NewLine + "Info III3" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Log(ex1, LogLevel.Warn, "WWW3"); InternalLogger.Log(ex2, LogLevel.Error, "EEE3"); InternalLogger.Log(ex3, LogLevel.Fatal, "FFF3"); InternalLogger.Log(ex4, LogLevel.Trace, "TTT3"); InternalLogger.Log(ex5, LogLevel.Debug, "DDD3"); InternalLogger.Log(ex6, LogLevel.Info, "III3"); consoleOutWriter.Flush(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } { string expected = "Warn WWW4" + prefix + ex1 + Environment.NewLine + "Error EEE4" + prefix + ex2 + Environment.NewLine + "Fatal FFF4" + prefix + ex3 + Environment.NewLine + "Trace TTT4" + prefix + ex4 + Environment.NewLine + "Debug DDD4" + prefix + ex5 + Environment.NewLine + "Info III4" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Log(ex1, LogLevel.Warn, () => "WWW4"); InternalLogger.Log(ex2, LogLevel.Error, () => "EEE4"); InternalLogger.Log(ex3, LogLevel.Fatal, () => "FFF4"); InternalLogger.Log(ex4, LogLevel.Trace, () => "TTT4"); InternalLogger.Log(ex5, LogLevel.Debug, () => "DDD4"); InternalLogger.Log(ex6, LogLevel.Info, () => "III4"); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } } } [Theory] [InlineData("trace", 6)] [InlineData("debug", 5)] [InlineData("info", 4)] [InlineData("warn", 3)] [InlineData("error", 2)] [InlineData("fatal", 1)] [InlineData("off", 0)] public void TestMinLevelSwitch_log(string rawLogLevel, int count) { Action log = () => { InternalLogger.Log(LogLevel.Fatal, "L1"); InternalLogger.Log(LogLevel.Error, "L2"); InternalLogger.Log(LogLevel.Warn, "L3"); InternalLogger.Log(LogLevel.Info, "L4"); InternalLogger.Log(LogLevel.Debug, "L5"); InternalLogger.Log(LogLevel.Trace, "L6"); }; TestMinLevelSwitch_inner(rawLogLevel, count, log); } [Theory] [InlineData("trace", 6)] [InlineData("debug", 5)] [InlineData("info", 4)] [InlineData("warn", 3)] [InlineData("error", 2)] [InlineData("fatal", 1)] [InlineData("off", 0)] public void TestMinLevelSwitch(string rawLogLevel, int count) { Action log = () => { InternalLogger.Fatal("L1"); InternalLogger.Error("L2"); InternalLogger.Warn("L3"); InternalLogger.Info("L4"); InternalLogger.Debug("L5"); InternalLogger.Trace("L6"); }; TestMinLevelSwitch_inner(rawLogLevel, count, log); } [Theory] [InlineData("trace", 6)] [InlineData("debug", 5)] [InlineData("info", 4)] [InlineData("warn", 3)] [InlineData("error", 2)] [InlineData("fatal", 1)] [InlineData("off", 0)] public void TestMinLevelSwitch_lambda(string rawLogLevel, int count) { Action log = () => { InternalLogger.Fatal(() => "L1"); InternalLogger.Error(() => "L2"); InternalLogger.Warn(() => "L3"); InternalLogger.Info(() => "L4"); InternalLogger.Debug(() => "L5"); InternalLogger.Trace(() => "L6"); }; TestMinLevelSwitch_inner(rawLogLevel, count, log); } private static void TestMinLevelSwitch_inner(string rawLogLevel, int count, Action log) { try { //set minimal InternalLogger.LogLevel = LogLevel.FromString(rawLogLevel); InternalLogger.IncludeTimestamp = false; StringWriter consoleOutWriter = new StringWriter() { NewLine = ";" }; InternalLogger.LogWriter = consoleOutWriter; var expected = ""; var logLevel = LogLevel.Fatal.Ordinal; for (int i = 0; i < count; i++, logLevel--) { expected += LogLevel.FromOrdinal(logLevel) + " L" + (i + 1) + ";"; } log(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } finally { InternalLogger.Reset(); } } [Theory] [InlineData("trace", true)] [InlineData("debug", true)] [InlineData("info", true)] [InlineData("warn", true)] [InlineData("error", true)] [InlineData("fatal", true)] [InlineData("off", false)] public void CreateDirectoriesIfNeededTests(string rawLogLevel, bool shouldCreateDirectory) { var tempDir = Path.GetTempPath(); var tempFileName = Path.GetRandomFileName(); var randomSubDirectory = Path.Combine(tempDir, Path.GetRandomFileName()); string tempFile = Path.Combine(randomSubDirectory, tempFileName); try { InternalLogger.LogLevel = LogLevel.FromString(rawLogLevel); InternalLogger.IncludeTimestamp = false; if (Directory.Exists(randomSubDirectory)) { Directory.Delete(randomSubDirectory); } Assert.False(Directory.Exists(randomSubDirectory)); // Set the log file, which will only create the needed directories InternalLogger.LogFile = tempFile; Assert.Equal(Directory.Exists(randomSubDirectory), shouldCreateDirectory); Assert.False(File.Exists(tempFile)); InternalLogger.Log(LogLevel.FromString(rawLogLevel), "File and Directory created."); Assert.Equal(File.Exists(tempFile), shouldCreateDirectory); } finally { InternalLogger.Reset(); if (File.Exists(tempFile)) { File.Delete(tempFile); } if (Directory.Exists(randomSubDirectory)) { Directory.Delete(randomSubDirectory); } } } [Fact] public void CreateFileInCurrentDirectoryTests() { string expected = "Warn WWW" + Environment.NewLine + "Error EEE" + Environment.NewLine + "Fatal FFF" + Environment.NewLine + "Trace TTT" + Environment.NewLine + "Debug DDD" + Environment.NewLine + "Info III" + Environment.NewLine; // Store off the previous log file string previousLogFile = InternalLogger.LogFile; var tempFileName = Path.GetRandomFileName(); try { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; Assert.False(File.Exists(tempFileName)); // Set the log file, which only has a filename InternalLogger.LogFile = tempFileName; Assert.False(File.Exists(tempFileName)); // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); AssertFileContents(tempFileName, expected, Encoding.UTF8); Assert.True(File.Exists(tempFileName)); } finally { InternalLogger.Reset(); if (File.Exists(tempFileName)) { File.Delete(tempFileName); } } } [Fact] public void TestReceivedLogEventTest() { using (var loggerScope = new InternalLoggerScope()) { // Arrange var receivedArgs = new List<InternalLoggerMessageEventArgs>(); var logFactory = new LogFactory(); logFactory.Setup().SetupInternalLogger(s => { EventHandler<InternalLoggerMessageEventArgs> eventHandler = (sender, e) => receivedArgs.Add(e); s.AddLogSubscription(eventHandler); s.RemoveLogSubscription(eventHandler); s.AddLogSubscription(eventHandler); }); var exception = new Exception(); // Act InternalLogger.Info(exception, "Hello {0}", "it's me!"); // Assert Assert.Single(receivedArgs); var logEventArgs = receivedArgs.Single(); Assert.Equal(LogLevel.Info, logEventArgs.Level); Assert.Equal(exception, logEventArgs.Exception); Assert.Equal("Hello it's me!", logEventArgs.Message); } } [Fact] public void TestReceivedLogEventThrowingTest() { using (var loggerScope = new InternalLoggerScope()) { // Arrange var receivedArgs = new List<InternalLoggerMessageEventArgs>(); InternalLogger.LogMessageReceived += (sender, e) => { receivedArgs.Add(e); throw new ApplicationException("I'm a bad programmer"); }; var exception = new Exception(); // Act InternalLogger.Info(exception, "Hello {0}", "it's me!"); // Assert Assert.Single(receivedArgs); var logEventArgs = receivedArgs.Single(); Assert.Equal(LogLevel.Info, logEventArgs.Level); Assert.Equal(exception, logEventArgs.Exception); Assert.Equal("Hello it's me!", logEventArgs.Message); } } [Fact] public void TestReceivedLogEventContextTest() { using (var loggerScope = new InternalLoggerScope()) { // Arrange var targetContext = new NLog.Targets.DebugTarget() { Name = "Ugly" }; var receivedArgs = new List<InternalLoggerMessageEventArgs>(); InternalLogger.LogMessageReceived += (sender, e) => { receivedArgs.Add(e); }; var exception = new Exception(); // Act NLog.Internal.ExceptionHelper.MustBeRethrown(exception, targetContext); // Assert Assert.Single(receivedArgs); var logEventArgs = receivedArgs.Single(); Assert.Equal(LogLevel.Error, logEventArgs.Level); Assert.Equal(exception, logEventArgs.Exception); Assert.Equal(targetContext.GetType(), logEventArgs.SenderType); } } public void Dispose() { TimeSource.Current = new FastLocalTimeSource(); InternalLogger.Reset(); } } } <file_sep>using NLog; using NLog.Targets; class Example { static void Main(string[] args) { NetworkTarget target = new NetworkTarget(); target.Layout = "${level} ${logger} ${message}${newline}"; target.Address = "tcp://localhost:5555"; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Trace("log message 1"); logger.Debug("log message 2"); logger.Info("log message 3"); logger.Warn("log message 4"); logger.Error("log message 5"); logger.Fatal("log message 6"); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; using NLog.Internal; /// <summary> /// Provides asynchronous, buffered execution of target writes. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/AsyncWrapper-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/AsyncWrapper-target">Documentation on NLog Wiki</seealso> /// <remarks> /// <p> /// Asynchronous target wrapper allows the logger code to execute more quickly, by queuing /// messages and processing them in a separate thread. You should wrap targets /// that spend a non-trivial amount of time in their Write() method with asynchronous /// target to speed up logging. /// </p> /// <p> /// Because asynchronous logging is quite a common scenario, NLog supports a /// shorthand notation for wrapping all targets with AsyncWrapper. Just add async="true" to /// the &lt;targets/&gt; element in the configuration file. /// </p> /// <code lang="XML"> /// <![CDATA[ /// <targets async="true"> /// ... your targets go here ... /// </targets> /// ]]></code> /// </remarks> /// <example> /// <p> /// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/AsyncWrapper/NLog.config" /> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/AsyncWrapper/Wrapping File/Example.cs" /> /// </example> [Target("AsyncWrapper", IsWrapper = true)] public class AsyncTargetWrapper : WrapperTargetBase { private readonly object _writeLockObject = new object(); private readonly object _timerLockObject = new object(); private Timer _lazyWriterTimer; private readonly ReusableAsyncLogEventList _reusableAsyncLogEventList = new ReusableAsyncLogEventList(200); private event EventHandler<LogEventDroppedEventArgs> _logEventDroppedEvent; private event EventHandler<LogEventQueueGrowEventArgs> _eventQueueGrowEvent; private bool _missingServiceTypes; /// <summary> /// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class. /// </summary> public AsyncTargetWrapper() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class. /// </summary> /// <param name="name">Name of the target.</param> /// <param name="wrappedTarget">The wrapped target.</param> public AsyncTargetWrapper(string name, Target wrappedTarget) : this(wrappedTarget) { Name = name ?? Name; } /// <summary> /// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> public AsyncTargetWrapper(Target wrappedTarget) : this(wrappedTarget, 10000, AsyncTargetWrapperOverflowAction.Discard) { } /// <summary> /// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="queueLimit">Maximum number of requests in the queue.</param> /// <param name="overflowAction">The action to be taken when the queue overflows.</param> public AsyncTargetWrapper(Target wrappedTarget, int queueLimit, AsyncTargetWrapperOverflowAction overflowAction) { Name = string.IsNullOrEmpty(wrappedTarget?.Name) ? Name : (wrappedTarget.Name + "_wrapped"); WrappedTarget = wrappedTarget; #if NETSTANDARD2_0 // NetStandard20 includes many optimizations for ConcurrentQueue: // - See: https://blogs.msdn.microsoft.com/dotnet/2017/06/07/performance-improvements-in-net-core/ // Net40 ConcurrencyQueue can seem to leak, because it doesn't clear properly on dequeue // - See: https://blogs.msdn.microsoft.com/pfxteam/2012/05/08/concurrentqueuet-holding-on-to-a-few-dequeued-elements/ _requestQueue = new ConcurrentRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard); #else _requestQueue = new AsyncRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard); #endif QueueLimit = queueLimit; OverflowAction = overflowAction; } /// <summary> /// Gets or sets the number of log events that should be processed in a batch /// by the lazy writer thread. /// </summary> /// <docgen category='Buffering Options' order='100' /> public int BatchSize { get; set; } = 200; /// <summary> /// Gets or sets the time in milliseconds to sleep between batches. (1 or less means trigger on new activity) /// </summary> /// <docgen category='Buffering Options' order='100' /> public int TimeToSleepBetweenBatches { get; set; } = 1; /// <summary> /// Occurs when LogEvent has been dropped, because internal queue is full and <see cref="OverflowAction"/> set to <see cref="AsyncTargetWrapperOverflowAction.Discard"/> /// </summary> public event EventHandler<LogEventDroppedEventArgs> LogEventDropped { add { if (_eventQueueGrowEvent == null && _requestQueue != null) { _requestQueue.LogEventDropped += OnRequestQueueDropItem; } _logEventDroppedEvent += value; } remove { _logEventDroppedEvent -= value; if (_eventQueueGrowEvent == null && _requestQueue != null) { _requestQueue.LogEventDropped -= OnRequestQueueDropItem; } } } /// <summary> /// Occurs when internal queue size is growing, because internal queue is full and <see cref="OverflowAction"/> set to <see cref="AsyncTargetWrapperOverflowAction.Grow"/> /// </summary> public event EventHandler<LogEventQueueGrowEventArgs> EventQueueGrow { add { if (_eventQueueGrowEvent == null && _requestQueue != null) { _requestQueue.LogEventQueueGrow += OnRequestQueueGrow; } _eventQueueGrowEvent += value; } remove { _eventQueueGrowEvent -= value; if (_eventQueueGrowEvent == null && _requestQueue != null) { _requestQueue.LogEventQueueGrow -= OnRequestQueueGrow; } } } /// <summary> /// Gets or sets the action to be taken when the lazy writer thread request queue count /// exceeds the set limit. /// </summary> /// <docgen category='Buffering Options' order='10' /> public AsyncTargetWrapperOverflowAction OverflowAction { get => _requestQueue.OnOverflow; set => _requestQueue.OnOverflow = value; } /// <summary> /// Gets or sets the limit on the number of requests in the lazy writer thread request queue. /// </summary> /// <docgen category='Buffering Options' order='10' /> public int QueueLimit { get => _requestQueue.RequestLimit; set => _requestQueue.RequestLimit = value; } /// <summary> /// Gets or sets the number of batches of <see cref="BatchSize"/> to write before yielding into <see cref="TimeToSleepBetweenBatches"/> /// </summary> /// <remarks> /// Performance is better when writing many small batches, than writing a single large batch /// </remarks> /// <docgen category='Buffering Options' order='100' /> public int FullBatchSizeWriteLimit { get; set; } = 5; /// <summary> /// Gets or sets whether to use the locking queue, instead of a lock-free concurrent queue /// </summary> /// <remarks> /// The locking queue is less concurrent when many logger threads, but reduces memory allocation /// </remarks> /// <docgen category='Buffering Options' order='100' /> public bool ForceLockingQueue { get => _forceLockingQueue ?? false; set => _forceLockingQueue = value; } private bool? _forceLockingQueue; /// <summary> /// Gets the queue of lazy writer thread requests. /// </summary> AsyncRequestQueueBase _requestQueue; /// <summary> /// Schedules a flush of pending events in the queue (if any), followed by flushing the WrappedTarget. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { if (_flushEventsInQueueDelegate is null) _flushEventsInQueueDelegate = new AsyncHelpersTask(FlushEventsInQueue); AsyncHelpers.StartAsyncTask(_flushEventsInQueueDelegate.Value, asyncContinuation); } private AsyncHelpersTask? _flushEventsInQueueDelegate; /// <summary> /// Initializes the target by starting the lazy writer timer. /// </summary> protected override void InitializeTarget() { base.InitializeTarget(); if (!ForceLockingQueue && OverflowAction == AsyncTargetWrapperOverflowAction.Block && BatchSize * 1.5m > QueueLimit) { ForceLockingQueue = true; // ConcurrentQueue does not perform well if constantly hitting QueueLimit } #if !NET35 if (_forceLockingQueue.HasValue && _forceLockingQueue.Value != (_requestQueue is AsyncRequestQueue)) { _requestQueue = ForceLockingQueue ? (AsyncRequestQueueBase)new AsyncRequestQueue(QueueLimit, OverflowAction) : new ConcurrentRequestQueue(QueueLimit, OverflowAction); } #endif if (BatchSize > QueueLimit && TimeToSleepBetweenBatches <= 1) { BatchSize = QueueLimit; // Avoid too much throttling } _layoutWithLock = _layoutWithLock ?? WrappedTarget?._layoutWithLock; if (WrappedTarget != null && WrappedTarget.InitializeException is Config.NLogDependencyResolveException && OverflowAction == AsyncTargetWrapperOverflowAction.Discard) { _missingServiceTypes = true; InternalLogger.Debug("{0} WrappedTarget has unresolved missing dependencies.", this); } _requestQueue.Clear(); InternalLogger.Trace("{0}: Start Timer", this); _lazyWriterTimer = new Timer(ProcessPendingEvents, null, Timeout.Infinite, Timeout.Infinite); StartLazyWriterTimer(); } /// <summary> /// Shuts down the lazy writer timer. /// </summary> protected override void CloseTarget() { StopLazyWriterThread(); if (Monitor.TryEnter(_writeLockObject, 500)) { try { WriteLogEventsInQueue(int.MaxValue, "Closing Target"); } finally { Monitor.Exit(_writeLockObject); } } if (OverflowAction == AsyncTargetWrapperOverflowAction.Block) { _requestQueue.Clear(); // Try to eject any threads, that are blocked in the RequestQueue } base.CloseTarget(); } /// <summary> /// Starts the lazy writer thread which periodically writes /// queued log messages. /// </summary> protected virtual void StartLazyWriterTimer() { if (TimeToSleepBetweenBatches <= 1) { StartTimerUnlessWriterActive(false); } else { lock (_timerLockObject) { _lazyWriterTimer?.Change(TimeToSleepBetweenBatches, Timeout.Infinite); } } } /// <summary> /// Attempts to start an instant timer-worker-thread which can write /// queued log messages. /// </summary> /// <returns>Returns true when scheduled a timer-worker-thread</returns> protected virtual bool StartInstantWriterTimer() { return StartLazyWriterThread(true); } private void StartTimerUnlessWriterActive(bool instant) { bool lockTaken = false; try { lockTaken = Monitor.TryEnter(_writeLockObject); if (lockTaken) { if (instant) StartInstantWriterTimer(); else StartLazyWriterThread(false); } else { // If not able to take lock, then it means timer-worker-thread is already active, // and timer-worker-thread will check RequestQueue after leaving writeLockObject InternalLogger.Trace("{0}: Timer not scheduled, since already active", this); } } finally { if (lockTaken) Monitor.Exit(_writeLockObject); } } private bool StartLazyWriterThread(bool instant) { lock (_timerLockObject) { if (_lazyWriterTimer != null) { if (instant) { InternalLogger.Trace("{0}: Timer scheduled instantly", this); _lazyWriterTimer.Change(0, Timeout.Infinite); } else { InternalLogger.Trace("{0}: Timer scheduled throttled", this); _lazyWriterTimer.Change(1, Timeout.Infinite); } return true; } } return false; } /// <summary> /// Stops the lazy writer thread. /// </summary> protected virtual void StopLazyWriterThread() { lock (_timerLockObject) { var currentTimer = _lazyWriterTimer; if (currentTimer != null) { _lazyWriterTimer = null; currentTimer.WaitForDispose(TimeSpan.FromSeconds(1)); } } } /// <summary> /// Adds the log event to asynchronous queue to be processed by /// the lazy writer thread. /// </summary> /// <param name="logEvent">The log event.</param> /// <remarks> /// The <see cref="Target.PrecalculateVolatileLayouts"/> is called /// to ensure that the log event can be processed in another thread. /// </remarks> protected override void Write(AsyncLogEventInfo logEvent) { PrecalculateVolatileLayouts(logEvent.LogEvent); bool queueWasEmpty = _requestQueue.Enqueue(logEvent); if (queueWasEmpty) { if (TimeToSleepBetweenBatches == 0) StartTimerUnlessWriterActive(true); else if (TimeToSleepBetweenBatches <= 1) StartLazyWriterTimer(); } } /// <summary> /// Write to queue without locking <see cref="Target.SyncRoot"/> /// </summary> /// <param name="logEvent"></param> protected override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { try { Write(logEvent); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception)) { throw; } logEvent.Continuation(exception); } } private void ProcessPendingEvents(object state) { if (_lazyWriterTimer is null) return; bool wroteFullBatchSize = false; try { lock (_writeLockObject) { int lastBatchSize = WriteLogEventsInQueue(BatchSize, "Timer"); wroteFullBatchSize = lastBatchSize == BatchSize; if (wroteFullBatchSize && TimeToSleepBetweenBatches <= 1) StartInstantWriterTimer(); // Found full batch, fast schedule to take next batch (within lock to avoid pile up) } } catch (Exception exception) { wroteFullBatchSize = false; // Something went wrong, lets throttle retry #if DEBUG if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } #endif InternalLogger.Error(exception, "{0}: Error in lazy writer timer procedure.", this); } finally { if (TimeToSleepBetweenBatches <= 1) { if (!wroteFullBatchSize) { if (!_requestQueue.IsEmpty) { // If queue was not empty, then more might have arrived while writing the first batch // Do not use instant timer, so we can process in larger batches (faster) StartLazyWriterTimer(); } else { InternalLogger.Trace("{0}: Timer not scheduled, since queue empty", this); } } } else { StartLazyWriterTimer(); } } } private void FlushEventsInQueue(object state) { try { var asyncContinuation = state as AsyncContinuation; lock (_writeLockObject) { WriteLogEventsInQueue(int.MaxValue, "Flush Async"); if (asyncContinuation != null) base.FlushAsync(asyncContinuation); } } catch (Exception exception) { #if DEBUG if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } #endif InternalLogger.Error(exception, "{0}: Error in flush procedure.", this); } finally { if (TimeToSleepBetweenBatches <= 1 && !_requestQueue.IsEmpty) { StartLazyWriterTimer(); } } } private int WriteLogEventsInQueue(int batchSize, string reason) { if (WrappedTarget is null) { InternalLogger.Error("{0}: WrappedTarget is NULL", this); return 0; } if (_missingServiceTypes) { if (WrappedTarget.InitializeException is Config.NLogDependencyResolveException) { return 0; } _missingServiceTypes = false; InternalLogger.Debug("{0}: WrappedTarget has resolved missing dependency", this); } if (batchSize == int.MaxValue) { var logEvents = _requestQueue.DequeueBatch(int.MaxValue); return WriteLogEventsToTarget(logEvents, reason); } else { int lastBatchSize = 0; for (int i = 0; i < FullBatchSizeWriteLimit; ++i) { using (var targetList = _reusableAsyncLogEventList.Allocate()) { var logEvents = targetList.Result; _requestQueue.DequeueBatch(batchSize, logEvents); lastBatchSize = WriteLogEventsToTarget(logEvents, reason); } if (lastBatchSize < batchSize) break; } return lastBatchSize; } } private int WriteLogEventsToTarget(IList<AsyncLogEventInfo> logEvents, string reason) { int batchSize = logEvents.Count; if (batchSize > 0) { if (reason != null) InternalLogger.Trace("{0}: Writing {1} events ({2})", this, batchSize, reason); WrappedTarget.WriteAsyncLogEvents(logEvents); } return batchSize; } private void OnRequestQueueDropItem(object sender, LogEventDroppedEventArgs logEventDroppedEventArgs) { _logEventDroppedEvent?.Invoke(this, logEventDroppedEventArgs); } private void OnRequestQueueGrow(object sender, LogEventQueueGrowEventArgs logEventQueueGrowEventArgs) { _eventQueueGrowEvent?.Invoke(this, logEventQueueGrowEventArgs); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class RandomizeGroupTargetTests : NLogTestBase { [Fact] public void RandomizeGroupSyncTest1() { var myTarget1 = new MyTarget(); var myTarget2 = new MyTarget(); var myTarget3 = new MyTarget(); var wrapper = new RandomizeGroupTarget() { Targets = { myTarget1, myTarget2, myTarget3 }, }; myTarget1.Initialize(null); myTarget2.Initialize(null); myTarget3.Initialize(null); wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); // no exceptions for (int i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.Equal(10, exceptions.Count); foreach (var e in exceptions) { Assert.Null(e); } Assert.Equal(10, myTarget1.WriteCount + myTarget2.WriteCount + myTarget3.WriteCount); Exception flushException = null; var flushHit = new ManualResetEvent(false); wrapper.Flush(ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); if (flushException != null) { Assert.True(false, flushException.ToString()); } Assert.Equal(1, myTarget1.FlushCount); Assert.Equal(1, myTarget2.FlushCount); Assert.Equal(1, myTarget3.FlushCount); } [Fact] public void RandomizeGroupSyncTest2() { var wrapper = new RandomizeGroupTarget() { // no targets }; wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); // no exceptions for (int i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.Equal(10, exceptions.Count); foreach (var e in exceptions) { Assert.Null(e); } Exception flushException = new Exception("Flush not hit synchronously."); wrapper.Flush(ex => flushException = ex); if (flushException != null) { Assert.True(false, flushException.ToString()); } } public class MyAsyncTarget : Target { public int FlushCount { get; private set; } public int WriteCount { get; private set; } public MyAsyncTarget() : base() { } public MyAsyncTarget(string name) : this() { Name = name; } protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); } protected override void Write(AsyncLogEventInfo logEvent) { Assert.True(FlushCount <= WriteCount); WriteCount++; ThreadPool.QueueUserWorkItem( s => { if (ThrowExceptions) { logEvent.Continuation(new InvalidOperationException("Some problem!")); logEvent.Continuation(new InvalidOperationException("Some problem!")); } else { logEvent.Continuation(null); logEvent.Continuation(null); } }); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { FlushCount++; ThreadPool.QueueUserWorkItem( s => asyncContinuation(null)); } public bool ThrowExceptions { get; set; } } class MyTarget : Target { public int FlushCount { get; set; } public int WriteCount { get; set; } public int FailCounter { get; set; } public MyTarget() : base() { } public MyTarget(string name) : this() { Name = name; } protected override void Write(LogEventInfo logEvent) { Assert.True(FlushCount <= WriteCount); WriteCount++; if (FailCounter > 0) { FailCounter--; throw new InvalidOperationException("Some failure."); } } protected override void FlushAsync(AsyncContinuation asyncContinuation) { FlushCount++; asyncContinuation(null); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Diagnostics.CodeAnalysis; /// <summary> /// Factory of named items (such as <see cref="Targets.Target"/>, <see cref="Layouts.Layout"/>, <see cref="LayoutRenderers.LayoutRenderer"/>, etc.). /// </summary> internal interface IFactory { void Clear(); [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] void ScanTypes(Type[] types, string assemblyName, string itemNamePrefix); void RegisterType([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicMethods)] Type type, string itemNamePrefix); } /// <summary> /// Factory of named items (such as <see cref="Targets.Target"/>, <see cref="Layouts.Layout"/>, <see cref="LayoutRenderers.LayoutRenderer"/>, etc.). /// </summary> public interface IFactory<TBaseType> where TBaseType : class { /// <summary> /// Registers type-creation from type-alias /// </summary> void RegisterType<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] TType>(string typeAlias) where TType : TBaseType, new(); /// <summary> /// Create type-instance from type-alias /// </summary> bool TryCreateInstance(string typeAlias, out TBaseType result); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; interface IFileArchiveMode { bool IsArchiveCleanupEnabled { get; } /// <summary> /// Check if cleanup should be performed on initialize new file /// </summary> /// <param name="archiveFilePath">Base archive file pattern</param> /// <param name="maxArchiveFiles">Maximum number of archive files that should be kept</param> /// <param name="maxArchiveDays">Maximum days of archive files that should be kept</param> /// <returns>True, when archive cleanup is needed</returns> bool AttemptCleanupOnInitializeFile(string archiveFilePath, int maxArchiveFiles, int maxArchiveDays); /// <summary> /// Create a wildcard file-mask that allows one to find all files belonging to the same archive. /// </summary> /// <param name="archiveFilePath">Base archive file pattern</param> /// <returns>Wildcard file-mask</returns> string GenerateFileNameMask(string archiveFilePath); /// <summary> /// Search directory for all existing files that are part of the same archive. /// </summary> /// <param name="archiveFilePath">Base archive file pattern</param> /// <returns></returns> List<DateAndSequenceArchive> GetExistingArchiveFiles(string archiveFilePath); /// <summary> /// Generate the next archive filename for the archive. /// </summary> /// <param name="archiveFilePath">Base archive file pattern</param> /// <param name="archiveDate">File date of archive</param> /// <param name="existingArchiveFiles">Existing files in the same archive</param> /// <returns></returns> DateAndSequenceArchive GenerateArchiveFileName(string archiveFilePath, DateTime archiveDate, List<DateAndSequenceArchive> existingArchiveFiles); /// <summary> /// Return all files that should be removed from the provided archive. /// </summary> /// <param name="archiveFilePath">Base archive file pattern</param> /// <param name="existingArchiveFiles">Existing files in the same archive</param> /// <param name="maxArchiveFiles">Maximum number of archive files that should be kept</param> /// <param name="maxArchiveDays">Maximum days of archive files that should be kept</param> IEnumerable<DateAndSequenceArchive> CheckArchiveCleanup(string archiveFilePath, List<DateAndSequenceArchive> existingArchiveFiles, int maxArchiveFiles, int maxArchiveDays); }; } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.IO; using NLog.Common; namespace NLog.Targets.FileArchiveModes { internal abstract class FileArchiveModeBase : IFileArchiveMode { static readonly DateTime MaxAgeArchiveFileDate = new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc); private int _lastArchiveFileCount = short.MaxValue * 2; private DateTime _oldestArchiveFileDate = MaxAgeArchiveFileDate.Date; public bool IsArchiveCleanupEnabled { get; } protected FileArchiveModeBase(bool isArchiveCleanupEnabled) { IsArchiveCleanupEnabled = isArchiveCleanupEnabled; } /// <summary> /// Check if cleanup should be performed on initialize new file /// /// Skip cleanup when initializing new file, just after having performed archive operation /// </summary> /// <param name="archiveFilePath">Base archive file pattern</param> /// <param name="maxArchiveFiles">Maximum number of archive files that should be kept</param> /// <param name="maxArchiveDays">Maximum days of archive files that should be kept</param> /// <returns>True, when archive cleanup is needed</returns> public virtual bool AttemptCleanupOnInitializeFile(string archiveFilePath, int maxArchiveFiles, int maxArchiveDays) { if (maxArchiveFiles > 0 && _lastArchiveFileCount++ > maxArchiveFiles) return true; if (maxArchiveDays > 0 && (NLog.Time.TimeSource.Current.Time.Date.ToUniversalTime() - _oldestArchiveFileDate).TotalDays > maxArchiveDays) return true; return false; } public string GenerateFileNameMask(string archiveFilePath) { int lastArchiveFileCount = _lastArchiveFileCount; DateTime oldestArchiveFileDate = _oldestArchiveFileDate; var fileMask = GenerateFileNameMask(archiveFilePath, GenerateFileNameTemplate(archiveFilePath)); _lastArchiveFileCount = lastArchiveFileCount; // Restore if modified by "mistake" _oldestArchiveFileDate = oldestArchiveFileDate; // Restore if modified by "mistake" return fileMask; } public virtual List<DateAndSequenceArchive> GetExistingArchiveFiles(string archiveFilePath) { _lastArchiveFileCount = short.MaxValue * 2; _oldestArchiveFileDate = MaxAgeArchiveFileDate.Date; string archiveFolderPath = Path.GetDirectoryName(archiveFilePath); FileNameTemplate archiveFileNameTemplate = GenerateFileNameTemplate(archiveFilePath); string archiveFileMask = GenerateFileNameMask(archiveFilePath, archiveFileNameTemplate); var existingArchiveFiles = new List<DateAndSequenceArchive>(); if (string.IsNullOrEmpty(archiveFileMask)) return existingArchiveFiles; DirectoryInfo directoryInfo = new DirectoryInfo(archiveFolderPath); if (!directoryInfo.Exists) return existingArchiveFiles; var existingFiles = directoryInfo.GetFiles(archiveFileMask); foreach (var fileInfo in existingFiles) { var archiveFileInfo = GenerateArchiveFileInfo(fileInfo, archiveFileNameTemplate); if (archiveFileInfo != null) { InternalLogger.Trace("FileTarget: Found existing archive file: {0} [SeqNo={1} and FileTimeUtc={2:u}]", archiveFileInfo.FileName, archiveFileInfo.Sequence, archiveFileInfo.Date); existingArchiveFiles.Add(archiveFileInfo); } else { InternalLogger.Trace("FileTarget: Ignored existing archive file: {0}", fileInfo.FullName); } } if (existingArchiveFiles.Count > 1) existingArchiveFiles.Sort((x,y) => FileSortOrderComparison(x, y)); UpdateMaxArchiveState(existingArchiveFiles); return existingArchiveFiles; } protected void UpdateMaxArchiveState(List<DateAndSequenceArchive> existingArchiveFiles) { _lastArchiveFileCount = existingArchiveFiles.Count; _oldestArchiveFileDate = existingArchiveFiles.Count == 0 ? NLog.Time.TimeSource.Current.Time.Date.ToUniversalTime() : existingArchiveFiles[0].Date.Date.ToUniversalTime(); } private static int FileSortOrderComparison(DateAndSequenceArchive x, DateAndSequenceArchive y) { if (x.Date != y.Date && !x.HasSameFormattedDate(y.Date)) return x.Date.CompareTo(y.Date); if (x.Sequence.CompareTo(y.Sequence) != 0) return x.Sequence.CompareTo(y.Sequence); return StringComparer.OrdinalIgnoreCase.Compare(x.FileName, y.FileName); } protected virtual FileNameTemplate GenerateFileNameTemplate(string archiveFilePath) { ++_lastArchiveFileCount; return new FileNameTemplate(Path.GetFileName(archiveFilePath)); } protected virtual string GenerateFileNameMask(string archiveFilePath, FileNameTemplate fileTemplate) { return fileTemplate?.ReplacePattern("*") ?? string.Empty; } protected abstract DateAndSequenceArchive GenerateArchiveFileInfo(FileInfo archiveFile, FileNameTemplate fileTemplate); public abstract DateAndSequenceArchive GenerateArchiveFileName(string archiveFilePath, DateTime archiveDate, List<DateAndSequenceArchive> existingArchiveFiles); public virtual IEnumerable<DateAndSequenceArchive> CheckArchiveCleanup(string archiveFilePath, List<DateAndSequenceArchive> existingArchiveFiles, int maxArchiveFiles, int maxArchiveDays) { if (maxArchiveFiles <= 0 && maxArchiveDays <= 0) yield break; UpdateMaxArchiveState(existingArchiveFiles); if (existingArchiveFiles.Count == 0) yield break; if (maxArchiveFiles > 0 && existingArchiveFiles.Count <= maxArchiveFiles && maxArchiveDays <= 0) yield break; for (int i = 0; i < existingArchiveFiles.Count; i++) { if (ShouldDeleteFile(existingArchiveFiles[i], existingArchiveFiles.Count - i, maxArchiveFiles, maxArchiveDays)) { if (_lastArchiveFileCount > 0) --_lastArchiveFileCount; yield return existingArchiveFiles[i]; } else { _oldestArchiveFileDate = existingArchiveFiles[i].Date.Date.ToUniversalTime(); break; } } } private bool ShouldDeleteFile(DateAndSequenceArchive existingArchiveFile, int remainingFileCount, int maxArchiveFiles, int maxArchiveDays) { if (maxArchiveFiles > 0 && remainingFileCount > maxArchiveFiles) return true; if (maxArchiveDays > 0) { var fileDateUtc = existingArchiveFile.Date.Date.ToUniversalTime(); if (fileDateUtc > MaxAgeArchiveFileDate) { var currentDateUtc = NLog.Time.TimeSource.Current.Time.Date.ToUniversalTime(); var fileAgeDays = (currentDateUtc - fileDateUtc).TotalDays; if (fileAgeDays > maxArchiveDays) { InternalLogger.Debug("FileTarget: Detected old file in archive. FileName={0}, FileDate={1:u}, FileDateUtc={2:u}, CurrentDateUtc={3:u}, Age={4} days", existingArchiveFile.FileName, existingArchiveFile.Date, fileDateUtc, currentDateUtc, Math.Round(fileAgeDays, 1)); return true; } } } return false; } internal sealed class FileNameTemplate { /// <summary> /// Characters determining the start of the <see cref="FileNameTemplate.Template"/>. /// </summary> public const string PatternStartCharacters = "{#"; /// <summary> /// Characters determining the end of the <see cref="FileNameTemplate.Template"/>. /// </summary> public const string PatternEndCharacters = "#}"; /// <summary> /// File name which is used as template for matching and replacements. /// It is expected to contain a pattern to match. /// </summary> public string Template { get; } /// <summary> /// The beginning position of the <see cref="FileNameTemplate.PatternStartCharacters"/> /// within the <see cref="FileNameTemplate.Template"/>. -1 is returned /// when no pattern can be found. /// </summary> public int BeginAt { get; } /// <summary> /// The ending position of the <see cref="FileNameTemplate.PatternEndCharacters"/> /// within the <see cref="FileNameTemplate.Template"/>. -1 is returned /// when no pattern can be found. /// </summary> public int EndAt { get; } private bool FoundPattern => BeginAt != -1 && EndAt != -1; public FileNameTemplate(string template) { Template = template; BeginAt = template.IndexOf(PatternStartCharacters, StringComparison.Ordinal); EndAt = BeginAt != -1 ? (template.IndexOf(PatternEndCharacters, StringComparison.Ordinal) + PatternEndCharacters.Length) : -1; } /// <summary> /// Replace the pattern with the specified String. /// </summary> /// <param name="replacementValue"></param> /// <returns></returns> public string ReplacePattern(string replacementValue) { return !FoundPattern || string.IsNullOrEmpty(replacementValue) ? Template : Template.Substring(0, BeginAt) + replacementValue + Template.Substring(EndAt); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using JetBrains.Annotations; using NLog.Internal; namespace NLog.MessageTemplates { /// <summary> /// Description of a single parameter extracted from a MessageTemplate /// </summary> public struct MessageTemplateParameter { /// <summary> /// Parameter Name extracted from <see cref="LogEventInfo.Message"/> /// This is everything between "{" and the first of ",:}". /// </summary> [NotNull] public string Name { get; } /// <summary> /// Parameter Value extracted from the <see cref="LogEventInfo.Parameters"/>-array /// </summary> [CanBeNull] public object Value { get; } /// <summary> /// Format to render the parameter. /// This is everything between ":" and the first unescaped "}" /// </summary> [CanBeNull] public string Format { get; } /// <summary> /// Parameter method that should be used to render the parameter /// See also <see cref="IValueFormatter"/> /// </summary> public CaptureType CaptureType { get; } /// <summary> /// Returns index for <see cref="LogEventInfo.Parameters"/>, when <see cref="MessageTemplateParameters.IsPositional"/> /// </summary> public int? PositionalIndex { get { switch (Name) { case "0": return 0; case "1": return 1; case "2": return 2; case "3": return 3; case "4": return 4; case "5": return 5; case "6": return 6; case "7": return 7; case "8": return 8; case "9": return 9; default: if (Name?.Length >= 1 && Name[0] >= '0' && Name[0] <= '9' && int.TryParse(Name, out var parameterIndex)) { return parameterIndex; } return null; } } } /// <summary> /// Constructs a single message template parameter /// </summary> /// <param name="name">Parameter Name</param> /// <param name="value">Parameter Value</param> /// <param name="format">Parameter Format</param> internal MessageTemplateParameter([NotNull] string name, object value, string format) { Name = Guard.ThrowIfNull(name); Value = value; Format = format; CaptureType = CaptureType.Normal; } /// <summary> /// Constructs a single message template parameter /// </summary> /// <param name="name">Parameter Name</param> /// <param name="value">Parameter Value</param> /// <param name="format">Parameter Format</param> /// <param name="captureType">Parameter CaptureType</param> public MessageTemplateParameter([NotNull] string name, object value, string format, CaptureType captureType) { Name = Guard.ThrowIfNull(name); Value = value; Format = format; CaptureType = captureType; } } }<file_sep>using NLog; using NLog.Targets; class Example { static void Main(string[] args) { WebServiceTarget target = new WebServiceTarget(); target.Url = "http://localhost:2648/Service1.asmx"; target.MethodName = "HelloWorld"; target.Namespace = "http://www.nlog-project.org/example"; target.Protocol = WebServiceTarget.WebServiceProtocol.Soap11; target.Parameters.Add(new MethodCallParameter("n1", "${message}")); target.Parameters.Add(new MethodCallParameter("n2", "${logger}")); target.Parameters.Add(new MethodCallParameter("n3", "${level}")); NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Trace("log message 1"); logger.Debug("log message 2"); logger.Info("log message 3"); logger.Warn("log message 4"); logger.Error("log message 5"); logger.Fatal("log message 6"); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Layouts { using NLog.LayoutRenderers; using NLog.Internal; using NLog.Config; using NLog.LayoutRenderers.Wrappers; using NLog.Layouts; using Xunit; public class ThreadAgnosticTests : NLogTestBase { [Fact] public void ThreadAgnosticTest() { Layout l = new SimpleLayout("${message}"); l.Initialize(null); Assert.True(l.ThreadAgnostic); } [Fact] public void NonThreadAgnosticTest() { Layout l = new SimpleLayout("${threadname}"); l.Initialize(null); Assert.False(l.ThreadAgnostic); } [Fact] public void AgnosticPlusNonAgnostic() { Layout l = new SimpleLayout("${message}${threadname}"); l.Initialize(null); Assert.False(l.ThreadAgnostic); } [Fact] public void AgnosticPlusAgnostic() { Layout l = new SimpleLayout("${message}${level}${logger}"); l.Initialize(null); Assert.True(l.ThreadAgnostic); } [Fact] public void WrapperOverAgnostic() { Layout l = new SimpleLayout("${rot13:${message}}"); l.Initialize(null); Assert.True(l.ThreadAgnostic); } [Fact] public void DoubleWrapperOverAgnostic() { Layout l = new SimpleLayout("${lowercase:${rot13:${message}}}"); l.Initialize(null); Assert.True(l.ThreadAgnostic); } [Fact] public void TripleWrapperOverAgnostic() { Layout l = new SimpleLayout("${uppercase:${lowercase:${rot13:${message}}}}"); l.Initialize(null); Assert.True(l.ThreadAgnostic); } [Fact] public void TripleWrapperOverNonAgnostic() { Layout l = new SimpleLayout("${uppercase:${lowercase:${rot13:${message}${threadname}}}}"); l.Initialize(null); Assert.False(l.ThreadAgnostic); } [Fact] public void ComplexAgnosticWithCondition() { Layout l = @"${message:padding=-10:padCharacter=Y:when='${pad:${logger}:padding=10:padCharacter=X}'=='XXXXlogger'}"; l.Initialize(null); Assert.True(l.ThreadAgnostic); } [Fact] public void ComplexNonAgnosticWithCondition() { Layout l = @"${message:padding=-10:padCharacter=Y:when='${pad:${threadname}:padding=10:padCharacter=X}'=='XXXXlogger'}"; l.Initialize(null); Assert.False(l.ThreadAgnostic); } [Fact] public void CsvThreadAgnostic() { CsvLayout l = new CsvLayout() { Columns = { new CsvColumn("name1", "${message}"), new CsvColumn("name2", "${level}"), new CsvColumn("name3", "${longdate}"), }, }; l.Initialize(null); Assert.True(l.ThreadAgnostic); } [Fact] public void CsvNonAgnostic() { CsvLayout l = new CsvLayout() { Columns = { new CsvColumn("name1", "${message}"), new CsvColumn("name2", "${threadname}"), new CsvColumn("name3", "${longdate}"), }, }; l.Initialize(null); Assert.False(l.ThreadAgnostic); } [Fact] public void CustomNotAgnosticTests() { var cif = new ConfigurationItemFactory(); cif.LayoutRendererFactory.RegisterType<CustomRendererNonAgnostic>("customNotAgnostic"); Layout l = new SimpleLayout("${customNotAgnostic}", cif); l.Initialize(null); Assert.False(l.ThreadAgnostic); } [Fact] public void CustomAgnosticTests() { var cif = new ConfigurationItemFactory(); cif.LayoutRendererFactory.RegisterType<CustomRendererAgnostic>("customAgnostic"); Layout l = new SimpleLayout("${customAgnostic}", cif); l.Initialize(null); Assert.True(l.ThreadAgnostic); } [LayoutRenderer("customNotAgnostic")] public class CustomRendererNonAgnostic : LayoutRenderer { protected override void Append(System.Text.StringBuilder builder, LogEventInfo logEvent) { builder.Append("custom"); } } [LayoutRenderer("customAgnostic")] [ThreadAgnostic] public class CustomRendererAgnostic : LayoutRenderer { protected override void Append(System.Text.StringBuilder builder, LogEventInfo logEvent) { builder.Append("customAgnostic"); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class GroupByTargetWrapperTests : NLogTestBase { [Fact] public void SimpleGroupByTest() { // Arrange var memoryTarget = new MemoryTarget("memory") { Layout = "${level}" }; var groupByTarget = new GroupByTargetWrapper("groupby", memoryTarget, "${logger}"); var bufferTarget = new BufferingTargetWrapper("buffer", groupByTarget); var logFactory = new LogFactory(); var logConfig = new NLog.Config.LoggingConfiguration(logFactory); logConfig.AddRule(LogLevel.Info, LogLevel.Fatal, bufferTarget); logFactory.Configuration = logConfig; var logger1 = logFactory.GetLogger("Logger1"); var logger2 = logFactory.GetLogger("Logger2"); var logger3 = logFactory.GetLogger("Logger3"); // Act logger1.Trace("Ignore Me"); logger2.Warn("Special Warning"); logger1.Debug("Hello world"); logger1.Fatal("Catastropic Goodbye"); logger2.Error("General Error"); logFactory.Flush(); groupByTarget.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Info, logger1.Name, "Special Hello").WithContinuation((ex) => { })); // Assert Assert.Equal(4, memoryTarget.Logs.Count); Assert.Equal("Warn", memoryTarget.Logs[0]); Assert.Equal("Error", memoryTarget.Logs[1]); Assert.Equal("Fatal", memoryTarget.Logs[2]); Assert.Equal("Info", memoryTarget.Logs[3]); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Conditions { using System; using System.Globalization; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using NLog.Conditions; using NLog.Config; using Xunit; public class ConditionEvaluatorTests : NLogTestBase { [Fact] public void BooleanOperatorTest() { AssertEvaluationResult(false, "false or false"); AssertEvaluationResult(true, "false or true"); AssertEvaluationResult(true, "true or false"); AssertEvaluationResult(true, "true or true"); AssertEvaluationResult(false, "false and false"); AssertEvaluationResult(false, "false and true"); AssertEvaluationResult(false, "true and false"); AssertEvaluationResult(true, "true and true"); AssertEvaluationResult(false, "not true"); AssertEvaluationResult(true, "not false"); AssertEvaluationResult(false, "not not false"); AssertEvaluationResult(true, "not not true"); } [Fact] public void ConditionMethodsTest() { AssertEvaluationResult(true, "'${exception:format=type}'==''"); AssertEvaluationResult(true, "starts-with('foobar','foo')"); AssertEvaluationResult(false, "starts-with('foobar','bar')"); AssertEvaluationResult(true, "ends-with('foobar','bar')"); AssertEvaluationResult(false, "ends-with('foobar','foo')"); AssertEvaluationResult(0, "length('')"); AssertEvaluationResult(4, "length('${level}')"); AssertEvaluationResult(false, "equals(1, 2)"); AssertEvaluationResult(true, "equals(3.14, 3.14)"); AssertEvaluationResult(true, "contains('foobar','ooba')"); AssertEvaluationResult(false, "contains('foobar','oobe')"); AssertEvaluationResult(false, "contains('','foo')"); AssertEvaluationResult(true, "contains('foo','')"); AssertEvaluationResult(true, "regex-matches('foo', '^foo$')"); AssertEvaluationResult(false, "regex-matches('foo', '^bar$')"); //Check that calling with empty string is equivalent with not passing the parameter AssertEvaluationResult(true, "regex-matches('foo', '^foo$', '')"); AssertEvaluationResult(false, "regex-matches('foo', '^bar$', '')"); //Check that options are parsed correctly AssertEvaluationResult(true, "regex-matches('Foo', '^foo$', 'ignorecase')"); AssertEvaluationResult(false, "regex-matches('Foo', '^foo$')"); AssertEvaluationResult(true, "regex-matches('foo\nbar', '^Foo$', 'ignorecase,multiline')"); AssertEvaluationResult(false, "regex-matches('foo\nbar', '^Foo$')"); Assert.Throws<ConditionEvaluationException>(() => AssertEvaluationResult(true, "regex-matches('foo\nbar', '^Foo$', 'ignorecase,nonexistent')")); } [Fact] public void ConditionMethodNegativeTest1() { try { AssertEvaluationResult(true, "starts-with('foobar')"); Assert.True(false, "Expected exception"); } catch (ConditionParseException ex) { Assert.Equal("Cannot resolve function 'starts-with'", ex.Message); Assert.NotNull(ex.InnerException); Assert.Equal("Condition method 'starts-with' requires minimum 2 parameters, but passed 1.", ex.InnerException.Message); } } [Fact] public void ConditionMethodNegativeTest2() { try { AssertEvaluationResult(true, "starts-with('foobar','baz','qux','zzz')"); Assert.True(false, "Expected exception"); } catch (ConditionParseException ex) { Assert.Equal("Cannot resolve function 'starts-with'", ex.Message); Assert.NotNull(ex.InnerException); Assert.Equal("Condition method 'starts-with' requires maximum 3 parameters, but passed 4.", ex.InnerException.Message); } } [Fact] public void ConditionMethodNegativeTest3() { try { AssertEvaluationResult(true, "length()"); Assert.True(false, "Expected exception"); } catch (ConditionParseException ex) { Assert.Equal("Cannot resolve function 'length'", ex.Message); Assert.NotNull(ex.InnerException); Assert.Equal("Condition method 'length' requires minimum 1 parameters, but passed 0.", ex.InnerException.Message); } } [Fact] public void ConditionMethodNegativeTest4() { try { AssertEvaluationResult(true, "equals('foobar','baz','qux')"); Assert.True(false, "Expected exception"); } catch (ConditionParseException ex) { Assert.Equal("Cannot resolve function 'equals'", ex.Message); Assert.NotNull(ex.InnerException); Assert.Equal("Condition method 'equals' requires maximum 2 parameters, but passed 3.", ex.InnerException.Message); } } [Fact] public void LiteralTest() { AssertEvaluationResult(null, "null"); AssertEvaluationResult(0, "0"); AssertEvaluationResult(3, "3"); AssertEvaluationResult(3.1415, "3.1415"); AssertEvaluationResult(-1, "-1"); AssertEvaluationResult(-3.1415, "-3.1415"); AssertEvaluationResult(true, "true"); AssertEvaluationResult(false, "false"); AssertEvaluationResult(string.Empty, "''"); AssertEvaluationResult("x", "'x'"); AssertEvaluationResult("d'Artagnan", "'d''Artagnan'"); } [Fact] public void LogEventInfoPropertiesTest() { AssertEvaluationResult(LogLevel.Warn, "level"); AssertEvaluationResult("some message", "message"); AssertEvaluationResult("MyCompany.Product.Class", "logger"); } [Fact] public void RelationalOperatorTest() { AssertEvaluationResult(true, "1 < 2"); AssertEvaluationResult(false, "1 < 1"); AssertEvaluationResult(true, "2 > 1"); AssertEvaluationResult(false, "1 > 1"); AssertEvaluationResult(true, "1 <= 2"); AssertEvaluationResult(false, "1 <= 0"); AssertEvaluationResult(true, "2 >= 1"); AssertEvaluationResult(false, "0 >= 1"); AssertEvaluationResult(true, "2 == 2"); AssertEvaluationResult(false, "2 == 3"); AssertEvaluationResult(true, "2 != 3"); AssertEvaluationResult(false, "2 != 2"); AssertEvaluationResult(false, "1 < null"); AssertEvaluationResult(true, "1 > null"); AssertEvaluationResult(true, "null < 1"); AssertEvaluationResult(false, "null > 1"); AssertEvaluationResult(true, "null == null"); AssertEvaluationResult(false, "null != null"); AssertEvaluationResult(false, "null == 1"); AssertEvaluationResult(false, "1 == null"); AssertEvaluationResult(true, "null != 1"); AssertEvaluationResult(true, "1 != null"); } [Fact] public void UnsupportedRelationalOperatorTest() { var cond = new ConditionRelationalExpression("true", "true", (ConditionRelationalOperator)(-1)); Assert.Throws<ConditionEvaluationException>(() => cond.Evaluate(LogEventInfo.CreateNullEvent())); } [Fact] public void UnsupportedRelationalOperatorTest2() { var cond = new ConditionRelationalExpression("true", "true", (ConditionRelationalOperator)(-1)); Assert.Throws<NotSupportedException>(() => cond.ToString()); } [Fact] public void MethodWithLogEventInfoTest() { var factories = SetupConditionMethods(); Assert.Equal(true, ConditionParser.ParseExpression("IsValid()", factories).Evaluate(CreateWellKnownContext())); var ex = Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("IsValid('foobar')", factories)); Assert.Contains("Condition method 'IsValid' requires maximum 0 parameters, but passed 1", ex.ToString()); } [Fact] public void DoubleEqualsTest() { var factories = SetupConditionMethods(); Assert.Equal(true, ConditionParser.ParseExpression("DoubleEquals(0.01, 0.02, 0.1)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("DoubleEquals(0.01, 0.02, 0.001)", factories).Evaluate(CreateWellKnownContext())); var ex = Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("DoubleEquals(0.01, 0.02, 0.001, 'foobar')", factories)); Assert.Contains("Condition method 'DoubleEquals' requires maximum 3 parameters, but passed 4", ex.ToString()); Assert.Throws<ConditionEvaluationException>(() => ConditionParser.ParseExpression("DoubleEquals(0.01, 0.02, 'foobar')", factories).Evaluate(CreateWellKnownContext())); } [Fact] public void ManyParametersTest() { var factories = SetupConditionMethods(); Assert.Equal(false, ConditionParser.ParseExpression("ManyParameters('One', 'Two', 'Three', 'Four')", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ManyParameters('One', 'Two', 'Three', 'Four')", factories).Evaluate(new LogEventInfo() { Message = "Four" })); } [Fact] public void TypePromotionTest() { var factories = SetupConditionMethods(); Assert.Equal(true, ConditionParser.ParseExpression("ToDateTime('2010/01/01') == '2010/01/01'", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToInt64(1) == ToInt32(1)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("'42' == 42", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("42 == '42'", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToDouble(3) == 3", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("3 == ToDouble(3)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToSingle(3) == 3", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("3 == ToSingle(3)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToDecimal(3) == 3", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("3 == ToDecimal(3)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToInt32(3) == ToInt16(3)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToInt16(3) == ToInt32(3)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("true == ToInt16(1)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToInt16(1) == true", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToDateTime('2010/01/01') == '2010/01/02'", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToInt64(1) == ToInt32(2)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("'42' == 43", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("42 == '43'", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToDouble(3) == 4", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("3 == ToDouble(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToSingle(3) == 4", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("3 == ToSingle(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToDecimal(3) == 4", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("3 == ToDecimal(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToInt32(3) == ToInt16(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToInt16(3) == ToInt32(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("false == ToInt16(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToInt16(1) == false", factories).Evaluate(CreateWellKnownContext())); //this is doing string comparision as that's the common type which works in this case. Assert.Equal(false, ConditionParser.ParseExpression("ToDateTime('2010/01/01') == '20xx/01/01'", factories).Evaluate(CreateWellKnownContext())); } [Fact] public void TypePromotionNegativeTest2() { var factories = SetupConditionMethods(); Assert.Throws<ConditionEvaluationException>(() => ConditionParser.ParseExpression("GetGuid() == ToInt16(1)", factories).Evaluate(CreateWellKnownContext())); } [Fact] public void ExceptionTest1() { var ex1 = new ConditionEvaluationException(); Assert.NotNull(ex1.Message); } [Fact] public void ExceptionTest2() { var ex1 = new ConditionEvaluationException("msg"); Assert.Equal("msg", ex1.Message); } [Fact] public void ExceptionTest3() { var inner = new InvalidOperationException("f"); var ex1 = new ConditionEvaluationException("msg", inner); Assert.Equal("msg", ex1.Message); Assert.Same(inner, ex1.InnerException); } #if !NET6_0_OR_GREATER [Fact] public void ExceptionTest4() { var inner = new InvalidOperationException("f"); var ex1 = new ConditionEvaluationException("msg", inner); BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, ex1); ms.Position = 0; Exception ex2 = (Exception)bf.Deserialize(ms); Assert.Equal("msg", ex2.Message); Assert.Equal("f", ex2.InnerException.Message); } #endif [Fact] public void ExceptionTest11() { var ex1 = new ConditionParseException(); Assert.NotNull(ex1.Message); } [Fact] public void ExceptionTest12() { var ex1 = new ConditionParseException("msg"); Assert.Equal("msg", ex1.Message); } [Fact] public void ExceptionTest13() { var inner = new InvalidOperationException("f"); var ex1 = new ConditionParseException("msg", inner); Assert.Equal("msg", ex1.Message); Assert.Same(inner, ex1.InnerException); } #if !NET6_0_OR_GREATER [Fact] public void ExceptionTest14() { var inner = new InvalidOperationException("f"); var ex1 = new ConditionParseException("msg", inner); BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, ex1); ms.Position = 0; Exception ex2 = (Exception)bf.Deserialize(ms); Assert.Equal("msg", ex2.Message); Assert.Equal("f", ex2.InnerException.Message); } #endif private static ConfigurationItemFactory SetupConditionMethods() { var factories = new ConfigurationItemFactory(); factories.ConditionMethodFactory.RegisterDefinition("GetGuid", typeof(MyConditionMethods).GetMethod("GetGuid")); factories.ConditionMethodFactory.RegisterDefinition("ToInt16", typeof(MyConditionMethods).GetMethod("ToInt16")); factories.ConditionMethodFactory.RegisterDefinition("ToInt32", typeof(MyConditionMethods).GetMethod("ToInt32")); factories.ConditionMethodFactory.RegisterDefinition("ToInt64", typeof(MyConditionMethods).GetMethod("ToInt64")); factories.ConditionMethodFactory.RegisterDefinition("ToDouble", typeof(MyConditionMethods).GetMethod("ToDouble")); factories.ConditionMethodFactory.RegisterDefinition("ToSingle", typeof(MyConditionMethods).GetMethod("ToSingle")); factories.ConditionMethodFactory.RegisterDefinition("ToDateTime", typeof(MyConditionMethods).GetMethod("ToDateTime")); factories.ConditionMethodFactory.RegisterDefinition("ToDecimal", typeof(MyConditionMethods).GetMethod("ToDecimal")); factories.ConditionMethodFactory.RegisterDefinition("IsValid", typeof(MyConditionMethods).GetMethod("IsValid")); factories.ConditionMethodFactory.RegisterDefinition("DoubleEquals", typeof(MyConditionMethods).GetMethod("DoubleEquals")); factories.ConditionMethodFactory.RegisterDefinition("ManyParameters", typeof(MyConditionMethods).GetMethod("ManyParameters")); return factories; } private static void AssertEvaluationResult(object expectedResult, string conditionText) { ConditionExpression condition = ConditionParser.ParseExpression(conditionText); LogEventInfo context = CreateWellKnownContext(); object actualResult = condition.Evaluate(context); Assert.Equal(expectedResult, actualResult); } private static LogEventInfo CreateWellKnownContext() { var context = new LogEventInfo { Level = LogLevel.Warn, Message = "some message", LoggerName = "MyCompany.Product.Class" }; return context; } /// <summary> /// Conversion methods helpful in covering type promotion logic /// </summary> public class MyConditionMethods { public static Guid GetGuid() { return new Guid("{40190B01-C9C0-4F78-AA5A-615E413742E1}"); } public static short ToInt16(object v) { return Convert.ToInt16(v, CultureInfo.InvariantCulture); } public static int ToInt32(object v) { return Convert.ToInt32(v, CultureInfo.InvariantCulture); } public static long ToInt64(object v) { return Convert.ToInt64(v, CultureInfo.InvariantCulture); } public static float ToSingle(object v) { return Convert.ToSingle(v, CultureInfo.InvariantCulture); } public static decimal ToDecimal(object v) { return Convert.ToDecimal(v, CultureInfo.InvariantCulture); } public static double ToDouble(object v) { return Convert.ToDouble(v, CultureInfo.InvariantCulture); } public static DateTime ToDateTime(object v) { return Convert.ToDateTime(v, CultureInfo.InvariantCulture); } public static bool IsValid(LogEventInfo context) { return true; } public static bool DoubleEquals(object left, object right, object epsilon) { return Math.Abs(Convert.ToDouble(left) - Convert.ToDouble(right)) < Convert.ToDouble(epsilon); } public static bool ManyParameters(LogEventInfo logEvent, object first, object second, object third, object fourth) { if (logEvent.Message == first?.ToString()) return true; if (logEvent.Message == second?.ToString()) return true; if (logEvent.Message == third?.ToString()) return true; if (logEvent.Message == fourth?.ToString()) return true; return false; } } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests { using System; using System.Globalization; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using NLog.Targets; using NLog.Config; using Xunit; public class LoggerTests : NLogTestBase { private static readonly CultureInfo NLCulture = GetCultureInfo("nl-nl"); [Fact] public void TraceTest() { // test all possible overloads of the Trace() method for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='Trace' writeTo='debug' /> </rules> </nlog>"); } var logger = LogManager.GetLogger("A"); LogManager.Configuration.DefaultCultureInfo = CultureInfo.InvariantCulture; logger.Trace("message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.Trace((object)"message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (object)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Trace("message{0}{1}", 1, 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message12"); logger.Trace("message{0}{1}{2}", 1, 2, 3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message123"); logger.Trace(NLCulture, "message{0}{1}{2}", 1.4, 2.5, 3.6); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1,42,53,6"); logger.Trace("message{0}", (float)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Trace("message{0}", (double)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Trace("message{0}", (decimal)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Trace("message{0}", (object)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Trace(NLCulture, "message{0}", (object)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2,3"); logger.Trace("message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Trace("message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Trace("message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Trace("message{0}", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Trace("message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Trace("message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Trace("message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.Trace("message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Trace("message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Trace("message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagec"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messaged"); logger.Trace("message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee"); logger.Trace("message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2"); logger.Trace("message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1eee"); logger.Trace(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fff"); logger.Trace("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fffggg"); logger.Trace("message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageTrue"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageFalse"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", 2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Trace(new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "A|System.Exception: testtest"); logger.Trace(CultureInfo.InvariantCulture, new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "A|System.Exception: testtest"); logger.Trace(new Exception("test"), "message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagetest"); logger.Trace(new Exception("test"), "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.Trace(new Exception("test"), CultureInfo.InvariantCulture, "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.Trace(delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } [Fact] public void DebugTest() { // test all possible overloads of the Debug() method for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='Debug' writeTo='debug' /> </rules> </nlog>"); } var logger = LogManager.GetLogger("A"); LogManager.Configuration.DefaultCultureInfo = CultureInfo.InvariantCulture; logger.Debug("message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.Debug((object)"message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (object)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Debug("message{0}{1}", 1, 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message12"); logger.Debug("message{0}{1}{2}", 1, 2, 3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message123"); logger.Debug(NLCulture, "message{0}{1}{2}", 1.4, 2.5, 3.6); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1,42,53,6"); logger.Debug("message{0}", (float)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Debug("message{0}", (double)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Debug("message{0}", (decimal)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Debug("message{0}", (object)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Debug(NLCulture, "message{0}", (object)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2,3"); logger.Debug("message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Debug("message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Debug("message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Debug("message{0}", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Debug("message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Debug("message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Debug("message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.Debug("message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Debug("message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Debug("message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagec"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messaged"); logger.Debug("message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee"); logger.Debug("message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2"); logger.Debug("message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1eee"); logger.Debug(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fff"); logger.Debug("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fffggg"); logger.Debug("message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageTrue"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageFalse"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", 2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Debug(new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "A|System.Exception: testtest"); logger.Debug(CultureInfo.InvariantCulture, new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "A|System.Exception: testtest"); logger.Debug(new Exception("test"), "message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagetest"); logger.Debug(new Exception("test"), "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.Debug(new Exception("test"), CultureInfo.InvariantCulture, "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.Debug(delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } [Fact] public void InfoTest() { // test all possible overloads of the Info() method for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='Info' writeTo='debug' /> </rules> </nlog>"); } var logger = LogManager.GetLogger("A"); LogManager.Configuration.DefaultCultureInfo = CultureInfo.InvariantCulture; logger.Info("message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.Info((object)"message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (object)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Info("message{0}{1}", 1, 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message12"); logger.Info("message{0}{1}{2}", 1, 2, 3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message123"); logger.Info(NLCulture, "message{0}{1}{2}", 1.4, 2.5, 3.6); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1,42,53,6"); logger.Info("message{0}", (float)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Info("message{0}", (double)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Info("message{0}", (decimal)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Info("message{0}", (object)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Info(NLCulture, "message{0}", (object)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2,3"); logger.Info("message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Info("message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Info("message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Info("message{0}", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Info(CultureInfo.InvariantCulture, "message{0}", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Info("message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Info("message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Info("message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.Info(CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.Info("message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Info("message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Info("message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagec"); logger.Info(CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messaged"); logger.Info("message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd"); logger.Info(CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee"); logger.Info("message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1"); logger.Info(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2"); logger.Info("message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1eee"); logger.Info(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fff"); logger.Info("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fffggg"); logger.Info("message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageTrue"); logger.Info(CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageFalse"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Info(CultureInfo.InvariantCulture, "message{0}", 2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Info(new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "A|System.Exception: testtest"); logger.Info(CultureInfo.InvariantCulture, new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "A|System.Exception: testtest"); logger.Info(new Exception("test"), "message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagetest"); logger.Info(new Exception("test"), "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.Info(new Exception("test"), CultureInfo.InvariantCulture, "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.Info(delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } [Fact] public void WarnTest() { // test all possible overloads of the Warn() method for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); } var logger = LogManager.GetLogger("A"); LogManager.Configuration.DefaultCultureInfo = CultureInfo.InvariantCulture; logger.Warn("message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.Warn((object)"message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (object)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Warn("message{0}{1}", 1, 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message12"); logger.Warn("message{0}{1}{2}", 1, 2, 3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message123"); logger.Warn(NLCulture, "message{0}{1}{2}", 1.4, 2.5, 3.6); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1,42,53,6"); logger.Warn("message{0}", (float)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Warn("message{0}", (double)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Warn("message{0}", (decimal)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Warn("message{0}", (object)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Warn(NLCulture, "message{0}", (object)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2,3"); logger.Warn("message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Warn("message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Warn("message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Warn("message{0}", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Warn("message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Warn("message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Warn("message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.Warn("message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Warn("message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Warn("message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagec"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messaged"); logger.Warn("message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee"); logger.Warn("message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2"); logger.Warn("message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1eee"); logger.Warn(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fff"); logger.Warn("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fffggg"); logger.Warn("message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageTrue"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageFalse"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", 2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Warn(new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "A|System.Exception: testtest"); logger.Warn(CultureInfo.InvariantCulture, new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "A|System.Exception: testtest"); logger.Warn(new Exception("test"), "message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagetest"); logger.Warn(new Exception("test"), "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.Warn(new Exception("test"), CultureInfo.InvariantCulture, "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.Warn(delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } [Fact] public void ErrorTest() { // test all possible overloads of the Error() method for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='Error' writeTo='debug' /> </rules> </nlog>"); } var logger = LogManager.GetLogger("A"); LogManager.Configuration.DefaultCultureInfo = CultureInfo.InvariantCulture; logger.Error("message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.Error((object)"message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (object)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Error("message{0}{1}", 1, 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message12"); logger.Error("message{0}{1}{2}", 1, 2, 3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message123"); logger.Error(NLCulture, "message{0}{1}{2}", 1.4, 2.5, 3.6); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1,42,53,6"); logger.Error("message{0}", (float)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Error("message{0}", (double)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Error("message{0}", (decimal)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Error("message{0}", (object)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Error(NLCulture, "message{0}", (object)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2,3"); logger.Error("message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Error("message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Error("message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Error("message{0}", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Error(CultureInfo.InvariantCulture, "message{0}", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Error("message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Error("message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Error("message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.Error(CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.Error("message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Error("message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Error("message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagec"); logger.Error(CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messaged"); logger.Error("message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd"); logger.Error(CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee"); logger.Error("message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1"); logger.Error(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2"); logger.Error("message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1eee"); logger.Error(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fff"); logger.Error("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fffggg"); logger.Error("message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageTrue"); logger.Error(CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageFalse"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Error(CultureInfo.InvariantCulture, "message{0}", 2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Error(new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "A|System.Exception: testtest"); logger.Error(CultureInfo.InvariantCulture, new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "A|System.Exception: testtest"); logger.Error(new Exception("test"), "message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagetest"); logger.Error(new Exception("test"), "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.Error(new Exception("test"), CultureInfo.InvariantCulture, "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.Error(delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } [Fact] public void FatalTest() { // test all possible overloads of the Fatal() method for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); } var logger = LogManager.GetLogger("A"); LogManager.Configuration.DefaultCultureInfo = CultureInfo.InvariantCulture; logger.Fatal("message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.Fatal((object)"message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (object)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Fatal("message{0}{1}", 1, 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message12"); logger.Fatal("message{0}{1}{2}", 1, 2, 3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message123"); logger.Fatal(NLCulture, "message{0}{1}{2}", 1.4, 2.5, 3.6); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1,42,53,6"); logger.Fatal("message{0}", (float)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Fatal("message{0}", (double)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Fatal("message{0}", (decimal)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Fatal("message{0}", (object)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); logger.Fatal(NLCulture, "message{0}", (object)2.3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2,3"); logger.Fatal("message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Fatal("message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Fatal("message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Fatal("message{0}", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Fatal("message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Fatal("message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Fatal("message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.Fatal("message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Fatal("message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Fatal("message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagec"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messaged"); logger.Fatal("message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee"); logger.Fatal("message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2"); logger.Fatal("message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1eee"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fff"); logger.Fatal("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fffggg"); logger.Fatal("message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageTrue"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageFalse"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", 2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Fatal(new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "A|System.Exception: testtest"); logger.Fatal(CultureInfo.InvariantCulture, new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "A|System.Exception: testtest"); logger.Fatal(new Exception("test"), "message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagetest"); logger.Fatal(new Exception("test"), "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.Fatal(new Exception("test"), CultureInfo.InvariantCulture, "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.Fatal(delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } [Fact] public void LogTest() { // test all possible overloads of the Log(level) method foreach (LogLevel level in new LogLevel[] { LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal }) { for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='" + level.Name + @"' writeTo='debug' /> </rules> </nlog>"); } var logger = LogManager.GetLogger("A"); logger.Log(level, "message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.Log(level, "message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Log(level, "message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Log(level, "message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Log(level, "message{0}", (int)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (int)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Log(level, "message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Log(level, "message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Log(level, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.Log(level, "message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Log(level, "message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.Log(level, "message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagec"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messaged"); logger.Log(level, "message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee"); logger.Log(level, "message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2"); logger.Log(level, "message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1eee"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fff"); logger.Log(level, "message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fffggg"); logger.Log(level, "message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageTrue"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageFalse"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (double)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Log(level, new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "A|System.Exception: testtest"); logger.Log(level, CultureInfo.InvariantCulture, new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "A|System.Exception: testtest"); logger.Log(level, new Exception("test"), "message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagetest"); logger.Log(level, new Exception("test"), "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.Log(level, new Exception("test"), CultureInfo.InvariantCulture, "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.Log(level, delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } } #region Conditional Logger #if DEBUG [Fact] public void ConditionalTraceTest() { // test all possible overloads of the Trace() method for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='Trace' writeTo='debug' /> </rules> </nlog>"); } var logger = LogManager.GetLogger("A"); //set current UI culture as invariant to receive exception messages in EN Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; var argException = new ArgumentException("arg1 is obvious wrong", "arg1"); LogManager.Configuration.DefaultCultureInfo = CultureInfo.InvariantCulture; logger.ConditionalTrace("message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.ConditionalTrace(404); if (enabled == 1) AssertDebugLastMessage("debug", "A|404"); logger.ConditionalTrace(NLCulture, 404.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|404,5"); logger.ConditionalTrace(NLCulture, "hello error {0} !", 404.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|hello error 404,5 !"); logger.ConditionalTrace(NLCulture, "hello error {0} and {1} !", 404.5, 401); if (enabled == 1) AssertDebugLastMessage("debug", "A|hello error 404,5 and 401 !"); logger.ConditionalTrace(NLCulture, "hello error {0}, {1} & {2} !", 404.5, 401, 500); if (enabled == 1) AssertDebugLastMessage("debug", "A|hello error 404,5, 401 & 500 !"); logger.ConditionalTrace(NLCulture, "we've got error {0}, {1}, {2}, {3} ...", 500, 501, 502, 503); if (enabled == 1) AssertDebugLastMessage("debug", "A|we've got error 500, 501, 502, 503 ..."); logger.ConditionalTrace(argException, NLCulture, "we've got error {0}, {1}, {2}, {3} ...", 500, 501, 502, 503.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|we\'ve got error 500, 501, 502, 503,5 ...arg1 is obvious wrong\r\nParameter name: arg1"); logger.ConditionalTrace(argException, "we've got error {0}, {1}, {2}, {3} ...", 500, 501, 502, 503.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|we\'ve got error 500, 501, 502, 503.5 ...arg1 is obvious wrong\r\nParameter name: arg1"); logger.ConditionalTrace("message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalTrace("message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalTrace("message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalTrace("message{0}", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalTrace("message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalTrace("message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalTrace("message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.ConditionalTrace("message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalTrace("message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalTrace("message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagec"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messaged"); logger.ConditionalTrace("message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee"); logger.ConditionalTrace("message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2"); logger.ConditionalTrace("message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1eee"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fff"); logger.ConditionalTrace("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fffggg"); logger.ConditionalTrace("message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageTrue"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageFalse"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", 2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.ConditionalTrace(new Exception("test"), "message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagetest"); logger.ConditionalTrace(new Exception("test"), "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.ConditionalTrace(delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } [Fact] public void ConditionalTraceILogTest() { // test all possible overloads of the Trace() method for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='Trace' writeTo='debug' /> </rules> </nlog>"); } ILogger logger = LogManager.GetLogger("A"); //set current UI culture as invariant to receive exception messages in EN Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; var argException = new ArgumentException("arg1 is obvious wrong", "arg1"); LogManager.Configuration.DefaultCultureInfo = CultureInfo.InvariantCulture; logger.ConditionalTrace("message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.ConditionalTrace(404); if (enabled == 1) AssertDebugLastMessage("debug", "A|404"); logger.ConditionalTrace(NLCulture, 404.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|404,5"); logger.ConditionalTrace(NLCulture, "hello error {0} !", 404.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|hello error 404,5 !"); logger.ConditionalTrace(NLCulture, "hello error {0} and {1} !", 404.5, 401); if (enabled == 1) AssertDebugLastMessage("debug", "A|hello error 404,5 and 401 !"); logger.ConditionalTrace(NLCulture, "hello error {0}, {1} & {2} !", 404.5, 401, 500); if (enabled == 1) AssertDebugLastMessage("debug", "A|hello error 404,5, 401 & 500 !"); logger.ConditionalTrace(NLCulture, "we've got error {0}, {1}, {2}, {3} ...", 500, 501, 502, 503); if (enabled == 1) AssertDebugLastMessage("debug", "A|we've got error 500, 501, 502, 503 ..."); logger.ConditionalTrace(argException, NLCulture, "we've got error {0}, {1}, {2}, {3} ...", 500, 501, 502, 503.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|we\'ve got error 500, 501, 502, 503,5 ...arg1 is obvious wrong\r\nParameter name: arg1"); logger.ConditionalTrace(argException, "we've got error {0}, {1}, {2}, {3} ...", 500, 501, 502, 503.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|we\'ve got error 500, 501, 502, 503.5 ...arg1 is obvious wrong\r\nParameter name: arg1"); logger.ConditionalTrace("message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalTrace("message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalTrace("message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalTrace("message{0}", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalTrace("message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalTrace("message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalTrace("message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.ConditionalTrace("message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalTrace("message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalTrace("message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagec"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messaged"); logger.ConditionalTrace("message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee"); logger.ConditionalTrace("message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2"); logger.ConditionalTrace("message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1eee"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fff"); logger.ConditionalTrace("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fffggg"); logger.ConditionalTrace("message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageTrue"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageFalse"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", 2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.ConditionalTrace(new Exception("test"), "message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagetest"); logger.ConditionalTrace(new Exception("test"), "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.ConditionalTrace(delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } [Fact] public void ConditionalDebugTest() { // test all possible overloads of the Debug() method for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='Debug' writeTo='debug' /> </rules> </nlog>"); } var logger = LogManager.GetLogger("A"); //set current UI culture as invariant to receive exception messages in EN Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; var argException = new ArgumentException("arg1 is obvious wrong", "arg1"); LogManager.Configuration.DefaultCultureInfo = CultureInfo.InvariantCulture; logger.ConditionalDebug("message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.ConditionalDebug(404); if (enabled == 1) AssertDebugLastMessage("debug", "A|404"); logger.ConditionalDebug(NLCulture, 404.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|404,5"); logger.ConditionalDebug(NLCulture, "hello error {0} !", 404.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|hello error 404,5 !"); logger.ConditionalDebug(NLCulture, "hello error {0} and {1} !", 404.5, 401); if (enabled == 1) AssertDebugLastMessage("debug", "A|hello error 404,5 and 401 !"); logger.ConditionalDebug(NLCulture, "hello error {0}, {1} & {2} !", 404.5, 401, 500); if (enabled == 1) AssertDebugLastMessage("debug", "A|hello error 404,5, 401 & 500 !"); logger.ConditionalDebug(NLCulture, "we've got error {0}, {1}, {2}, {3} ...", 500, 501, 502, 503); if (enabled == 1) AssertDebugLastMessage("debug", "A|we've got error 500, 501, 502, 503 ..."); logger.ConditionalDebug(argException, NLCulture, "we've got error {0}, {1}, {2}, {3} ...", 500, 501, 502, 503.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|we\'ve got error 500, 501, 502, 503,5 ...arg1 is obvious wrong\r\nParameter name: arg1"); logger.ConditionalDebug(argException, "we've got error {0}, {1}, {2}, {3} ...", 500, 501, 502, 503.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|we\'ve got error 500, 501, 502, 503.5 ...arg1 is obvious wrong\r\nParameter name: arg1"); logger.ConditionalDebug("message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalDebug("message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalDebug("message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalDebug("message{0}", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalDebug("message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalDebug("message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalDebug("message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.ConditionalDebug("message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalDebug("message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalDebug("message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagec"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messaged"); logger.ConditionalDebug("message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee"); logger.ConditionalDebug("message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2"); logger.ConditionalDebug("message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1eee"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fff"); logger.ConditionalDebug("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fffggg"); logger.ConditionalDebug("message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageTrue"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageFalse"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", 2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.ConditionalDebug(new Exception("test"), "message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagetest"); logger.ConditionalDebug(new Exception("test"), "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.ConditionalDebug(delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } [Fact] public void ConditionalDebugILogTest() { // test all possible overloads of the Debug() method for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='Debug' writeTo='debug' /> </rules> </nlog>"); } ILogger logger = LogManager.GetLogger("A"); //set current UI culture as invariant to receive exception messages in EN Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; var argException = new ArgumentException("arg1 is obvious wrong", "arg1"); LogManager.Configuration.DefaultCultureInfo = CultureInfo.InvariantCulture; logger.ConditionalDebug("message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message"); logger.ConditionalDebug(404); if (enabled == 1) AssertDebugLastMessage("debug", "A|404"); logger.ConditionalDebug(NLCulture, 404.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|404,5"); logger.ConditionalDebug(NLCulture, "hello error {0} !", 404.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|hello error 404,5 !"); logger.ConditionalDebug(NLCulture, "hello error {0} and {1} !", 404.5, 401); if (enabled == 1) AssertDebugLastMessage("debug", "A|hello error 404,5 and 401 !"); logger.ConditionalDebug(NLCulture, "hello error {0}, {1} & {2} !", 404.5, 401, 500); if (enabled == 1) AssertDebugLastMessage("debug", "A|hello error 404,5, 401 & 500 !"); logger.ConditionalDebug(NLCulture, "we've got error {0}, {1}, {2}, {3} ...", 500, 501, 502, 503); if (enabled == 1) AssertDebugLastMessage("debug", "A|we've got error 500, 501, 502, 503 ..."); logger.ConditionalDebug(argException, NLCulture, "we've got error {0}, {1}, {2}, {3} ...", 500, 501, 502, 503.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|we\'ve got error 500, 501, 502, 503,5 ...arg1 is obvious wrong\r\nParameter name: arg1"); logger.ConditionalDebug(argException, "we've got error {0}, {1}, {2}, {3} ...", 500, 501, 502, 503.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|we\'ve got error 500, 501, 502, 503.5 ...arg1 is obvious wrong\r\nParameter name: arg1"); logger.ConditionalDebug("message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalDebug("message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalDebug("message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalDebug("message{0}", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalDebug("message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalDebug("message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalDebug("message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); logger.ConditionalDebug("message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalDebug("message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); logger.ConditionalDebug("message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagec"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "A|messaged"); logger.ConditionalDebug("message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee"); logger.ConditionalDebug("message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2"); logger.ConditionalDebug("message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1eee"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fff"); logger.ConditionalDebug("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fffggg"); logger.ConditionalDebug("message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageTrue"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "A|messageFalse"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", 2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.ConditionalDebug(new Exception("test"), "message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagetest"); logger.ConditionalDebug(new Exception("test"), "message {0}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from parametertest"); logger.ConditionalDebug(delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "A|message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } #endif #endregion [Fact] public void SwallowTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' levels='Error' writeTo='debug' /> </rules> </nlog>"); var logger = LogManager.GetLogger("A"); bool warningFix = true; bool executed = false; logger.Swallow(() => executed = true); Assert.True(executed); Assert.Equal(1, logger.Swallow(() => 1)); Assert.Equal(1, logger.Swallow(() => 1, 2)); #if !NET35 logger.SwallowAsync(Task.WhenAll()).Wait(); int executions = 0; logger.Swallow(Task.Run(() => Interlocked.Increment(ref executions))); logger.SwallowAsync(async () => { await Task.Delay(50); Interlocked.Increment(ref executions); }).Wait(); for (int i = 0; i < 500 && executions != 2; ++i) Thread.Sleep(10); Assert.Equal(2, executions); Assert.Equal(1, logger.SwallowAsync(async () => { await Task.Delay(10); return 1; }).Result); Assert.Equal(1, logger.SwallowAsync(async () => { await Task.Delay(10); return 1; }, 2).Result); #endif AssertDebugCounter("debug", 0); logger.Swallow(() => { throw new InvalidOperationException("Test message 1"); }); AssertDebugLastMessageContains("debug", "Test message 1"); Assert.Equal(0, logger.Swallow(() => { if (warningFix) throw new InvalidOperationException("Test message 2"); return 1; })); AssertDebugLastMessageContains("debug", "Test message 2"); Assert.Equal(2, logger.Swallow(() => { if (warningFix) throw new InvalidOperationException("Test message 3"); return 1; }, 2)); AssertDebugLastMessageContains("debug", "Test message 3"); #if !NET35 var fireAndFogetCompletion = new TaskCompletionSource<bool>(); fireAndFogetCompletion.SetException(new InvalidOperationException("Swallow fire and forget test message")); logger.Swallow(fireAndFogetCompletion.Task); while (!GetDebugLastMessage("debug").Contains("Swallow fire and forget test message")) Thread.Sleep(10); // Polls forever since there is nothing to wait on. var completion = new TaskCompletionSource<bool>(); completion.SetException(new InvalidOperationException("Test message 4")); logger.SwallowAsync(completion.Task).Wait(); AssertDebugLastMessageContains("debug", "Test message 4"); logger.SwallowAsync(async () => { await Task.Delay(10); throw new InvalidOperationException("Test message 5"); }).Wait(); AssertDebugLastMessageContains("debug", "Test message 5"); Assert.Equal(0, logger.SwallowAsync(async () => { await Task.Delay(10); if (warningFix) throw new InvalidOperationException("Test message 6"); return 1; }).Result); AssertDebugLastMessageContains("debug", "Test message 6"); Assert.Equal(2, logger.SwallowAsync(async () => { await Task.Delay(10); if (warningFix) throw new InvalidOperationException("Test message 7"); return 1; }, 2).Result); AssertDebugLastMessageContains("debug", "Test message 7"); #endif } [Fact] public void StringFormatWillNotCauseExceptions() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minLevel='Info' writeTo='debug' /> </rules> </nlog>"); var logger = LogManager.GetLogger("StringFormatWillNotCauseExceptions"); // invalid format string logger.Info("aaaa {0"); AssertDebugLastMessage("debug", "aaaa {0"); } [Fact] public void MultipleLoggersWithSameNameShouldBothReceiveMessages() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='first' type='Debug' layout='${message}' /> <target name='second' type='Debug' layout='${message}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='first' /> <logger name='*' minlevel='Debug' writeTo='second' /> </rules> </nlog>"); var logger = LogManager.GetLogger("A"); const string logMessage = "Anything"; logger.Debug(logMessage); AssertDebugLastMessage("first", logMessage); AssertDebugLastMessage("second", logMessage); } [Fact] public void When_Logging_LogEvent_Without_Level_Defined_No_Exception_Should_Be_Thrown() { var config = new LoggingConfiguration(); var target = new MyTarget(); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, target)); LogManager.Configuration = config; var logger = LogManager.GetLogger("A"); Assert.Throws<InvalidOperationException>(() => logger.Log(new LogEventInfo())); } [Fact] public void When_Logging_LogEvent_Without_Logger_Defined_UseLoggerName() { var config = new LoggingConfiguration(); var target = new MyTarget(); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, target)); LogManager.Configuration = config; var logger = LogManager.GetLogger("A"); logger.Log(new LogEventInfo() { Level = LogLevel.Debug, Message = "Hello" }); Assert.NotNull(target.LastEvent); Assert.Equal(LogLevel.Debug, target.LastEvent.Level); Assert.Equal(logger.Name, target.LastEvent.LoggerName); logger.Log(logger.GetType(), new LogEventInfo() { Level = LogLevel.Info, Message = "Hello" }); Assert.NotNull(target.LastEvent); Assert.Equal(LogLevel.Info, target.LastEvent.Level); Assert.Equal(logger.Name, target.LastEvent.LoggerName); logger.Log(new LogEventInfo() { Level = LogLevel.Warn, Message = "Hello", LoggerName = string.Empty }); Assert.NotNull(target.LastEvent); Assert.Equal(LogLevel.Warn, target.LastEvent.Level); Assert.Equal(string.Empty, target.LastEvent.LoggerName); logger.Log(logger.GetType(), new LogEventInfo() { Level = LogLevel.Error, Message = "Hello", LoggerName = string.Empty }); Assert.NotNull(target.LastEvent); Assert.Equal(LogLevel.Error, target.LastEvent.Level); Assert.Equal(string.Empty, target.LastEvent.LoggerName); } [Fact] public void SingleTargetMessageFormatOptimizationTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='target1' type='Debug' layout='${logger}|${message}' /> <target name='target2' type='Debug' layout='${logger}|${message}' /> </targets> <rules> <logger name='SingleTarget' writeTo='target1' /> <logger name='DualTarget' writeTo='target1,target2' /> </rules> </nlog>"); var singleLogger = LogManager.GetLogger("SingleTarget"); var dualLogger = LogManager.GetLogger("DualTarget"); ConfigurationItemFactory.Default.ParseMessageTemplates = true; singleLogger.Debug("Hello"); AssertDebugLastMessage("target1", "SingleTarget|Hello"); singleLogger.Debug("Hello {0}", "World"); AssertDebugLastMessage("target1", "SingleTarget|Hello World"); dualLogger.Debug("Hello"); AssertDebugLastMessage("target1", "DualTarget|Hello"); AssertDebugLastMessage("target2", "DualTarget|Hello"); dualLogger.Debug("Hello {0}", "World"); AssertDebugLastMessage("target1", "DualTarget|Hello World"); AssertDebugLastMessage("target2", "DualTarget|Hello World"); ConfigurationItemFactory.Default.ParseMessageTemplates = false; singleLogger.Debug("Hello"); AssertDebugLastMessage("target1", "SingleTarget|Hello"); singleLogger.Debug("Hello {0}", "World"); AssertDebugLastMessage("target1", "SingleTarget|Hello World"); dualLogger.Debug("Hello"); AssertDebugLastMessage("target1", "DualTarget|Hello"); AssertDebugLastMessage("target2", "DualTarget|Hello"); dualLogger.Debug("Hello {0}", "World"); AssertDebugLastMessage("target1", "DualTarget|Hello World"); AssertDebugLastMessage("target2", "DualTarget|Hello World"); ConfigurationItemFactory.Default.ParseMessageTemplates = null; singleLogger.Debug("Hello"); AssertDebugLastMessage("target1", "SingleTarget|Hello"); singleLogger.Debug("Hello {0}", "World"); AssertDebugLastMessage("target1", "SingleTarget|Hello World"); dualLogger.Debug("Hello"); AssertDebugLastMessage("target1", "DualTarget|Hello"); AssertDebugLastMessage("target2", "DualTarget|Hello"); dualLogger.Debug("Hello {0}", "World"); AssertDebugLastMessage("target1", "DualTarget|Hello World"); AssertDebugLastMessage("target2", "DualTarget|Hello World"); } [Theory] [InlineData(null, "0", "@Client", Skip = "Not supported for performance reasons")] [InlineData(true, "0", "@Client")] [InlineData(null, "$0", "@Client")] [InlineData(true, "$0", "@Client")] [InlineData(null, "@0", "@Client")] [InlineData(true, "@0", "@Client")] [InlineData(null, "1", "@Client", Skip = "Not supported for performance reasons")] [InlineData(true, "1", "@Client")] [InlineData(null, "@Client", "1")] [InlineData(true, "@Client", "1")] [InlineData(true, "0", "1")] [InlineData(false, "0", "1")] [InlineData(true, "OrderId", "Client")] //succeeds, but gives JSON like (no quoted key, missing quotes around string, =, other spacing) [InlineData(true, "OrderId", "@Client")] [InlineData(null, "OrderId", "@Client")] public void MixedStructuredEventsConfigTest(bool? parseMessageTemplates, string param1, string param2) { LogManager.Configuration = CreateSimpleDebugConfig(parseMessageTemplates); var logger = LogManager.GetLogger("A"); logger.Debug("Process order {" + param1 + "} for {" + param2 + "}", 13424, new { ClientId = 3001, ClientName = "<NAME>" }); string param1Value; if (param1.StartsWith("$")) { param1Value = "\"13424\""; } else { param1Value = "13424"; } string param2Value; if (param2.StartsWith("@")) { param2Value = "{\"ClientId\":3001, \"ClientName\":\"<NAME>\"}"; } else { param2Value = "{ ClientId = 3001, ClientName = <NAME> }"; } AssertDebugLastMessage("debug", $"A|Process order {param1Value} for {param2Value}"); } [Fact] public void StructuredParametersShouldHandleDeferredCheck() { LoggingConfiguration configuration = new LoggingConfiguration(); var debugTarget = new DebugTarget("debug") { Layout = "${message}" }; var bufferingTarget = new NLog.Targets.Wrappers.BufferingTargetWrapper("flushTarget", debugTarget); configuration.AddTarget(debugTarget); configuration.AddRuleForAllLevels(bufferingTarget); LogManager.Configuration = configuration; System.Text.StringBuilder sb = new System.Text.StringBuilder("Test"); LogEventInfo logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, "{0}", new object[] { sb }); LogManager.GetLogger("deferred").Log(logEventInfo); sb.Clear(); AssertDebugLastMessage("debug", ""); // Not written string formattedMessage = logEventInfo.FormattedMessage; Assert.Equal("Test", formattedMessage); var properties = logEventInfo.Properties; Assert.Empty(properties); string formattedMessage2 = logEventInfo.FormattedMessage; Assert.Equal("Test", formattedMessage2); LogManager.Flush(); AssertDebugLastMessage("debug", "Test"); } [Theory] [InlineData(true)] [InlineData(false)] [InlineData(null)] public void TooManyStructuredParametersShouldKeepBeInParamList(bool? parseMessageTemplates) { LogManager.Configuration = CreateSimpleDebugConfig(parseMessageTemplates); var target = new MyTarget(); LogManager.Configuration.AddRuleForAllLevels(target); LogManager.ReconfigExistingLoggers(); var logger = LogManager.GetLogger("A"); logger.Debug("Hello World {0}", "world", "universe"); Assert.Equal(2, target.LastEvent.Parameters.Length); Assert.Equal("world", target.LastEvent.Parameters[0]); Assert.Equal("universe", target.LastEvent.Parameters[1]); } [Theory] [InlineData(true, null)] [InlineData(false, null)] [InlineData(null, true)] [InlineData(null, false)] [InlineData(null, null)] public void StructuredEventsConfigTest(bool? parseMessageTemplates, bool? overrideParseMessageTemplates) { LogManager.Configuration = CreateSimpleDebugConfig(parseMessageTemplates); if (parseMessageTemplates.HasValue) { Assert.Equal(ConfigurationItemFactory.Default.ParseMessageTemplates, parseMessageTemplates.Value); } if (overrideParseMessageTemplates.HasValue) { ConfigurationItemFactory.Default.ParseMessageTemplates = overrideParseMessageTemplates.Value; } var logger = LogManager.GetLogger("A"); logger.Debug("Hello World {0}", new object[] { null }); if (parseMessageTemplates == true || overrideParseMessageTemplates == true) AssertDebugLastMessage("debug", "A|Hello World NULL"); else AssertDebugLastMessage("debug", "A|Hello World "); } [Fact] public void StructuredEventsTest1() { // test all possible overloads of the Error() method var James = new Person("James"); var Mike = new Person("Mike"); var Jane = new Person("Jane") { Childs = new List<Person> { James, Mike } }; for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' levels='Error' writeTo='debug' /> </rules> </nlog>"); } var logger = LogManager.GetLogger("A"); LogManager.Configuration.DefaultCultureInfo = CultureInfo.InvariantCulture; logger.Error("hello from {@Person}", Jane); if (enabled == 1) AssertDebugLastMessage("debug", "A|hello from {\"Name\":\"Jane\", \"Childs\":[{\"Name\":\"James\"},{\"Name\":\"Mike\"}]}"); logger.Error("Test structured logging in {NLogVersion} for .NET {NETVersion}", "4.5-alpha01", new[] { 3.5, 4, 4.5 }); if (enabled == 1) AssertDebugLastMessage("debug", "A|Test structured logging in \"4.5-alpha01\" for .NET 3.5, 4, 4.5"); logger.Error("hello from {FamilyNames}", new Dictionary<int, string>() { { 1, "James" }, { 2, "Mike" }, { 3, "Jane" } }); if (enabled == 1) AssertDebugLastMessage("debug", "A|hello from 1=\"James\", 2=\"Mike\", 3=\"Jane\""); logger.Error("message {a} {b}", 1, 2); if (enabled == 1) { AssertDebugLastMessage("debug", "A|message 1 2"); } logger.Error("message{a}{b}{c}", 1, 2, 3); if (enabled == 1) { AssertDebugLastMessage("debug", "A|message123"); } logger.Error("message {a} {b} {c}", "1", "2", "3"); if (enabled == 1) { //todo single quotes AssertDebugLastMessage("debug", "A|message \"1\" \"2\" \"3\""); } logger.Error("message{a}{b}{c}", 1, 2, 3); if (enabled == 1) AssertDebugLastMessage("debug", "A|message123"); logger.Error("message{a,2}{b,-2}{c,1}{d,-1}{f,1}", 1, 2, 3, 4, ""); if (enabled == 1) AssertDebugLastMessage("debug", "A|message 12 34\"\""); //todo other tests // logger.Error(NLCulture, "message{0}{1}{2}", 1.4, 2.5, 3.6); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message1,42,53,6"); // logger.Error("message{0}", (float)2.3); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); // logger.Error("message{0}", (double)2.3); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); // logger.Error("message{0}", (decimal)2.3); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); // logger.Error("message{0}", (object)2.3); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.3"); // logger.Error(NLCulture, "message{0}", (object)2.3); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message2,3"); // logger.Error("message{0}", (ulong)1); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); // logger.Error(CultureInfo.InvariantCulture, "message{0}", (ulong)2); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); // logger.Error("message{0}", (long)1); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); // logger.Error(CultureInfo.InvariantCulture, "message{0}", (long)2); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); // logger.Error("message{0}", (uint)1); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); // logger.Error(CultureInfo.InvariantCulture, "message{0}", (uint)2); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); // logger.Error("message{0}", 1); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); // logger.Error(CultureInfo.InvariantCulture, "message{0}", 2); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); // logger.Error("message{0}", (ushort)1); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); // logger.Error(CultureInfo.InvariantCulture, "message{0}", (ushort)2); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); // logger.Error("message{0}", (sbyte)1); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); // logger.Error(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); // logger.Error("message{0}", this); // if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); // logger.Error(CultureInfo.InvariantCulture, "message{0}", this); // if (enabled == 1) AssertDebugLastMessage("debug", "A|messageobject-to-string"); // logger.Error("message{0}", (short)1); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); // logger.Error(CultureInfo.InvariantCulture, "message{0}", (short)2); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); // logger.Error("message{0}", (byte)1); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message1"); // logger.Error(CultureInfo.InvariantCulture, "message{0}", (byte)2); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message2"); // logger.Error("message{0}", 'c'); // if (enabled == 1) AssertDebugLastMessage("debug", "A|messagec"); // logger.Error(CultureInfo.InvariantCulture, "message{0}", 'd'); // if (enabled == 1) AssertDebugLastMessage("debug", "A|messaged"); // logger.Error("message{0}", "ddd"); // if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd"); // logger.Error(CultureInfo.InvariantCulture, "message{0}", "eee"); // if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee"); // logger.Error("message{0}{1}", "ddd", 1); // if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1"); // logger.Error(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); // if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2"); // logger.Error("message{0}{1}{2}", "ddd", 1, "eee"); // if (enabled == 1) AssertDebugLastMessage("debug", "A|messageddd1eee"); // logger.Error(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); // if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fff"); // logger.Error("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); // if (enabled == 1) AssertDebugLastMessage("debug", "A|messageeee2fffggg"); // logger.Error("message{0}", true); // if (enabled == 1) AssertDebugLastMessage("debug", "A|messageTrue"); // logger.Error(CultureInfo.InvariantCulture, "message{0}", false); // if (enabled == 1) AssertDebugLastMessage("debug", "A|messageFalse"); // logger.Error(CultureInfo.InvariantCulture, "message{0}", (float)2.5); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); // logger.Error(CultureInfo.InvariantCulture, "message{0}", 2.5); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); // logger.Error(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message2.5"); logger.Error(new Exception("test"), "message"); if (enabled == 1) AssertDebugLastMessage("debug", "A|messagetest"); logger.Error(new Exception("test"), "message {Exception}", "from parameter"); if (enabled == 1) AssertDebugLastMessage("debug", "A|message \"from parameter\"test"); // logger.Error(delegate { return "message from lambda"; }); // if (enabled == 1) AssertDebugLastMessage("debug", "A|message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } /// <summary> /// Only properties /// </summary> [Fact] public void TestStructuredProperties_json() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' > <layout type='JsonLayout' IncludeAllProperties='true'> <attribute name='LogMessage' layout='${message:raw=true}' /> </layout> </target> </targets> <rules> <logger name='*' levels='Error' writeTo='debug' /> </rules> </nlog>"); var logger = LogManager.GetLogger("A"); logger.Error("Login request from {@Username} for {$Application}", new Person("John"), "BestApplicationEver"); AssertDebugLastMessage("debug", "{ \"LogMessage\": \"Login request from {@Username} for {$Application}\", \"Username\": {\"Name\":\"John\"}, \"Application\": \"BestApplicationEver\" }"); } /// <summary> /// Only properties /// </summary> [Fact] public void TestStructuredProperties_json_async() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <target name='debugbuffer' type='bufferingWrapper'> <target name='debug' type='Debug' > <layout type='JsonLayout' IncludeAllProperties='true'> <attribute name='LogMessage' layout='${message:raw=true}' /> </layout> </target> </target> </targets> <rules> <logger name='*' levels='Error' writeTo='debugbuffer' /> </rules> </nlog>"); var logger = LogManager.GetLogger("A"); System.Text.StringBuilder sb = new System.Text.StringBuilder("BestApplicationEver"); logger.Error("Login request from {@Username} for {$Application}", new Person("John"), sb); sb.Clear(); LogManager.Flush(); AssertDebugLastMessage("debug", "{ \"LogMessage\": \"Login request from {@Username} for {$Application}\", \"Username\": {\"Name\":\"John\"}, \"Application\": \"BestApplicationEver\" }"); } /// <summary> /// Properties and message /// </summary> [Fact] public void TestStructuredProperties_json_compound() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' > <layout type='CompoundLayout'> <layout type='SimpleLayout' text='${message}' /> <layout type='JsonLayout' IncludeAllProperties='true' maxRecursionLimit='0' /> </layout> </target> </targets> <rules> <logger name='*' levels='Error' writeTo='debug' /> </rules> </nlog>"); var logger = LogManager.GetLogger("A"); logger.Error("Login request from {Username} for {Application}", new Person("\"John\""), "BestApplicationEver"); AssertDebugLastMessage("debug", "Login request from \"John\" for \"BestApplicationEver\"{ \"Username\": \"\\\"John\\\"\", \"Application\": \"BestApplicationEver\" }"); } [Fact] public void TestOptimizedBlackHoleLogger() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout='${message}' /> </targets> <rules> <logger name='Microsoft*' maxLevel='Info' writeTo='' final='true' /> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); var loggerMicrosoft = LogManager.GetLogger("Microsoft.NoiseGenerator"); var loggerA = LogManager.GetLogger("A"); loggerMicrosoft.Warn("Important Noise"); AssertDebugLastMessage("debug", "Important Noise"); loggerMicrosoft.Debug("White Noise"); AssertDebugLastMessage("debug", "Important Noise"); loggerA.Debug("Good Noise"); AssertDebugLastMessage("debug", "Good Noise"); loggerA.Error("Important Noise"); AssertDebugLastMessage("debug", "Important Noise"); } private static XmlLoggingConfiguration CreateSimpleDebugConfig(bool? parseMessageTemplates) { return XmlLoggingConfiguration.CreateFromXmlString(@" <nlog parseMessageTemplates='" + (parseMessageTemplates?.ToString() ?? string.Empty) + @"'> <targets><target name='debug' type='Debug' layout='${logger}|${message}${exception:message}' /></targets> <rules> <logger name='*' writeTo='debug' /> </rules> </nlog>"); } private class Person { public Person() { } public Person(string name) { Name = name; } public string Name { get; set; } public List<Person> Childs { get; set; } public override string ToString() { return Name; } } public class MyTarget : TargetWithLayout { public MyTarget() { // enforce creation of stack trace Layout = "${stacktrace}"; } public MyTarget(string name) : this() { Name = name; } public LogEventInfo LastEvent { get; private set; } protected override void Write(LogEventInfo logEvent) { LastEvent = logEvent; base.Write(logEvent); } } public override string ToString() { return "object-to-string"; } [Fact] public void LogEventTemplateHandleTrickyDictionary() { IDictionary<object, object> dictionary = new Internal.TrickyTestDictionary(); dictionary.Add("key1", 13); dictionary.Add("key 2", 1.3m); LogEventInfo logEventInfo = new LogEventInfo(LogLevel.Info, "Logger", null, "{mybad}", new object[] { dictionary }); var result = logEventInfo.FormattedMessage; Assert.Contains("\"key1\"=13, \"key 2\"", result); } [Fact] public void LogEventTemplateShouldHaveProperties() { var logEventInfo = new LogEventInfo(LogLevel.Debug, "logger1", null, "{A}", new object[] { "b" }); var props = logEventInfo.Properties; Assert.Contains("A", props.Keys); Assert.Equal("b", props["A"]); Assert.Equal(1, props.Count); } [Fact] public void LogEventTemplateShouldHaveProperties_even_when_changed() { var logEventInfo = new LogEventInfo(LogLevel.Debug, "logger1", null, "{A}", new object[] { "b" }); var props = logEventInfo.Properties; logEventInfo.Message = "{A}"; Assert.Contains("A", props.Keys); Assert.Equal("b", props["A"]); Assert.Equal(1, props.Count); } static Logger GetContextLoggerFromTemporary(string loggerName) { var globalLogger = LogManager.GetLogger(loggerName); var loggerStage1 = globalLogger.WithProperty("Stage", 1); globalLogger.Trace("{Stage}", "Connected"); return loggerStage1; } [Fact] public void LogEventTemplateShouldOverrideProperties() { string uniqueLoggerName = Guid.NewGuid().ToString(); var config = new LoggingConfiguration(); var target = new MyTarget(); config.LoggingRules.Add(new LoggingRule(uniqueLoggerName, LogLevel.Trace, target)); LogManager.Configuration = config; Logger loggerStage1 = GetContextLoggerFromTemporary(uniqueLoggerName); GC.Collect(); // Try and free globalLogger var loggerStage2 = loggerStage1.WithProperty("Stage", 2); Assert.Single(target.LastEvent.Properties); AssertContainsInDictionary(target.LastEvent.Properties, "Stage", "Connected"); loggerStage1.Trace("Login attempt from {userid}", "kermit"); Assert.Equal(2, target.LastEvent.Properties.Count); AssertContainsInDictionary(target.LastEvent.Properties, "Stage", 1); AssertContainsInDictionary(target.LastEvent.Properties, "userid", "kermit"); loggerStage2.Trace("Login successful for {userid}", "kermit"); Assert.Equal(2, target.LastEvent.Properties.Count); AssertContainsInDictionary(target.LastEvent.Properties, "Stage", 2); AssertContainsInDictionary(target.LastEvent.Properties, "userid", "kermit"); loggerStage2.Trace("{Stage}", "Disconnected"); Assert.Single(target.LastEvent.Properties); AssertContainsInDictionary(target.LastEvent.Properties, "Stage", "Disconnected"); } [Fact] public void LoggerWithPropertyShouldInheritLogLevel() { string uniqueLoggerName = Guid.NewGuid().ToString(); var config = new LoggingConfiguration(); var target = new MyTarget(); config.LoggingRules.Add(new LoggingRule(uniqueLoggerName, LogLevel.Trace, target)); LogManager.Configuration = config; Logger loggerStage1 = GetContextLoggerFromTemporary(uniqueLoggerName); GC.Collect(); // Try and free globalLogger Assert.Single(target.LastEvent.Properties); AssertContainsInDictionary(target.LastEvent.Properties, "Stage", "Connected"); LogManager.Configuration.LoggingRules[0].DisableLoggingForLevel(LogLevel.Trace); LogManager.ReconfigExistingLoggers(); // Refreshes the configuration of globalLogger var loggerStage2 = loggerStage1.WithProperty("Stage", 2); loggerStage2.Trace("Login attempt from {userid}", "kermit"); AssertContainsInDictionary(target.LastEvent.Properties, "Stage", "Connected"); // Verify nothing writtne loggerStage2.Debug("{Stage}", "Disconnected"); AssertContainsInDictionary(target.LastEvent.Properties, "Stage", "Disconnected"); } [Fact] [Obsolete("Instead use WithProperty which is safe. If really necessary then one can use Properties-property. Marked obsolete on NLog 5.0")] public void LoggerSetPropertyChangesCurrentLogger() { string uniqueLoggerName = Guid.NewGuid().ToString(); var config = new LoggingConfiguration(); var target = new MyTarget(); config.LoggingRules.Add(new LoggingRule(uniqueLoggerName, LogLevel.Trace, target)); LogManager.Configuration = config; var globalLogger = LogManager.GetLogger(uniqueLoggerName); globalLogger.SetProperty("Stage", 1); globalLogger.Trace("Login attempt from {userid}", "kermit"); AssertContainsInDictionary(target.LastEvent.Properties, "Stage", 1); var loggerStage2 = globalLogger.WithProperty("Stage", 2); loggerStage2.Trace("Hello from {userid}", "kermit"); AssertContainsInDictionary(target.LastEvent.Properties, "Stage", 2); globalLogger.SetProperty("Stage", 4); loggerStage2.SetProperty("Stage", 3); loggerStage2.Trace("Goodbye from {userid}", "kermit"); AssertContainsInDictionary(target.LastEvent.Properties, "Stage", 3); globalLogger.Trace("Logoff by {userid}", "kermit"); AssertContainsInDictionary(target.LastEvent.Properties, "Stage", 4); } [Fact] [Obsolete("Obsoleted too complex interface. Obsoleted in NLog 5.0")] public void ObsoleteILoggerExceptionMethods() { // Arrange var logFactory = new LogFactory(); var logConfig = new LoggingConfiguration(logFactory); var debugTarget = new DebugTarget("debug") { Layout = "${level}|${message}|${exception:format=message}" }; logConfig.AddRuleForAllLevels(debugTarget); logFactory.Configuration = logConfig; ILogger logger = logFactory.GetLogger(nameof(ObsoleteILoggerExceptionMethods)); logger.LogException(LogLevel.Info, "Hello World", new Exception("Galactic Failure")); Assert.Equal("Info|Hello World|Galactic Failure", debugTarget.LastMessage); logger.TraceException("Hello World", new Exception("Galactic Failure")); Assert.Equal("Trace|Hello World|Galactic Failure", debugTarget.LastMessage); logger.DebugException("Hello World", new Exception("Galactic Failure")); Assert.Equal("Debug|Hello World|Galactic Failure", debugTarget.LastMessage); logger.InfoException("Hello World", new Exception("Galactic Failure")); Assert.Equal("Info|Hello World|Galactic Failure", debugTarget.LastMessage); logger.WarnException("Hello World", new Exception("Galactic Failure")); Assert.Equal("Warn|Hello World|Galactic Failure", debugTarget.LastMessage); logger.ErrorException("Hello World", new Exception("Galactic Failure")); Assert.Equal("Error|Hello World|Galactic Failure", debugTarget.LastMessage); logger.FatalException("Hello World", new Exception("Galactic Failure")); Assert.Equal("Fatal|Hello World|Galactic Failure", debugTarget.LastMessage); logger.Log(LogLevel.Info, "Hello World", new Exception("Galactic Failure")); Assert.Equal("Info|Hello World|Galactic Failure", debugTarget.LastMessage); logger.Trace("Hello World", new Exception("Galactic Failure")); Assert.Equal("Trace|Hello World|Galactic Failure", debugTarget.LastMessage); logger.Debug("Hello World", new Exception("Galactic Failure")); Assert.Equal("Debug|Hello World|Galactic Failure", debugTarget.LastMessage); logger.Info("Hello World", new Exception("Galactic Failure")); Assert.Equal("Info|Hello World|Galactic Failure", debugTarget.LastMessage); logger.Warn("Hello World", new Exception("Galactic Failure")); Assert.Equal("Warn|Hello World|Galactic Failure", debugTarget.LastMessage); logger.Error("Hello World", new Exception("Galactic Failure")); Assert.Equal("Error|Hello World|Galactic Failure", debugTarget.LastMessage); logger.Fatal("Hello World", new Exception("Galactic Failure")); Assert.Equal("Fatal|Hello World|Galactic Failure", debugTarget.LastMessage); } [Fact] public void LoggerPushScopeContextUpdatesMDLC() { // Arrange var logFactory = new LogFactory(); var logConfig = new LoggingConfiguration(logFactory); var debugTarget = new DebugTarget("debug") { Layout = "${mdlc:hello}" }; logConfig.AddRuleForAllLevels(debugTarget); logFactory.Configuration = logConfig; var logger = logFactory.GetLogger(nameof(LoggerPushScopeContextUpdatesMDLC)); // Act using (logger.PushScopeProperty("hello", "world")) { logger.Info("Test"); } // Assert Assert.Equal("world", debugTarget.LastMessage); } [Fact] public void LoggerPushScopeContextUpdatesNDLC() { // Arrange var logFactory = new LogFactory(); var logConfig = new LoggingConfiguration(logFactory); var debugTarget = new DebugTarget("debug") { Layout = "${ndlc}" }; logConfig.AddRuleForAllLevels(debugTarget); logFactory.Configuration = logConfig; var logger = logFactory.GetLogger(nameof(LoggerPushScopeContextUpdatesMDLC)); // Act using (logger.PushScopeNested("hello world")) { logger.Info("Test"); } // Assert Assert.Equal("hello world", debugTarget.LastMessage); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 #define SupportsMutex #endif namespace NLog.Internal { using System; using NLog.Common; using NLog.Internal.FileAppenders; /// <summary> /// Detects the platform the NLog is running on. /// </summary> internal static class MutexDetector { /// <summary> /// Gets a value indicating whether current runtime supports use of mutex /// </summary> public static bool SupportsSharableMutex => _supportsSharableMutex ?? (_supportsSharableMutex = ResolveSupportsSharableMutex()).Value; private static bool? _supportsSharableMutex; /// <summary> /// Will creating a mutex succeed runtime? /// </summary> private static bool ResolveSupportsSharableMutex() { try { #if SupportsMutex #if !NETSTANDARD if (Environment.Version.Major < 4 && PlatformDetector.IsMono) return false; // MONO ver. 4 is needed for named Mutex to work #endif var mutex = BaseMutexFileAppender.ForceCreateSharableMutex("NLogMutexTester"); mutex.Close(); //"dispose" return true; #endif } catch (Exception ex) { InternalLogger.Debug(ex, "Failed to create sharable mutex processes"); } return false; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal.FileAppenders { using System; using System.IO; using System.Security; /// <summary> /// Optimized single-process file appender which keeps the file open for exclusive write. /// </summary> [SecuritySafeCritical] internal class SingleProcessFileAppender : BaseFileAppender { public static readonly IFileAppenderFactory TheFactory = new Factory(); private FileStream _file; private readonly bool _enableFileDeleteSimpleMonitor; private int _lastSimpleMonitorCheckTickCount; /// <summary> /// Initializes a new instance of the <see cref="SingleProcessFileAppender" /> class. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="parameters">The parameters.</param> public SingleProcessFileAppender(string fileName, ICreateFileParameters parameters) : base(fileName, parameters) { _file = CreateFileStream(false); _enableFileDeleteSimpleMonitor = parameters.EnableFileDeleteSimpleMonitor; _lastSimpleMonitorCheckTickCount = Environment.TickCount; } /// <inheritdoc/> public override void Write(byte[] bytes, int offset, int count) { if (_file is null) { return; } if (_enableFileDeleteSimpleMonitor && MonitorForEnableFileDeleteEvent(FileName, ref _lastSimpleMonitorCheckTickCount)) { NLog.Common.InternalLogger.Debug("{0}: Recreating FileStream because no longer File.Exists: '{1}'", CreateFileParameters, FileName); CloseFileSafe(ref _file, FileName); _file = CreateFileStream(false); } _file.Write(bytes, offset, count); } /// <inheritdoc/> public override void Flush() { _file?.Flush(); } /// <inheritdoc/> public override void Close() { CloseFileSafe(ref _file, FileName); } /// <inheritdoc/> public override DateTime? GetFileCreationTimeUtc() { return CreationTimeUtc; } /// <inheritdoc/> public override long? GetFileLength() { return _file?.Length; } /// <summary> /// Factory class. /// </summary> private sealed class Factory : IFileAppenderFactory { /// <inheritdoc/> BaseFileAppender IFileAppenderFactory.Open(string fileName, ICreateFileParameters parameters) { return new SingleProcessFileAppender(fileName, parameters); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections; using System.Collections.Generic; /// <summary> /// HashSet optimized for single item /// </summary> /// <typeparam name="T"></typeparam> internal struct SingleItemOptimizedHashSet<T> : ICollection<T> { private readonly T _singleItem; private HashSet<T> _hashset; private readonly IEqualityComparer<T> _comparer; private IEqualityComparer<T> Comparer => _comparer ?? EqualityComparer<T>.Default; public struct SingleItemScopedInsert : IDisposable { private readonly T _singleItem; private readonly HashSet<T> _hashset; /// <summary> /// Insert single item on scope start, and remove on scope exit /// </summary> /// <param name="singleItem">Item to insert in scope</param> /// <param name="existing">Existing hashset to update</param> /// <param name="forceHashSet">Force allocation of real hashset-container</param> /// <param name="comparer">HashSet EqualityComparer</param> public SingleItemScopedInsert(T singleItem, ref SingleItemOptimizedHashSet<T> existing, bool forceHashSet, IEqualityComparer<T> comparer) { _singleItem = singleItem; if (existing._hashset != null) { existing._hashset.Add(singleItem); _hashset = existing._hashset; } else if (forceHashSet) { existing = new SingleItemOptimizedHashSet<T>(singleItem, existing, comparer); existing.Add(singleItem); _hashset = existing._hashset; } else { existing = new SingleItemOptimizedHashSet<T>(singleItem, existing, comparer); _hashset = null; } } public void Dispose() { if (_hashset != null) { _hashset.Remove(_singleItem); } } } public int Count => _hashset?.Count ?? (EqualityComparer<T>.Default.Equals(_singleItem, default(T)) ? 0 : 1); // Object Equals to default value public bool IsReadOnly => false; public SingleItemOptimizedHashSet(T singleItem, SingleItemOptimizedHashSet<T> existing, IEqualityComparer<T> comparer = null) { _comparer = existing._comparer ?? comparer ?? EqualityComparer<T>.Default; if (existing._hashset != null) { _hashset = new HashSet<T>(existing._hashset, _comparer); _hashset.Add(singleItem); _singleItem = default(T); } else if (existing.Count == 1) { _hashset = new HashSet<T>(_comparer); _hashset.Add(existing._singleItem); _hashset.Add(singleItem); _singleItem = default(T); } else { _hashset = null; _singleItem = singleItem; } } /// <summary> /// Add item to collection, if it not already exists /// </summary> /// <param name="item">Item to insert</param> public void Add(T item) { if (_hashset != null) { _hashset.Add(item); } else { var hashset = new HashSet<T>(Comparer); if (Count != 0) { hashset.Add(_singleItem); } hashset.Add(item); _hashset = hashset; } } /// <summary> /// Clear hashset /// </summary> public void Clear() { if (_hashset != null) { _hashset.Clear(); } else { _hashset = new HashSet<T>(Comparer); } } /// <summary> /// Check if hashset contains item /// </summary> /// <param name="item"></param> /// <returns>Item exists in hashset (true/false)</returns> public bool Contains(T item) { if (_hashset != null) { return _hashset.Contains(item); } else { return Count == 1 && Comparer.Equals(_singleItem, item); } } /// <summary> /// Remove item from hashset /// </summary> /// <param name="item"></param> /// <returns>Item removed from hashset (true/false)</returns> public bool Remove(T item) { if (_hashset != null) { return _hashset.Remove(item); } else { _hashset = new HashSet<T>(Comparer); return Comparer.Equals(_singleItem, item); } } /// <summary> /// Copy items in hashset to array /// </summary> /// <param name="array">Destination array</param> /// <param name="arrayIndex">Array offset</param> public void CopyTo(T[] array, int arrayIndex) { if (_hashset != null) { _hashset.CopyTo(array, arrayIndex); } else if (Count == 1) { array[arrayIndex] = _singleItem; } } /// <summary> /// Create hashset enumerator /// </summary> /// <returns>Enumerator</returns> public IEnumerator<T> GetEnumerator() { if (_hashset != null) { return _hashset.GetEnumerator(); } else { return SingleItemEnumerator(); } } private IEnumerator<T> SingleItemEnumerator() { if (Count != 0) yield return _singleItem; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public sealed class ReferenceEqualityComparer : IEqualityComparer<T> { public static readonly ReferenceEqualityComparer Default = new ReferenceEqualityComparer(); bool IEqualityComparer<T>.Equals(T x, T y) { return ReferenceEquals(x, y); } int IEqualityComparer<T>.GetHashCode(T obj) { return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class FallbackGroupTargetTests : NLogTestBase { [Fact] public void FirstTargetWorks_Write_AllEventsAreWrittenToFirstTarget() { var myTarget1 = new MyTarget(); var myTarget2 = new MyTarget(); var myTarget3 = new MyTarget(); var wrapper = CreateAndInitializeFallbackGroupTarget(false, myTarget1, myTarget2, myTarget3); WriteAndAssertNoExceptions(wrapper); Assert.Equal(10, myTarget1.WriteCount); Assert.Equal(0, myTarget2.WriteCount); Assert.Equal(0, myTarget3.WriteCount); AssertNoFlushException(wrapper); } [Fact] public void FirstTargetFails_Write_SecondTargetWritesAllEvents() { using (new NoThrowNLogExceptions()) { var myTarget1 = new MyTarget { FailCounter = 1 }; var myTarget2 = new MyTarget(); var myTarget3 = new MyTarget(); var wrapper = CreateAndInitializeFallbackGroupTarget(false, myTarget1, myTarget2, myTarget3); WriteAndAssertNoExceptions(wrapper); Assert.Equal(1, myTarget1.WriteCount); Assert.Equal(10, myTarget2.WriteCount); Assert.Equal(0, myTarget3.WriteCount); AssertNoFlushException(wrapper); } } [Fact] public void FirstTwoTargetsFails_Write_ThirdTargetWritesAllEvents() { using (new NoThrowNLogExceptions()) { var myTarget1 = new MyTarget { FailCounter = 1 }; var myTarget2 = new MyTarget { FailCounter = 1 }; var myTarget3 = new MyTarget(); var wrapper = CreateAndInitializeFallbackGroupTarget(false, myTarget1, myTarget2, myTarget3); WriteAndAssertNoExceptions(wrapper); Assert.Equal(1, myTarget1.WriteCount); Assert.Equal(1, myTarget2.WriteCount); Assert.Equal(10, myTarget3.WriteCount); AssertNoFlushException(wrapper); } } [Fact] public void ReturnToFirstOnSuccessAndSecondTargetSucceeds_Write_ReturnToFirstTargetOnSuccess() { using (new NoThrowNLogExceptions()) { var myTarget1 = new MyTarget { FailCounter = 1 }; var myTarget2 = new MyTarget(); var myTarget3 = new MyTarget(); var wrapper = CreateAndInitializeFallbackGroupTarget(true, myTarget1, myTarget2, myTarget3); WriteAndAssertNoExceptions(wrapper); Assert.Equal(10, myTarget1.WriteCount); Assert.Equal(1, myTarget2.WriteCount); Assert.Equal(0, myTarget3.WriteCount); AssertNoFlushException(wrapper); } } [Fact] public void FallbackGroupTargetSyncTest5() { using (new NoThrowNLogExceptions()) { // fail once var myTarget1 = new MyTarget { FailCounter = 3 }; var myTarget2 = new MyTarget { FailCounter = 3 }; var myTarget3 = new MyTarget { FailCounter = 3 }; var wrapper = CreateAndInitializeFallbackGroupTarget(true, myTarget1, myTarget2, myTarget3); var exceptions = new List<Exception>(); // no exceptions for (var i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.Equal(10, exceptions.Count); for (var i = 0; i < 10; ++i) { if (i < 3) { Assert.NotNull(exceptions[i]); } else { Assert.Null(exceptions[i]); } } Assert.Equal(10, myTarget1.WriteCount); Assert.Equal(3, myTarget2.WriteCount); Assert.Equal(3, myTarget3.WriteCount); AssertNoFlushException(wrapper); } } [Fact] public void FallbackGroupTargetSyncTest6() { using (new NoThrowNLogExceptions()) { // fail once var myTarget1 = new MyTarget { FailCounter = 10 }; var myTarget2 = new MyTarget { FailCounter = 3 }; var myTarget3 = new MyTarget { FailCounter = 3 }; var wrapper = CreateAndInitializeFallbackGroupTarget(true, myTarget1, myTarget2, myTarget3); var exceptions = new List<Exception>(); // no exceptions for (var i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.Equal(10, exceptions.Count); for (var i = 0; i < 10; ++i) { if (i < 3) { // for the first 3 rounds, no target is available Assert.NotNull(exceptions[i]); Assert.IsType<ApplicationException>(exceptions[i]); Assert.Equal("Some failure.", exceptions[i].Message); } else { Assert.Null(exceptions[i]); } } Assert.Equal(10, myTarget1.WriteCount); Assert.Equal(10, myTarget2.WriteCount); Assert.Equal(3, myTarget3.WriteCount); AssertNoFlushException(wrapper); Assert.Equal(1, myTarget1.FlushCount); Assert.Equal(1, myTarget2.FlushCount); Assert.Equal(1, myTarget3.FlushCount); } } [Fact] public void FallbackGroupWithBufferingTargets_ReturnToFirstOnSuccess() { FallbackGroupWithBufferingTargets(true); } [Fact] public void FallbackGroupWithBufferingTargets_DoNotReturnToFirstOnSuccess() { FallbackGroupWithBufferingTargets(false); } private static void FallbackGroupWithBufferingTargets(bool returnToFirstOnSuccess) { using (new NoThrowNLogExceptions()) { const int totalEvents = 1000; var myTarget1 = new MyTarget { FailCounter = int.MaxValue }; // Always failing. var myTarget2 = new MyTarget(); var myTarget3 = new MyTarget(); var buffer1 = new BufferingTargetWrapper() { WrappedTarget = myTarget1, FlushTimeout = 100, SlidingTimeout = false }; var buffer2 = new BufferingTargetWrapper() { WrappedTarget = myTarget2, FlushTimeout = 100, SlidingTimeout = false }; var buffer3 = new BufferingTargetWrapper() { WrappedTarget = myTarget3, FlushTimeout = 100, SlidingTimeout = false }; var wrapper = CreateAndInitializeFallbackGroupTarget(returnToFirstOnSuccess, buffer1, buffer2, buffer3); var allEventsDone = new ManualResetEvent(false); var exceptions = new List<Exception>(); for (var i = 0; i < totalEvents; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { lock (exceptions) { exceptions.Add(ex); if (exceptions.Count >= totalEvents) allEventsDone.Set(); } })); } allEventsDone.WaitOne(5000); // Wait for all events to be delivered. Assert.True(totalEvents >= myTarget1.WriteCount, // Check events weren't delivered twice to myTarget1, "Target 1 received " + myTarget1.WriteCount + " writes although only " + totalEvents + " events were written"); Assert.Equal(totalEvents, myTarget2.WriteCount); // were all delivered exactly once to myTarget2, Assert.Equal(0, myTarget3.WriteCount); // with nothing delivered to myTarget3. Assert.Equal(totalEvents, exceptions.Count); foreach (var e in exceptions) { Assert.Null(e); // All events should have succeeded on myTarget2. } } } [Fact] public void FallbackGroupTargetAsyncTest() { using (new NoThrowNLogExceptions()) { var myTarget1 = new MyTarget { FailCounter = int.MaxValue }; // Always failing. var myTarget1Async = new AsyncTargetWrapper(myTarget1) { TimeToSleepBetweenBatches = 0 }; // Always failing. var myTarget2 = new MyTarget() { Layout = "${ndlc}" }; var wrapper = CreateAndInitializeFallbackGroupTarget(true, myTarget1Async, myTarget2); var exceptions = new List<Exception>(); // no exceptions for (var i = 0; i < 10; ++i) { using (ScopeContext.PushNestedState("Hello World")) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } } ManualResetEvent resetEvent = new ManualResetEvent(false); myTarget1Async.Flush((ex) => { Assert.Null(ex); resetEvent.Set(); }); resetEvent.WaitOne(1000); Assert.Equal(10, exceptions.Count); for (var i = 0; i < 10; ++i) { Assert.Null(exceptions[i]); } Assert.Equal(10, myTarget2.WriteCount); AssertNoFlushException(wrapper); } } private static FallbackGroupTarget CreateAndInitializeFallbackGroupTarget(bool returnToFirstOnSuccess, params Target[] targets) { var wrapper = new FallbackGroupTarget(targets) { ReturnToFirstOnSuccess = returnToFirstOnSuccess, }; foreach (var target in targets) { WrapperTargetBase wrapperTarget = target as WrapperTargetBase; if (wrapperTarget != null) wrapperTarget.WrappedTarget.Initialize(null); target.Initialize(null); } wrapper.Initialize(null); return wrapper; } private static void WriteAndAssertNoExceptions(FallbackGroupTarget wrapper) { var exceptions = new List<Exception>(); for (var i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.Equal(10, exceptions.Count); foreach (var e in exceptions) { Assert.Null(e); } } private static void AssertNoFlushException(FallbackGroupTarget wrapper) { Exception flushException = null; var flushHit = new ManualResetEvent(false); wrapper.Flush(ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); if (flushException != null) Assert.True(false, flushException.ToString()); } private class MyTarget : TargetWithLayout { public int FlushCount { get; set; } public int WriteCount { get; set; } public int FailCounter { get; set; } protected override void Write(LogEventInfo logEvent) { if (Layout != null && string.IsNullOrEmpty(Layout.Render(logEvent))) { throw new ApplicationException("Empty LogEvent."); } Assert.True(FlushCount <= WriteCount); WriteCount++; if (FailCounter > 0) { FailCounter--; throw new ApplicationException("Some failure."); } } protected override void FlushAsync(AsyncContinuation asyncContinuation) { FlushCount++; asyncContinuation(null); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Config { using System; using System.Text; using JetBrains.Annotations; using NLog.Config; using NLog.Internal; using NLog.Targets; using Xunit; public class ServiceRepositoryTests : NLogTestBase { [Fact] public void SideBySideLogFactoryExternalInterfaceTest() { // Arrange var logFactory1 = new LogFactory(); const string name1 = "name1"; logFactory1.ServiceRepository.RegisterService(typeof(IMyPrettyInterface), new MyPrettyImplementation() { Test = name1 }); var logFactory2 = new LogFactory(); const string name2 = "name2"; logFactory2.ServiceRepository.RegisterService(typeof(IMyPrettyInterface), new MyPrettyImplementation { Test = name2 }); // Act var logFactoryService1 = logFactory1.ServiceRepository.ResolveService<IMyPrettyInterface>(); var logFactoryService2 = logFactory2.ServiceRepository.ResolveService<IMyPrettyInterface>(); // Assert Assert.Equal(name1, logFactoryService1.ToString()); Assert.Equal(name2, logFactoryService2.ToString()); } [Fact] public void SideBySideLogFactoryInternalInterfaceTest() { // Arrange var logFactory1 = new LogFactory(); const string name1 = "name1"; InitializeLogFactoryJsonConverter(logFactory1, name1, out var logger1, out var target1); var logFactory2 = new LogFactory(); const string name2 = "name2"; InitializeLogFactoryJsonConverter(logFactory2, name2, out var logger2, out var target2); // Act logger1.Info("Hello {user}", "Kenny"); logger2.Info("Hello {user}", "Kenny"); // Assert Assert.Equal("Kenny" + "_" + name1, target1.LastMessage); Assert.Equal("Kenny" + "_" + name2, target2.LastMessage); } [Fact] public void ResolveShouldInjectDependencies() { // Arrange var logFactory = new LogFactory(); // Act var target = logFactory.ServiceRepository.ResolveService<TargetWithInjection>(); // Assert Assert.NotNull(target.JsonConverter); } [Fact] public void ResolveShouldInjectNestedDependencies() { // Arrange var logFactory = new LogFactory(); // Act var target = logFactory.ServiceRepository.ResolveService<TargetWithNestedInjection>(); // Assert Assert.NotNull(target.Helper.JsonConverter); } [Fact] public void ResolveWithDirectCycleShouldThrow() { // Arrange var logFactory = new LogFactory(); // Act & Assert AssertCycleException<TargetWithDirectCycleInjection>(logFactory); } [Fact] public void ResolveWithIndirectCycleShouldThrow() { // Arrange var logFactory = new LogFactory(); // Act & Assert AssertCycleException<TargetWithIndirectCycleInjection>(logFactory); } [Fact] public void HandleDelayedInjectDependenciesFailure() { using (new NoThrowNLogExceptions()) { // Arrange var logFactory = new LogFactory(); logFactory.ThrowConfigExceptions = true; var logConfig = new LoggingConfiguration(logFactory); var logTarget = new TargetWithMissingDependency() { Name = "NeedDependency" }; logConfig.AddRuleForAllLevels(logTarget); // Act logFactory.Configuration = logConfig; logFactory.GetLogger("Test").Info("Test"); // Assert Assert.Null(logTarget.LastLogEvent); } } [Fact] public void HandleDelayedInjectDependenciesSuccess() { using (new NoThrowNLogExceptions()) { // Arrange var logFactory = new LogFactory(); logFactory.ThrowConfigExceptions = true; var logConfig = new LoggingConfiguration(logFactory); var logTarget = new TargetWithMissingDependency() { Name = "NeedDependency" }; logConfig.AddRuleForAllLevels(logTarget); // Act logFactory.Configuration = logConfig; logFactory.GetLogger("Test").Info("Test"); logFactory.ServiceRepository.RegisterSingleton<IMisingDependencyClass>(new MisingDependencyClass()); logFactory.GetLogger("Test").Info("Test Again"); // Assert Assert.NotNull(logTarget.LastLogEvent); } } [Fact] public void HandleLayoutRendererDependency() { // Arrange var logFactory = new LogFactory().Setup().SetupExtensions(ext => { ext.RegisterLayoutRenderer<LayoutRendererUsingDependency>(); ext.RegisterServiceProvider(new ExternalServiceRepository(t => t == typeof(IMisingDependencyClass) ? new MisingDependencyClass() : null)); }).LoadConfiguration(builder => { builder.ForLogger().WriteTo(new MemoryTarget() { Layout = "${NeedDependency}" }); }).LogFactory; // Act logFactory.GetLogger("Test").Info("Test"); // Assert Assert.Equal("Success", (logFactory.Configuration.AllTargets[0] as MemoryTarget).Logs[0]); } [Fact] public void ResolveShouldCheckExternalServiceProvider() { // Arrange var logFactory = new LogFactory().Setup().SetupExtensions(ext => { ext.RegisterSingletonService<IMyPrettyInterface>(new MyPrettyImplementation()); ext.RegisterSingletonService(typeof(IMyPrettyInterface), new MyPrettyImplementation()); ext.RegisterServiceProvider(new ExternalServiceRepository(t => t == typeof(IMisingDependencyClass) ? new MisingDependencyClass() : null)); }).LogFactory; // Act var missingDependency = logFactory.ServiceRepository.ResolveService<IMisingDependencyClass>(false); var otherDependency = logFactory.ServiceRepository.ResolveService<IMyPrettyInterface>(false); // Assert Assert.NotNull(missingDependency); Assert.NotNull(otherDependency); } private static void AssertCycleException<T>(LogFactory logFactory) where T : class { var ex = Assert.Throws<NLogDependencyResolveException>(() => logFactory.ServiceRepository.ResolveService<T>()); Assert.Contains("cycle", ex.Message, StringComparison.OrdinalIgnoreCase); Assert.Equal(typeof(T), ex.ServiceType); } private static void InitializeLogFactoryJsonConverter(LogFactory logFactory, string testValue, out Logger logger, out DebugTarget target) { logFactory.ServiceRepository.RegisterService(typeof(IJsonConverter), new MySimpleJsonConverter { Test = testValue }); var xmlConfig = @"<nlog><targets><target type='debug' name='test' layout='${event-properties:user:format=@}'/></targets><rules><logger name='*' minLevel='Debug' writeTo='test'/></rules></nlog>"; logFactory.Configuration = XmlLoggingConfiguration.CreateFromXmlString(xmlConfig, logFactory); logger = logFactory.GetLogger(nameof(logFactory)); target = logFactory.Configuration.FindTargetByName("test") as DebugTarget; } private interface IMyPrettyInterface { string Test { get; } } private class MyPrettyImplementation : IMyPrettyInterface { public string Test { get; set; } public override string ToString() { return Test; } } private class MySimpleJsonConverter : IJsonConverter { public string Test { get; set; } public bool SerializeObject(object value, StringBuilder builder) { builder.Append(string.Concat(value.ToString(), "_", Test)); return true; } } private class TargetWithInjection : Target { public TargetWithInjection([NotNull] IJsonConverter jsonConverter) { JsonConverter = Guard.ThrowIfNull(jsonConverter); } public IJsonConverter JsonConverter { get; } } private class TargetWithNestedInjection : Target { public ClassWithInjection Helper { get; } /// <inheritdoc/> public TargetWithNestedInjection([NotNull] ClassWithInjection helper) { Helper = Guard.ThrowIfNull(helper); } } private class TargetWithDirectCycleInjection : Target { /// <inheritdoc/> public TargetWithDirectCycleInjection(TargetWithDirectCycleInjection cycle1) { } } private class TargetWithIndirectCycleInjection : Target { /// <inheritdoc/> public TargetWithIndirectCycleInjection(CycleHelperClass1 helper) { } } private class CycleHelperClass1 { /// <inheritdoc/> public CycleHelperClass1(CycleHelperClass2 helper) { } } private class CycleHelperClass2 { /// <inheritdoc/> public CycleHelperClass2(CycleHelperClass1 helper) { } } private class ClassWithInjection { public IJsonConverter JsonConverter { get; } /// <inheritdoc/> public ClassWithInjection(IJsonConverter jsonConverter) { JsonConverter = jsonConverter; } } private class TargetWithMissingDependency : Target { public LogEventInfo LastLogEvent { get; private set; } protected override void InitializeTarget() { var wantedDependency = ResolveService<IMisingDependencyClass>(); base.InitializeTarget(); } protected override void Write(LogEventInfo logEvent) { LastLogEvent = logEvent; } } [NLog.LayoutRenderers.LayoutRenderer("needdependency")] private class LayoutRendererUsingDependency : NLog.LayoutRenderers.LayoutRenderer { private object _wantedDependency; protected override void InitializeLayoutRenderer() { _wantedDependency = ResolveService<IMisingDependencyClass>(); base.InitializeLayoutRenderer(); } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(_wantedDependency != null ? "Success" : "Failed"); } } private interface IMisingDependencyClass { } private class MisingDependencyClass : IMisingDependencyClass { } private class ExternalServiceRepository : IServiceProvider { private readonly Func<Type, object> _serviceResolver; public ExternalServiceRepository(Func<Type, object> serviceResolver) { _serviceResolver = serviceResolver; } public object GetService(Type serviceType) { return _serviceResolver(serviceType); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Internal { using System; using System.Linq; using System.Collections.Generic; using NLog.Internal; using Xunit; public class SortHelpersTests { [Fact] public void SingleBucketDictionary_NoBucketTest() { SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>> dict = new SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>>(); Assert.Empty(dict); Assert.Empty(dict); Assert.Equal(0, dict.Count(val => val.Key == "Bucket1")); foreach (var _ in dict) Assert.False(true); Assert.Equal(0, dict.Keys.Count); foreach (var _ in dict.Keys) Assert.False(true); Assert.Equal(0, dict.Values.Count); foreach (var _ in dict.Values) Assert.False(true); IList<string> bucket; Assert.False(dict.TryGetValue("Bucket1", out bucket) || bucket != null); Assert.False(dict.TryGetValue(string.Empty, out bucket) || bucket != null); Assert.False(dict.TryGetValue(null, out bucket) || bucket != null); Assert.Throws<NotSupportedException>(() => dict[string.Empty] = ArrayHelper.Empty<string>()); } [Fact] public void SingleBucketDictionary_OneBucketEmptyTest() { IList<string> bucket = ArrayHelper.Empty<string>(); SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>> dict = new SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>>(new KeyValuePair<string, IList<string>>("Bucket1", bucket)); Assert.Single(dict); Assert.Contains(new KeyValuePair<string, IList<string>>("Bucket1", bucket), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>("Bucket1", null), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>(string.Empty, bucket), dict); Assert.True(dict.ContainsKey("Bucket1")); Assert.False(dict.ContainsKey(string.Empty)); KeyValuePair<string, IList<string>>[] copyToResult = new KeyValuePair<string, IList<string>>[10]; dict.CopyTo(copyToResult, 0); Assert.Equal("Bucket1", copyToResult[0].Key); Assert.Equal(0, copyToResult[0].Value.Count); Assert.Single(dict); Assert.Equal(1, dict.Count(val => val.Key == "Bucket1")); foreach (var item in dict) { Assert.Equal("Bucket1", item.Key); Assert.Equal(0, item.Value.Count); } Assert.Equal(1, dict.Keys.Count); foreach (var key in dict.Keys) { Assert.Equal("Bucket1", key); } Assert.Equal(1, dict.Values.Count); foreach (var val in dict.Values) { Assert.Equal(0, val.Count); } Assert.Equal(0, dict["Bucket1"].Count); Assert.True(dict.TryGetValue("Bucket1", out bucket) && bucket.Count == 0); Assert.False(dict.TryGetValue(string.Empty, out bucket) || bucket != null); Assert.False(dict.TryGetValue(null, out bucket) || bucket != null); Assert.Throws<NotSupportedException>(() => dict[string.Empty] = ArrayHelper.Empty<string>()); } [Fact] public void SingleBucketDictionary_OneBucketOneItem() { IList<string> bucket = new string[] { "Bucket1Item1" }; SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>> dict = new SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>>(new KeyValuePair<string, IList<string>>("Bucket1", bucket)); Assert.Single(dict); Assert.Contains(new KeyValuePair<string, IList<string>>("Bucket1", bucket), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>("Bucket1", null), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>(string.Empty, bucket), dict); Assert.True(dict.ContainsKey("Bucket1")); Assert.False(dict.ContainsKey(string.Empty)); KeyValuePair<string, IList<string>>[] copyToResult = new KeyValuePair<string, IList<string>>[10]; dict.CopyTo(copyToResult, 0); Assert.Equal("Bucket1", copyToResult[0].Key); Assert.Equal(1, copyToResult[0].Value.Count); Assert.Equal("Bucket1Item1", copyToResult[0].Value[0]); Assert.Single(dict); Assert.Equal(1, dict.Count(val => val.Key == "Bucket1")); foreach (var item in dict) { Assert.Equal("Bucket1", item.Key); Assert.Equal(1, item.Value.Count); Assert.Equal("Bucket1Item1", item.Value[0]); } Assert.Equal(1, dict.Keys.Count); foreach (var key in dict.Keys) { Assert.Equal("Bucket1", key); } Assert.Equal(1, dict.Values.Count); foreach (var val in dict.Values) { Assert.Equal(1, val.Count); Assert.Equal("Bucket1Item1", val[0]); } Assert.Equal(1, dict["Bucket1"].Count); Assert.True(dict.TryGetValue("Bucket1", out bucket) && bucket.Count == 1); Assert.False(dict.TryGetValue(string.Empty, out bucket) || bucket != null); Assert.False(dict.TryGetValue(null, out bucket) || bucket != null); Assert.Throws<NotSupportedException>(() => dict[string.Empty] = ArrayHelper.Empty<string>()); } [Fact] public void SingleBucketDictionary_OneBucketTwoItemsTest() { IList<string> bucket = new string[] { "Bucket1Item1", "Bucket1Item2" }; SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>> dict = new SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>>(new KeyValuePair<string, IList<string>>("Bucket1", bucket)); Assert.Single(dict); Assert.Contains(new KeyValuePair<string, IList<string>>("Bucket1", bucket), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>("Bucket1", null), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>(string.Empty, bucket), dict); Assert.True(dict.ContainsKey("Bucket1")); Assert.False(dict.ContainsKey(string.Empty)); KeyValuePair<string, IList<string>>[] copyToResult = new KeyValuePair<string, IList<string>>[10]; dict.CopyTo(copyToResult, 0); Assert.Equal("Bucket1", copyToResult[0].Key); Assert.Equal(2, copyToResult[0].Value.Count); Assert.Equal("Bucket1Item1", copyToResult[0].Value[0]); Assert.Equal("Bucket1Item2", copyToResult[0].Value[1]); Assert.Single(dict); Assert.Equal(1, dict.Count(val => val.Key == "Bucket1")); foreach (var item in dict) { Assert.Equal("Bucket1", item.Key); Assert.Equal(2, item.Value.Count); Assert.Equal("Bucket1Item1", item.Value[0]); Assert.Equal("Bucket1Item2", item.Value[1]); } Assert.Equal(1, dict.Keys.Count); foreach (var key in dict.Keys) { Assert.Equal("Bucket1", key); } Assert.Equal(1, dict.Values.Count); foreach (var val in dict.Values) { Assert.Equal(2, val.Count); Assert.Equal("Bucket1Item1", val[0]); Assert.Equal("Bucket1Item2", val[1]); } Assert.Equal(2, dict["Bucket1"].Count); Assert.True(dict.TryGetValue("Bucket1", out bucket) && bucket.Count == 2); Assert.False(dict.TryGetValue(string.Empty, out bucket) || bucket != null); Assert.False(dict.TryGetValue(null, out bucket) || bucket != null); Assert.Throws<NotSupportedException>(() => dict[string.Empty] = ArrayHelper.Empty<string>()); } [Fact] public void SingleBucketDictionary_TwoBucketEmptyTest() { IList<string> bucket1 = ArrayHelper.Empty<string>(); IList<string> bucket2 = ArrayHelper.Empty<string>(); Dictionary<string, IList<string>> buckets = new Dictionary<string, IList<string>>(); buckets["Bucket1"] = bucket1; buckets["Bucket2"] = bucket2; SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>> dict = new SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>>(buckets); Assert.Equal(2, dict.Count); Assert.Contains(new KeyValuePair<string, IList<string>>("Bucket1", bucket1), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>("Bucket1", null), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>(string.Empty, bucket1), dict); Assert.Contains(new KeyValuePair<string, IList<string>>("Bucket2", bucket2), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>("Bucket2", null), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>(string.Empty, bucket2), dict); Assert.True(dict.ContainsKey("Bucket1")); Assert.True(dict.ContainsKey("Bucket2")); Assert.False(dict.ContainsKey(string.Empty)); KeyValuePair<string, IList<string>>[] copyToResult = new KeyValuePair<string, IList<string>>[10]; dict.CopyTo(copyToResult, 0); Assert.Equal("Bucket1", copyToResult[0].Key); Assert.Equal("Bucket2", copyToResult[1].Key); Assert.Equal(0, copyToResult[0].Value.Count); Assert.Equal(0, copyToResult[1].Value.Count); Assert.Equal(2, dict.Count()); Assert.Equal(1, dict.Count(val => val.Key == "Bucket1")); Assert.Equal(1, dict.Count(val => val.Key == "Bucket2")); foreach (var item in dict) { Assert.True(item.Key == "Bucket1" || item.Key == "Bucket2"); Assert.Equal(0, item.Value.Count); } Assert.Equal(2, dict.Keys.Count); foreach (var key in dict.Keys) { Assert.True(key == "Bucket1" || key == "Bucket2"); } Assert.Equal(2, dict.Values.Count); foreach (var val in dict.Values) { Assert.Equal(0, val.Count); } Assert.Equal(0, dict["Bucket1"].Count); Assert.Equal(0, dict["Bucket2"].Count); Assert.True(dict.TryGetValue("Bucket1", out bucket1) && bucket1.Count == 0); Assert.True(dict.TryGetValue("Bucket2", out bucket2) && bucket2.Count == 0); Assert.Throws<NotSupportedException>(() => dict[string.Empty] = ArrayHelper.Empty<string>()); } [Fact] public void SingleBucketDictionary_TwoBuckettOneItemTest() { IList<string> bucket1 = new string[] { "Bucket1Item1" }; IList<string> bucket2 = new string[] { "Bucket1Item1" }; Dictionary<string, IList<string>> buckets = new Dictionary<string, IList<string>>(); buckets["Bucket1"] = bucket1; buckets["Bucket2"] = bucket2; SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>> dict = new SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>>(buckets); Assert.Equal(2, dict.Count); Assert.Contains(new KeyValuePair<string, IList<string>>("Bucket1", bucket1), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>("Bucket1", null), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>(string.Empty, bucket1), dict); Assert.Contains(new KeyValuePair<string, IList<string>>("Bucket2", bucket2), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>("Bucket2", null), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>(string.Empty, bucket2), dict); Assert.True(dict.ContainsKey("Bucket1")); Assert.True(dict.ContainsKey("Bucket2")); Assert.False(dict.ContainsKey(string.Empty)); KeyValuePair<string, IList<string>>[] copyToResult = new KeyValuePair<string, IList<string>>[10]; dict.CopyTo(copyToResult, 0); Assert.Equal("Bucket1", copyToResult[0].Key); Assert.Equal("Bucket2", copyToResult[1].Key); Assert.Equal(1, copyToResult[0].Value.Count); Assert.Equal(1, copyToResult[1].Value.Count); Assert.Equal(2, dict.Count()); Assert.Equal(1, dict.Count(val => val.Key == "Bucket1")); Assert.Equal(1, dict.Count(val => val.Key == "Bucket2")); foreach (var item in dict) { Assert.True(item.Key == "Bucket1" || item.Key == "Bucket2"); Assert.Equal(1, item.Value.Count); Assert.Equal("Bucket1Item1", item.Value[0]); } Assert.Equal(2, dict.Keys.Count); foreach (var key in dict.Keys) { Assert.True(key == "Bucket1" || key == "Bucket2"); } Assert.Equal(2, dict.Values.Count); foreach (var val in dict.Values) { Assert.Equal(1, val.Count); Assert.Equal("Bucket1Item1", val[0]); } Assert.Equal(1, dict["Bucket1"].Count); Assert.Equal(1, dict["Bucket2"].Count); Assert.True(dict.TryGetValue("Bucket1", out bucket1) && bucket1.Count == 1); Assert.True(dict.TryGetValue("Bucket2", out bucket2) && bucket2.Count == 1); Assert.Throws<NotSupportedException>(() => dict[string.Empty] = ArrayHelper.Empty<string>()); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Globalization; using System.Text; using System.Xml; /// <summary> /// Helper class for XML /// </summary> internal static class XmlHelper { // found on https://stackoverflow.com/questions/397250/unicode-regex-invalid-xml-characters/961504#961504 // filters control characters but allows only properly-formed surrogate sequences #if NET35 || NETSTANDARD1_3 || NETSTANDARD1_5 private static readonly System.Text.RegularExpressions.Regex InvalidXmlChars = new System.Text.RegularExpressions.Regex( @"(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\uFEFF\uFFFE\uFFFF]", System.Text.RegularExpressions.RegexOptions.Compiled); #endif /// <summary> /// removes any unusual unicode characters that can't be encoded into XML /// </summary> private static string RemoveInvalidXmlChars(string text) { if (string.IsNullOrEmpty(text)) return string.Empty; #if !NET35 && !NETSTANDARD1_3 && !NETSTANDARD1_5 int length = text.Length; for (int i = 0; i < length; ++i) { char ch = text[i]; if (!XmlConvert.IsXmlChar(ch)) { if (i + 1 < text.Length && XmlConvert.IsXmlSurrogatePair(text[i + 1], ch)) { ++i; } else { return CreateValidXmlString(text); // rare expensive case } } } return text; #else return InvalidXmlChars.Replace(text, ""); #endif } #if !NET35 && !NETSTANDARD1_3 && !NETSTANDARD1_5 /// <summary> /// Cleans string of any invalid XML chars found /// </summary> /// <param name="text">unclean string</param> /// <returns>string with only valid XML chars</returns> private static string CreateValidXmlString(string text) { var sb = new StringBuilder(text.Length); for (int i = 0; i < text.Length; ++i) { char ch = text[i]; if (XmlConvert.IsXmlChar(ch)) { sb.Append(ch); } } return sb.ToString(); } #endif internal static void PerformXmlEscapeWhenNeeded(StringBuilder builder, int startPos, bool xmlEncodeNewlines) { if (RequiresXmlEscape(builder, startPos, xmlEncodeNewlines)) { var str = builder.ToString(startPos, builder.Length - startPos); builder.Length = startPos; EscapeXmlString(str, xmlEncodeNewlines, builder); } } private static bool RequiresXmlEscape(StringBuilder target, int startPos, bool xmlEncodeNewlines) { for (int i = startPos; i < target.Length; ++i) { switch (target[i]) { case '<': case '>': case '&': case '\'': case '"': return true; case '\r': case '\n': if (xmlEncodeNewlines) return true; break; } } return false; } private static readonly char[] XmlEscapeChars = new char[] { '<', '>', '&', '\'', '"' }; private static readonly char[] XmlEscapeNewlineChars = new char[] { '<', '>', '&', '\'', '"', '\r', '\n' }; internal static string EscapeXmlString(string text, bool xmlEncodeNewlines, StringBuilder result = null) { if (result is null && SmallAndNoEscapeNeeded(text, xmlEncodeNewlines)) { return text; } var sb = result ?? new StringBuilder(text.Length); for (int i = 0; i < text.Length; ++i) { switch (text[i]) { case '<': sb.Append("&lt;"); break; case '>': sb.Append("&gt;"); break; case '&': sb.Append("&amp;"); break; case '\'': sb.Append("&apos;"); break; case '"': sb.Append("&quot;"); break; case '\r': if (xmlEncodeNewlines) sb.Append("&#13;"); else sb.Append(text[i]); break; case '\n': if (xmlEncodeNewlines) sb.Append("&#10;"); else sb.Append(text[i]); break; default: sb.Append(text[i]); break; } } return result is null ? sb.ToString() : null; } /// <summary> /// Pretest, small text and not escape needed /// </summary> /// <param name="text"></param> /// <param name="xmlEncodeNewlines"></param> /// <returns></returns> private static bool SmallAndNoEscapeNeeded(string text, bool xmlEncodeNewlines) { return text.Length < 4096 && text.IndexOfAny(xmlEncodeNewlines ? XmlEscapeNewlineChars : XmlEscapeChars) < 0; } /// <summary> /// Converts object value to invariant format, and strips any invalid xml-characters /// </summary> /// <param name="value">Object value</param> /// <returns>Object value converted to string</returns> internal static string XmlConvertToStringSafe(object value) { return XmlConvertToString(value, true); } /// <summary> /// Converts object value to invariant format (understood by JavaScript) /// </summary> /// <param name="value">Object value</param> /// <returns>Object value converted to string</returns> internal static string XmlConvertToString(object value) { return XmlConvertToString(value, false); } internal static string XmlConvertToString(float value) { if (float.IsNaN(value)) return XmlConvert.ToString(value); if (float.IsInfinity(value)) return Convert.ToString(value, CultureInfo.InvariantCulture); return EnsureDecimalPlace(XmlConvert.ToString(value)); } internal static string XmlConvertToString(double value) { if (double.IsNaN(value)) return XmlConvert.ToString(value); if (double.IsInfinity(value)) return Convert.ToString(value, CultureInfo.InvariantCulture); return EnsureDecimalPlace(XmlConvert.ToString(value)); } internal static string XmlConvertToString(decimal value) { return EnsureDecimalPlace(XmlConvert.ToString(value)); } /// <summary> /// XML elements must follow these naming rules: /// - Element names are case-sensitive /// - Element names must start with a letter or underscore /// - Element names can contain letters, digits, hyphens, underscores, and periods /// - Element names cannot contain spaces /// </summary> /// <param name="xmlElementName"></param> internal static string XmlConvertToElementName(string xmlElementName) { if (string.IsNullOrEmpty(xmlElementName)) return xmlElementName; xmlElementName = RemoveInvalidXmlChars(xmlElementName); bool allowNamespace = true; StringBuilder sb = null; for (int i = 0; i < xmlElementName.Length; ++i) { char chr = xmlElementName[i]; if (char.IsLetter(chr)) { sb?.Append(chr); continue; } bool includeChr = false; switch (chr) { case ':': // namespace-delimiter if (i != 0 && allowNamespace) { allowNamespace = false; sb?.Append(chr); continue; } break; case '_': sb?.Append(chr); continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': case '.': { if (i != 0) { sb?.Append(chr); continue; } includeChr = true; break; } } if (sb is null) { sb = CreateStringBuilder(xmlElementName, i); } sb.Append('_'); if (includeChr) sb.Append(chr); } sb?.TrimRight(); return sb?.ToString() ?? xmlElementName; StringBuilder CreateStringBuilder(string orgValue, int i) { var sb2 = new StringBuilder(orgValue.Length); if (i > 0) sb2.Append(orgValue, 0, i); return sb2; } } private static string XmlConvertToString(object value, bool safeConversion) { try { var convertibleValue = value as IConvertible; var objTypeCode = convertibleValue?.GetTypeCode() ?? (value is null ? TypeCode.Empty : TypeCode.Object); if (objTypeCode != TypeCode.Object) { return XmlConvertToString(convertibleValue, objTypeCode, safeConversion); } return XmlConvertToStringInvariant(value, safeConversion); } catch { return safeConversion ? "" : null; } } private static string XmlConvertToStringInvariant(object value, bool safeConversion) { try { string valueString = Convert.ToString(value, CultureInfo.InvariantCulture); return safeConversion ? RemoveInvalidXmlChars(valueString) : valueString; } catch { return safeConversion ? "" : null; } } /// <summary> /// Converts object value to invariant format (understood by JavaScript) /// </summary> /// <param name="value">Object value</param> /// <param name="objTypeCode">Object TypeCode</param> /// <param name="safeConversion">Check and remove unusual unicode characters from the result string.</param> /// <returns>Object value converted to string</returns> internal static string XmlConvertToString(IConvertible value, TypeCode objTypeCode, bool safeConversion = false) { if (objTypeCode == TypeCode.Empty || value is null) { return "null"; } switch (objTypeCode) { case TypeCode.Boolean: return XmlConvert.ToString(value.ToBoolean(CultureInfo.InvariantCulture)); // boolean as lowercase case TypeCode.Byte: return XmlConvert.ToString(value.ToByte(CultureInfo.InvariantCulture)); case TypeCode.SByte: return XmlConvert.ToString(value.ToSByte(CultureInfo.InvariantCulture)); case TypeCode.Int16: return XmlConvert.ToString(value.ToInt16(CultureInfo.InvariantCulture)); case TypeCode.Int32: return XmlConvert.ToString(value.ToInt32(CultureInfo.InvariantCulture)); case TypeCode.Int64: return XmlConvert.ToString(value.ToInt64(CultureInfo.InvariantCulture)); case TypeCode.UInt16: return XmlConvert.ToString(value.ToUInt16(CultureInfo.InvariantCulture)); case TypeCode.UInt32: return XmlConvert.ToString(value.ToUInt32(CultureInfo.InvariantCulture)); case TypeCode.UInt64: return XmlConvert.ToString(value.ToUInt64(CultureInfo.InvariantCulture)); case TypeCode.Single: return XmlConvertToString(value.ToSingle(CultureInfo.InvariantCulture)); case TypeCode.Double: return XmlConvertToString(value.ToDouble(CultureInfo.InvariantCulture)); case TypeCode.Decimal: return XmlConvertToString(value.ToDecimal(CultureInfo.InvariantCulture)); case TypeCode.DateTime: return XmlConvert.ToString(value.ToDateTime(CultureInfo.InvariantCulture), XmlDateTimeSerializationMode.Utc); case TypeCode.Char: return XmlConvert.ToString(value.ToChar(CultureInfo.InvariantCulture)); case TypeCode.String: return safeConversion ? RemoveInvalidXmlChars(value.ToString(CultureInfo.InvariantCulture)) : value.ToString(CultureInfo.InvariantCulture); default: return XmlConvertToStringInvariant(value, safeConversion); } } /// <summary> /// Safe version of WriteAttributeString /// </summary> /// <param name="writer"></param> /// <param name="localName"></param> /// <param name="value"></param> public static void WriteAttributeSafeString(this XmlWriter writer, string localName, string value) { writer.WriteAttributeString(localName, RemoveInvalidXmlChars(value)); } /// <summary> /// Safe version of WriteElementSafeString /// </summary> /// <param name="writer"></param> /// <param name="prefix"></param> /// <param name="localName"></param> /// <param name="ns"></param> /// <param name="value"></param> public static void WriteElementSafeString(this XmlWriter writer, string prefix, string localName, string ns, string value) { writer.WriteElementString(prefix, localName, ns, RemoveInvalidXmlChars(value)); } /// <summary> /// Safe version of WriteCData /// </summary> /// <param name="writer"></param> /// <param name="value"></param> public static void WriteSafeCData(this XmlWriter writer, string value) { writer.WriteCData(RemoveInvalidXmlChars(value)); } private static string EnsureDecimalPlace(string text) { if (text.IndexOf('.') != -1 || text.IndexOfAny(DecimalScientificExponent) != -1) { return text; } else if (text.Length == 1) { switch (text[0]) { case '0': return "0.0"; case '1': return "1.0"; case '2': return "2.0"; case '3': return "3.0"; case '4': return "4.0"; case '5': return "5.0"; case '6': return "6.0"; case '7': return "7.0"; case '8': return "8.0"; case '9': return "9.0"; } } return text + ".0"; } private static readonly char[] DecimalScientificExponent = new[] { 'e', 'E' }; } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System.Collections; using System.Collections.Generic; using NLog.Config; using NLog.Targets; internal class SetupConfigurationLoggingRuleBuilder : ISetupConfigurationLoggingRuleBuilder, IList<Target> { public SetupConfigurationLoggingRuleBuilder(LogFactory logFactory, LoggingConfiguration configuration, string loggerNamePattern = null, string ruleName = null) { LoggingRule = new LoggingRule(ruleName) { LoggerNamePattern = loggerNamePattern ?? "*" }; Configuration = configuration; LogFactory = logFactory; } /// <inheritdoc/> public LoggingRule LoggingRule { get; } /// <inheritdoc/> public LoggingConfiguration Configuration { get; } /// <inheritdoc/> public LogFactory LogFactory { get; } /// <summary> /// Collection of targets that should be written to /// </summary> public IList<Target> Targets => this; Target IList<Target>.this[int index] { get => LoggingRule.Targets[index]; set => LoggingRule.Targets[index] = value; } int ICollection<Target>.Count => LoggingRule.Targets.Count; bool ICollection<Target>.IsReadOnly => LoggingRule.Targets.IsReadOnly; void ICollection<Target>.Add(Target item) { if (!Configuration.LoggingRules.Contains(LoggingRule)) { Configuration.LoggingRules.Add(LoggingRule); } LoggingRule.Targets.Add(item); } void ICollection<Target>.Clear() { LoggingRule.Targets.Clear(); } bool ICollection<Target>.Contains(Target item) { return LoggingRule.Targets.Contains(item); } void ICollection<Target>.CopyTo(Target[] array, int arrayIndex) { LoggingRule.Targets.CopyTo(array, arrayIndex); } IEnumerator<Target> IEnumerable<Target>.GetEnumerator() { return LoggingRule.Targets.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return LoggingRule.Targets.GetEnumerator(); } int IList<Target>.IndexOf(Target item) { return LoggingRule.Targets.IndexOf(item); } void IList<Target>.Insert(int index, Target item) { LoggingRule.Targets.Insert(index, item); } bool ICollection<Target>.Remove(Target item) { return LoggingRule.Targets.Remove(item); } void IList<Target>.RemoveAt(int index) { LoggingRule.Targets.RemoveAt(index); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Security.Authentication; using System.Text; using System.Threading; using NLog.Common; using NLog.Config; using NLog.Internal.NetworkSenders; using NLog.Targets; using Xunit; public class NetworkTargetTests : NLogTestBase { [Fact] public void HappyPathDefaultsTest() { HappyPathTest(null, "msg1", "msg2", "msg3"); } [Fact] public void HappyPathCRLFTest() { HappyPathTest(LineEndingMode.CRLF, "msg1", "msg2", "msg3"); } [Fact] public void HappyPathLFTest() { HappyPathTest(LineEndingMode.LF, "msg1", "msg2", "msg3"); } private static void HappyPathTest(LineEndingMode lineEnding, params string[] messages) { var senderFactory = new MyQueudSenderFactory(); var target = new NetworkTarget(); target.Address = "tcp://someaddress/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.LineEnding = lineEnding; target.KeepConnection = true; target.Initialize(null); var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 3; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "msg1").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "msg2").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "msg3").WithContinuation(asyncContinuation)); Assert.True(mre.WaitOne(10000), "Network Write not completed"); foreach (var ex in exceptions) { Assert.True(ex == null, $"Network Write Exception: {ex?.ToString()}"); } Assert.Single(senderFactory.Senders); var sender = senderFactory.Senders[0]; target.Close(); // Get the length of all the messages and their line endings var eol = lineEnding?.NewLineCharacters ?? string.Empty; var eolLength = eol.Length; var length = messages.Sum(m => m.Length) + (eolLength * messages.Length); Assert.Equal(length, sender.MemoryStream.Length); Assert.Equal(string.Join(eol, messages) + eol, target.Encoding.GetString(sender.MemoryStream.GetBuffer(), 0, (int)sender.MemoryStream.Length)); // we invoke the sender for each message, each time sending 4 bytes var actual = senderFactory.Log.ToString(); Assert.True(actual.IndexOf("1: connect tcp://someaddress/") != -1); foreach (var message in messages) { Assert.True(actual.IndexOf($"1: send 0 {message.Length + eolLength}") != -1); } Assert.True(actual.IndexOf("1: close") != -1); } [Fact] public void NetworkTargetDefaultsTest() { var target = new NetworkTarget(); Assert.True(target.KeepConnection); Assert.False(target.NewLine); Assert.Equal("\r\n", target.LineEnding.NewLineCharacters); Assert.Equal(65000, target.MaxMessageSize); Assert.Equal(5, target.ConnectionCacheSize); Assert.Equal(100, target.MaxConnections); Assert.Equal(10000, target.MaxQueueSize); Assert.Equal(Encoding.UTF8, target.Encoding); } [Fact] public void NetworkTargetMultipleConnectionsTest() { var senderFactory = new MyQueudSenderFactory(); var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.Initialize(null); var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 3; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg1").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg2").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger3", "msg3").WithContinuation(asyncContinuation)); Assert.True(mre.WaitOne(10000), "Network Write not completed"); foreach (var ex in exceptions) { Assert.True(ex == null, $"Network Write Exception: {ex?.ToString()}"); } mre.Reset(); AsyncContinuation flushContinuation = ex => { mre.Set(); }; target.Flush(flushContinuation); Assert.True(mre.WaitOne(10000), "Network Flush not completed"); target.Close(); var actual = senderFactory.Log.ToString(); Assert.True(actual.IndexOf("1: connect tcp://logger1.company.lan/") != -1); Assert.True(actual.IndexOf("1: send 0 4") != -1); Assert.True(actual.IndexOf("2: connect tcp://logger2.company.lan/") != -1); Assert.True(actual.IndexOf("2: send 0 4") != -1); Assert.True(actual.IndexOf("3: connect tcp://logger3.company.lan/") != -1); Assert.True(actual.IndexOf("3: send 0 4") != -1); Assert.True(actual.IndexOf("1: flush") != -1); Assert.True(actual.IndexOf("2: flush") != -1); Assert.True(actual.IndexOf("3: flush") != -1); Assert.True(actual.IndexOf("1: close") != -1); Assert.True(actual.IndexOf("2: close") != -1); Assert.True(actual.IndexOf("3: close") != -1); } [Fact] public void NothingToFlushTest() { var senderFactory = new MyQueudSenderFactory(); var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.Initialize(null); var mre = new ManualResetEvent(false); AsyncContinuation flushContinuation = ex => { mre.Set(); }; target.Flush(flushContinuation); Assert.True(mre.WaitOne(10000), "Network Flush not completed"); target.Close(); string expectedLog = @""; Assert.Equal(expectedLog, senderFactory.Log.ToString()); } [Fact] public void NetworkTargetMultipleConnectionsWithCacheOverflowTest() { var senderFactory = new MyQueudSenderFactory(); var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.ConnectionCacheSize = 2; target.Initialize(null); var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 6; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; // logger1 should be kept alive because it's being referenced frequently target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg1").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg2").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg3").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger3", "msg1").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg2").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg3").WithContinuation(asyncContinuation)); Assert.True(mre.WaitOne(10000), "Network Write not completed"); foreach (var ex in exceptions) { Assert.True(ex == null, $"Network Write Exception: {ex?.ToString()}"); } target.Close(); string result = senderFactory.Log.ToString(); Assert.True(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("1: send 0 4") != -1); Assert.True(result.IndexOf("2: connect tcp://logger2.company.lan/") != -1); Assert.True(result.IndexOf("2: send 0 4") != -1); Assert.True(result.IndexOf("1: send 0 4") != -1); Assert.True(result.IndexOf("2: close") != -1); Assert.True(result.IndexOf("3: connect tcp://logger3.company.lan/") != -1); Assert.True(result.IndexOf("3: send 0 4") != -1); Assert.True(result.IndexOf("1: send 0 4") != -1); Assert.True(result.IndexOf("3: close") != -1); Assert.True(result.IndexOf("4: connect tcp://logger2.company.lan/") != -1); Assert.True(result.IndexOf("4: send 0 4") != -1); Assert.True(result.IndexOf("1: close") != -1); Assert.True(result.IndexOf("4: close") != -1); } [Fact] public void NetworkTargetMultipleConnectionsWithoutKeepAliveTest() { var senderFactory = new MyQueudSenderFactory(); var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = false; target.Initialize(null); var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 6; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg1").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg2").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg3").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger3", "msg1").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg2").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg3").WithContinuation(asyncContinuation)); Assert.True(mre.WaitOne(10000), "Network Write not completed"); foreach (var ex in exceptions) { Assert.True(ex == null, $"Network Write Exception: {ex?.ToString()}"); } target.Close(); string result = senderFactory.Log.ToString(); Assert.True(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("1: send 0 4") != -1); Assert.True(result.IndexOf("1: close") != -1); Assert.True(result.IndexOf("2: connect tcp://logger2.company.lan/") != -1); Assert.True(result.IndexOf("2: send 0 4") != -1); Assert.True(result.IndexOf("2: close") != -1); Assert.True(result.IndexOf("3: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("3: send 0 4") != -1); Assert.True(result.IndexOf("3: close") != -1); Assert.True(result.IndexOf("4: connect tcp://logger3.company.lan/") != -1); Assert.True(result.IndexOf("4: send 0 4") != -1); Assert.True(result.IndexOf("4: close") != -1); Assert.True(result.IndexOf("5: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("5: send 0 4") != -1); Assert.True(result.IndexOf("5: close") != -1); Assert.True(result.IndexOf("6: connect tcp://logger2.company.lan/") != -1); Assert.True(result.IndexOf("6: send 0 4") != -1); Assert.True(result.IndexOf("6: close") != -1); } [Fact] public void NetworkTargetMultipleConnectionsWithMessageDiscardTest() { var senderFactory = new MyQueudSenderFactory(); var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.MaxMessageSize = 10; target.OnOverflow = NetworkTargetOverflowAction.Discard; target.Initialize(null); int droppedLogs = 0; target.LogEventDropped += (sender, args) => droppedLogs++; var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 3; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "012345678901234").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "01234").WithContinuation(asyncContinuation)); Assert.True(mre.WaitOne(10000), "Network Write not completed"); foreach (var ex in exceptions) { Assert.True(ex == null, $"Network Write Exception: {ex?.ToString()}"); } target.Close(); string result = senderFactory.Log.ToString(); Assert.True(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("1: send 0 7") != -1); Assert.True(result.IndexOf("2: connect tcp://logger2.company.lan/") != -1); Assert.True(result.IndexOf("2: send 0 5") != -1); Assert.True(result.IndexOf("1: close") != -1); Assert.True(result.IndexOf("2: close") != -1); Assert.Equal(1, droppedLogs); } [Fact] public void NetworkTargetMultipleConnectionsWithMessageErrorTest() { var senderFactory = new MyQueudSenderFactory() { AsyncMode = false, // Disable async, because unit-test cannot handle it }; var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.MaxMessageSize = 10; target.OnOverflow = NetworkTargetOverflowAction.Error; target.Initialize(null); int droppedLogs = 0; target.LogEventDropped += (sender, args) => droppedLogs++; var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 3; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "012345678901234").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "01234").WithContinuation(asyncContinuation)); Assert.True(mre.WaitOne(10000), "Network Write not completed"); Assert.Null(exceptions[0]); Assert.NotNull(exceptions[1]); Assert.Equal("NetworkTarget: Discarded LogEvent because MessageSize=15 is above MaxMessageSize=10", exceptions[1].Message); Assert.Null(exceptions[2]); target.Close(); string result = senderFactory.Log.ToString(); Assert.True(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("1: send 0 7") != -1); Assert.True(result.IndexOf("1: close") != -1); Assert.True(result.IndexOf("2: connect tcp://logger2.company.lan/") != -1); Assert.True(result.IndexOf("2: send 0 5") != -1); Assert.True(result.IndexOf("2: close") != -1); Assert.Equal(2, droppedLogs); } [Fact] public void NetworkTargetSendFailureTests() { var senderFactory = new MyQueudSenderFactory() { FailCounter = 3, // first 3 sends will fail AsyncMode = false, // Disable async, because unit-test cannot handle it }; var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.OnOverflow = NetworkTargetOverflowAction.Discard; int droppedLogsDueToSendFailure = 0; int droppedLogsOther = 0; target.LogEventDropped += (sender, args) => { if (args.Reason == NetworkLogEventDroppedReason.NetworkError) { droppedLogsDueToSendFailure++; } else { droppedLogsOther++; } }; target.Initialize(null); var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 5; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "01234").WithContinuation(asyncContinuation)); Assert.True(mre.WaitOne(10000), "Network Write not completed"); Assert.NotNull(exceptions[0]); Assert.NotNull(exceptions[1]); Assert.NotNull(exceptions[2]); Assert.Null(exceptions[3]); Assert.Null(exceptions[4]); target.Close(); var result = senderFactory.Log.ToString(); Assert.True(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("1: send 0 7") != -1); Assert.True(result.IndexOf("1: failed") != -1); Assert.True(result.IndexOf("1: close") != -1); Assert.True(result.IndexOf("2: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("2: send 0 7") != -1); Assert.True(result.IndexOf("2: failed") != -1); Assert.True(result.IndexOf("2: close") != -1); Assert.True(result.IndexOf("3: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("3: send 0 7") != -1); Assert.True(result.IndexOf("3: failed") != -1); Assert.True(result.IndexOf("3: close") != -1); Assert.True(result.IndexOf("4: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("4: send 0 7") != -1); Assert.True(result.IndexOf("4: send 0 5") != -1); Assert.True(result.IndexOf("4: close") != -1); Assert.Equal(3, droppedLogsDueToSendFailure); Assert.Equal(0, droppedLogsOther); } [Fact] public void NetworkTargetTcpTest() { var loopBackIP = Socket.OSSupportsIPv4 ? IPAddress.Loopback : IPAddress.IPv6Loopback; var tcpPrefix = loopBackIP.AddressFamily == AddressFamily.InterNetwork ? "tcp4" : "tcp6"; var tcpPort = getNewNetworkPort(); string expectedResult = string.Empty; using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var target = new NetworkTarget() { Address = $"{tcpPrefix}://{loopBackIP}:{tcpPort}", Layout = "${message}\n", KeepConnection = true, }) { Exception receiveException = null; var resultStream = new MemoryStream(); var receiveFinished = new ManualResetEvent(false); listener.Bind(new IPEndPoint(loopBackIP, tcpPort)); listener.Listen(10); listener.BeginAccept( result => { try { byte[] buffer = new byte[4096]; using (Socket connectedSocket = listener.EndAccept(result)) { int got; while ((got = connectedSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None)) > 0) { resultStream.Write(buffer, 0, got); } } } catch (Exception ex) { Console.WriteLine("Receive exception {0}", ex); receiveException = ex; } finally { receiveFinished.Set(); } }, null); target.Initialize(new LoggingConfiguration()); int pendingWrites = 100; var writeCompleted = new ManualResetEvent(false); var exceptions = new List<Exception>(); AsyncContinuation writeFinished = ex => { lock (exceptions) { exceptions.Add(ex); pendingWrites--; if (pendingWrites == 0) { writeCompleted.Set(); } } }; int toWrite = pendingWrites; for (int i = 0; i < toWrite; ++i) { var ev = new LogEventInfo(LogLevel.Info, "logger1", "messagemessagemessagemessagemessage" + i).WithContinuation(writeFinished); target.WriteAsyncLogEvent(ev); expectedResult += "messagemessagemessagemessagemessage" + i + "\n"; } Assert.True(writeCompleted.WaitOne(10000), "Network Writes did not complete"); target.Close(); foreach (var ex in exceptions) { Assert.True(ex == null, $"Network Write Exception: {ex?.ToString()}"); } Assert.True(receiveFinished.WaitOne(10000), "Network Receive did not complete"); Assert.True(receiveException == null, $"Network Receive Exception: {receiveException?.ToString()}"); string resultString = Encoding.UTF8.GetString(resultStream.GetBuffer(), 0, (int)resultStream.Length); Assert.Equal(expectedResult, resultString); } } [Fact] public void NetworkTargetUdpSplitEnabledTest() { RetryingIntegrationTest(3, () => NetworkTargetUdpTest(true)); } [Fact] public void NetworkTargetUdpSplitDisabledTest() { RetryingIntegrationTest(3, () => NetworkTargetUdpTest(false)); } private static int getNewNetworkPort() { return 9500 + System.Threading.Interlocked.Increment(ref _portOffset); } private static int _portOffset; private static void NetworkTargetUdpTest(bool splitMessage) { var loopBackIP = Socket.OSSupportsIPv4 ? IPAddress.Loopback : IPAddress.IPv6Loopback; var udpPrefix = loopBackIP.AddressFamily == AddressFamily.InterNetwork ? "udp4" : "udp6"; var udpPort = getNewNetworkPort(); string expectedResult = string.Empty; using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var target = new NetworkTarget() { Address = $"{udpPrefix}://{loopBackIP}:{udpPort}", Layout = "${message}\n", KeepConnection = true, MaxMessageSize = splitMessage ? 4 : short.MaxValue, }) { Exception receiveException = null; var receivedMessages = new List<string>(); var receiveFinished = new ManualResetEvent(false); byte[] receiveBuffer = new byte[4096]; listener.Bind(new IPEndPoint(loopBackIP, udpPort)); EndPoint remoteEndPoint = null; AsyncCallback receivedDatagram = null; const int toWrite = 50; int pendingWrites = toWrite; receivedDatagram = result => { try { int got = listener.EndReceiveFrom(result, ref remoteEndPoint); string message = Encoding.UTF8.GetString(receiveBuffer, 0, got); lock (receivedMessages) { if (splitMessage) { if (receivedMessages.Count > 0 && !receivedMessages[receivedMessages.Count - 1].Contains('\n')) { receivedMessages[receivedMessages.Count - 1] = receivedMessages[receivedMessages.Count - 1] + message; } else { receivedMessages.Add(message); } } else { receivedMessages.Add(message); } if (receivedMessages.Count == toWrite && receivedMessages[receivedMessages.Count - 1].Contains('\n')) { receiveFinished.Set(); } } remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null); } catch (Exception ex) { receiveException = ex; receiveFinished.Set(); } }; remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null); target.Initialize(new LoggingConfiguration()); var writeCompleted = new ManualResetEvent(false); var exceptions = new List<Exception>(); AsyncContinuation writeFinished = ex => { lock (exceptions) { exceptions.Add(ex); pendingWrites--; if (pendingWrites == 0) { writeCompleted.Set(); } } }; for (int i = 0; i < toWrite; ++i) { var ev = new LogEventInfo(LogLevel.Info, "logger1", "message" + i).WithContinuation(writeFinished); target.WriteAsyncLogEvent(ev); expectedResult += "message" + i + "\n"; } Assert.True(writeCompleted.WaitOne(10000), "Network Write not completed"); target.Close(); foreach (var ex in exceptions) { Assert.True(ex == null, $"Network Write Exception: {ex?.ToString()}"); } Assert.True(receiveFinished.WaitOne(10000), $"Network Receive not completed. Count={receivedMessages.Count}, LastMsg={receivedMessages.LastOrDefault()}"); Assert.True(receiveException == null, $"Network Receive Exception: {receiveException?.ToString()}"); Assert.Equal(toWrite, receivedMessages.Count); for (int i = 0; i < toWrite; ++i) { Assert.Equal(receivedMessages[i], $"message{i}\n"); } } } [Fact] public void NetworkTargetNotConnectedTest() { var target = new NetworkTarget() { Address = "tcp4://localhost:33415", Layout = "${message}\n", KeepConnection = true, }; target.Initialize(new LoggingConfiguration()); int toWrite = 10; int pendingWrites = toWrite; var writeCompleted = new ManualResetEvent(false); var exceptions = new List<Exception>(); AsyncContinuation writeFinished = ex => { lock (exceptions) { exceptions.Add(ex); pendingWrites--; if (pendingWrites == 0) { writeCompleted.Set(); } } }; var loggerTask = new NLog.Internal.AsyncHelpersTask(state => { for (int i = 0; i < toWrite; ++i) { var ev = new LogEventInfo(LogLevel.Info, "logger1", "message" + i).WithContinuation(writeFinished); target.WriteAsyncLogEvent(ev); } }); AsyncHelpers.StartAsyncTask(loggerTask, null); Assert.True(writeCompleted.WaitOne(10000), "Network Write not completed"); var shutdownCompleted = new ManualResetEvent(false); var closeTask = new NLog.Internal.AsyncHelpersTask(state => { // no exception target.Close(); shutdownCompleted.Set(); }); AsyncHelpers.StartAsyncTask(closeTask, null); Assert.True(shutdownCompleted.WaitOne(10000), "Network Close not completed"); Assert.Equal(toWrite, exceptions.Count); foreach (var ex in exceptions) { Assert.NotNull(ex); } } [Fact] public void NetworkTargetQueueDiscardTest() { var senderFactory = new MyQueudSenderFactory(); var target = new NetworkTarget(); target.MaxQueueSize = 1; target.Address = "tcp://someaddress/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.Initialize(null); int discardEventCalls = 0; target.LogEventDropped += (sender, args) => discardEventCalls++; int pendingWrites = 1; var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--pendingWrites == 0) mre.Set(); } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "msg0").WithContinuation(asyncContinuation)); Assert.True(mre.WaitOne(10000), "Network Write not completed"); Assert.Equal(1, senderFactory.BeginRequestCounter); Assert.Single(exceptions); foreach (var ex in exceptions) { Assert.True(ex == null, $"Network Write Exception: {ex?.ToString()}"); } senderFactory.FailCounter = 1; senderFactory.AsyncSlowCounter = 1; pendingWrites = 5; // 1st = Block, 2nd = Queue Pending mre.Reset(); for (int i = 1; i <= 5 + 2; ++i) { target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", $"msg{i}").WithContinuation(asyncContinuation)); } Assert.True(mre.WaitOne(10000), "Network Write not completed"); Assert.True(exceptions.Count >= 6, $"Network write not completed: {exceptions.Count}"); Assert.True(senderFactory.BeginRequestCounter <= 3, $"Network write not discarded: {senderFactory.BeginRequestCounter}"); foreach (var ex in exceptions.Take(6)) { Assert.True(ex == null, $"Network Write Exception: {ex?.ToString()}"); } Assert.True(discardEventCalls >= 5, $"LogDropped not called: {discardEventCalls}"); } [Fact] public void NetworkTargetQueueGrowTest() { var senderFactory = new MyQueudSenderFactory(); var target = new NetworkTarget(); target.MaxQueueSize = 1; target.OnQueueOverflow = NetworkTargetQueueOverflowAction.Grow; target.Address = "tcp://someaddress/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.Initialize(null); int pendingWrites = 1; var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--pendingWrites == 0) mre.Set(); } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "msg0").WithContinuation(asyncContinuation)); Assert.True(mre.WaitOne(10000), "Network Write not completed"); Assert.Equal(1, senderFactory.BeginRequestCounter); Assert.Single(exceptions); foreach (var ex in exceptions) { Assert.True(ex == null, $"Network Write Exception: {ex?.ToString()}"); } senderFactory.AsyncSlowCounter = 1; pendingWrites = 5; mre.Reset(); for (int i = 1; i <= 5; ++i) { target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", $"msg{i}").WithContinuation(asyncContinuation)); } Assert.True(exceptions.Count < 4, $"Network write not growing: {exceptions.Count}"); Assert.True(mre.WaitOne(10000), "Network Write not completed"); Assert.Equal(6, exceptions.Count); Assert.Equal(6, senderFactory.BeginRequestCounter); foreach (var ex in exceptions) { Assert.True(ex == null, $"Network Write Exception: {ex?.ToString()}"); } } [Fact] public void NetworkTargetQueueBlockTest() { var senderFactory = new MyQueudSenderFactory(); var target = new NetworkTarget(); target.MaxQueueSize = 1; target.OnQueueOverflow = NetworkTargetQueueOverflowAction.Block; target.Address = "tcp://someaddress/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.Initialize(null); int pendingWrites = 1; var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--pendingWrites == 0) mre.Set(); } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "msg0").WithContinuation(asyncContinuation)); Assert.True(mre.WaitOne(10000), "Network Write not completed"); Assert.Equal(1, senderFactory.BeginRequestCounter); Assert.Single(exceptions); foreach (var ex in exceptions) { Assert.True(ex == null, $"Network Write Exception: {ex?.ToString()}"); } senderFactory.AsyncSlowCounter = 1; pendingWrites = 5; mre.Reset(); for (int i = 1; i <= 5; ++i) { target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", $"msg{i}").WithContinuation(asyncContinuation)); } Assert.True(exceptions.Count >= 4, $"Network write not blocking: {exceptions.Count}"); Assert.True(mre.WaitOne(10000), "Network Write not completed"); Assert.Equal(6, exceptions.Count); Assert.Equal(6, senderFactory.BeginRequestCounter); foreach (var ex in exceptions) { Assert.True(ex == null, $"Network Write Exception: {ex?.ToString()}"); } } [Fact] public void NetworkTargetSendFailureWithoutKeepAliveTests() { var senderFactory = new MyQueudSenderFactory() { FailCounter = 3, // first 3 sends will fail AsyncMode = false, // Disable async, because unit-test cannot handle it }; var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = false; target.OnOverflow = NetworkTargetOverflowAction.Discard; target.Initialize(null); var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 5; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "01234").WithContinuation(asyncContinuation)); Assert.True(mre.WaitOne(10000), "Network Write not completed"); Assert.NotNull(exceptions[0]); Assert.NotNull(exceptions[1]); Assert.NotNull(exceptions[2]); Assert.Null(exceptions[3]); Assert.Null(exceptions[4]); target.Close(); var result = senderFactory.Log.ToString(); Assert.True(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("1: send 0 7") != -1); Assert.True(result.IndexOf("1: failed") != -1); Assert.True(result.IndexOf("1: close") != -1); Assert.True(result.IndexOf("2: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("2: send 0 7") != -1); Assert.True(result.IndexOf("2: failed") != -1); Assert.True(result.IndexOf("2: close") != -1); Assert.True(result.IndexOf("3: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("3: send 0 7") != -1); Assert.True(result.IndexOf("3: failed") != -1); Assert.True(result.IndexOf("3: close") != -1); Assert.True(result.IndexOf("4: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("4: send 0 7") != -1); Assert.True(result.IndexOf("4: close") != -1); Assert.True(result.IndexOf("5: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("5: send 0 5") != -1); Assert.True(result.IndexOf("5: close") != -1); } [Fact] public void AsyncConnectionFailureOnCloseShouldNotDeadlock() { const int total = 100; var senderFactory = new MyQueudSenderFactory() { FailCounter = total, }; var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.Initialize(null); var exceptions = new List<Exception>(); var writeCompleted = new ManualResetEvent(false); var shutdownCompleted = new ManualResetEvent(false); int remaining = total; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { writeCompleted.Set(); } } }; var shutdownTask = new NLog.Internal.AsyncHelpersTask(state => { Thread.Sleep(10); target.Flush(ex => { }); target.Close(); shutdownCompleted.Set(); }); AsyncHelpers.StartAsyncTask(shutdownTask, null); var loggerTask = new NLog.Internal.AsyncHelpersTask(state => { for (int i = 0; i < total; ++i) { target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, $"logger{i}", i.ToString()).WithContinuation(asyncContinuation)); Thread.Sleep(1); } writeCompleted.Set(); }); AsyncHelpers.StartAsyncTask(loggerTask, null); Assert.True(writeCompleted.WaitOne(10000), "Network Write not completed"); Assert.True(shutdownCompleted.WaitOne(10000), "Network Shutdown not completed"); } [Theory] [InlineData("none", SslProtocols.None)] //we can't set it on "" [InlineData("tls", SslProtocols.Tls)] [InlineData("tls11", SslProtocols.Tls11)] [InlineData("tls,tls11", SslProtocols.Tls11 | SslProtocols.Tls)] public void SslProtocolsConfigTest(string sslOptions, SslProtocols expected) { var config = XmlLoggingConfiguration.CreateFromXmlString($@" <nlog> <targets><target name='target1' type='network' layout='${{message}}' Address='tcp://127.0.0.1:50001' sslProtocols='{sslOptions}' /></targets> </nlog>"); var target = config.FindTargetByName<NetworkTarget>("target1"); Assert.Equal(expected, target.SslProtocols); } [Theory] [InlineData("0", 0)] [InlineData("30", 30)] public void KeepAliveTimeConfigTest(string keepAliveTimeSeconds, int expected) { if (IsLinux()) { Console.WriteLine("[SKIP] NetworkTargetTests.KeepAliveTimeConfigTest because we are running in Travis"); return; } var logFactory = new LogFactory().Setup().LoadConfigurationFromXml($@" <nlog> <targets async='true'><target name='target1' type='network' layout='${{level}}|${{threadid}}|${{message}}' Address='tcp://127.0.0.1:50001' keepAliveTimeSeconds='{keepAliveTimeSeconds}' /></targets> <rules><logger name='*' minLevel='Trace' writeTo='target1'/></rules> </nlog>").LogFactory; var target = logFactory.Configuration.FindTargetByName<NetworkTarget>("target1"); Assert.Equal(expected, target.KeepAliveTimeSeconds); var logger = logFactory.GetLogger("keepAliveTimeSeconds"); logger.Info("Hello"); } [Fact] public void Bug3990StackOverflowWhenUsingNLogViewerTarget() { // this would fail because of stack overflow in the // constructor of NLogViewerTarget var config = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='viewer' type='NLogViewer' address='udp://127.0.0.1:9999' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='viewer' /> </rules> </nlog>"); var target = config.LoggingRules[0].Targets[0] as NLogViewerTarget; Assert.NotNull(target); } [Fact] public void GzipCompressionTest() { var senderFactory = new MyQueudSenderFactory(); var target = new NetworkTarget(); target.Address = "tcp://someaddress/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = false; target.Compress = NetworkTargetCompressionType.GZip; target.CompressMinBytes = 15; target.LineEnding = LineEndingMode.CRLF; target.Initialize(null); var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); mre.Set(); } }; mre.Reset(); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "smallmessage").WithContinuation(asyncContinuation)); Assert.True(mre.WaitOne(10000), "Network Write not completed"); var smallMessage = target.Encoding.GetString(senderFactory.Senders.Last().MemoryStream.GetBuffer(), 0, (int)senderFactory.Senders.Last().MemoryStream.Length); Assert.Equal("smallmessage\r\n", smallMessage); mre.Reset(); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "superbigmessage").WithContinuation(asyncContinuation)); Assert.True(mre.WaitOne(10000), "Network Write not completed"); senderFactory.Senders.Last().MemoryStream.Position = 0; using (var unzipper = new System.IO.Compression.GZipStream(senderFactory.Senders.Last().MemoryStream, System.IO.Compression.CompressionMode.Decompress, true)) using (var outstream = new MemoryStream()) { unzipper.CopyTo(outstream); unzipper.Flush(); var bigMessage = target.Encoding.GetString(outstream.GetBuffer(), 0, (int)outstream.Length); Assert.Equal("superbigmessage\r\n", bigMessage); } } internal class MyQueudSenderFactory : INetworkSenderFactory { internal List<MyQueudNetworkSender> Senders = new List<MyQueudNetworkSender>(); internal StringWriter Log = new StringWriter(); private int _idCounter; public QueuedNetworkSender Create(string url, int maxQueueSize, NetworkTargetQueueOverflowAction onQueueOverflow, int maxMessageSize, SslProtocols sslProtocols, TimeSpan keepAliveTime) { var sender = new MyQueudNetworkSender(url, ++_idCounter, Log, this) { MaxQueueSize = maxQueueSize, OnQueueOverflow = onQueueOverflow }; Senders.Add(sender); return sender; } public int BeginRequestCounter { get; set; } public int FailCounter { get; set; } public int AsyncSlowCounter { get; set; } public bool AsyncMode { get; set; } = true; } internal class MyQueudNetworkSender : QueuedNetworkSender { private readonly int _id; private readonly TextWriter _log; private readonly MyQueudSenderFactory _senderFactory; public MemoryStream MemoryStream { get; } = new MemoryStream(); public MyQueudNetworkSender(string url, int id, TextWriter log, MyQueudSenderFactory senderFactory) : base(url) { _id = id; _log = log; _senderFactory = senderFactory; } protected override void DoInitialize() { base.DoInitialize(); lock (_log) { _log.WriteLine("{0}: connect {1}", _id, Address); } } protected override void DoFlush(AsyncContinuation continuation) { lock (_log) { _log.WriteLine("{0}: flush", _id); } base.DoFlush(continuation); } protected override void DoClose(AsyncContinuation continuation) { lock (_log) { _log.WriteLine("{0}: close", _id); } base.DoClose(continuation); } protected override void BeginRequest(NetworkRequestArgs eventArgs) { RegisterNextRequest(); if (_senderFactory.AsyncMode) { var asyncTask = new NLog.Internal.AsyncHelpersTask(state => { SendSync(eventArgs); }); AsyncHelpers.StartAsyncTask(asyncTask, null); } else { SendSync(eventArgs); } } private void SendSync(NetworkRequestArgs? nextRequest) { while (nextRequest.HasValue) { Thread.Sleep(CheckSendThrottleTimeMs()); var eventArgs = nextRequest.Value; var failedException = CheckForFailedException(); lock (_log) { _log.WriteLine("{0}: send {1} {2}", _id, eventArgs.RequestBufferOffset, eventArgs.RequestBufferLength); MemoryStream.Write(eventArgs.RequestBuffer, eventArgs.RequestBufferOffset, eventArgs.RequestBufferLength); if (failedException != null) { _log.WriteLine("{0}: failed", _id); } } nextRequest = EndRequest(eventArgs.AsyncContinuation, failedException); if (nextRequest.HasValue) { RegisterNextRequest(); } } } private void RegisterNextRequest() { lock (_senderFactory) { _senderFactory.BeginRequestCounter++; } } private Exception CheckForFailedException() { lock (_senderFactory) { if (_senderFactory.FailCounter > 0) { _senderFactory.FailCounter--; return new IOException("some IO error has occured"); } } return null; } private int CheckSendThrottleTimeMs() { lock (_senderFactory) { if (_senderFactory.AsyncSlowCounter > 0) { _senderFactory.AsyncSlowCounter--; return 250; } return _senderFactory.AsyncMode ? 1 : 0; } } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal.Fakeables { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Xml; using NLog.Common; internal class AppEnvironmentWrapper : IAppEnvironment { #if !NETSTANDARD1_3 private const string UnknownProcessName = "<unknown>"; private string _entryAssemblyLocation; private string _entryAssemblyFileName; private string _currentProcessFilePath; private string _currentProcessBaseName; private int? _currentProcessId; /// <inheritdoc/> public string EntryAssemblyLocation => _entryAssemblyLocation ?? (_entryAssemblyLocation = LookupEntryAssemblyLocation()); /// <inheritdoc/> public string EntryAssemblyFileName => _entryAssemblyFileName ?? (_entryAssemblyFileName = LookupEntryAssemblyFileName()); /// <inheritdoc/> public string CurrentProcessFilePath => _currentProcessFilePath ?? (_currentProcessFilePath = LookupCurrentProcessFilePathWithFallback()); /// <inheritdoc/> public string CurrentProcessBaseName => _currentProcessBaseName ?? (_currentProcessBaseName = LookupCurrentProcessNameWithFallback()); /// <inheritdoc/> public int CurrentProcessId => _currentProcessId ?? (_currentProcessId = LookupCurrentProcessIdWithFallback()).Value; #endif #pragma warning disable CS0618 // Type or member is obsolete /// <inheritdoc/> public string AppDomainBaseDirectory => AppDomain.BaseDirectory; /// <inheritdoc/> public string AppDomainConfigurationFile => AppDomain.ConfigurationFile; /// <inheritdoc/> public string AppDomainFriendlyName => AppDomain.FriendlyName; /// <inheritdoc/> public int AppDomainId => AppDomain.Id; /// <inheritdoc/> public IEnumerable<string> AppDomainPrivateBinPath => AppDomain.PrivateBinPath; /// <inheritdoc/> public IEnumerable<System.Reflection.Assembly> GetAppDomainRuntimeAssemblies() => AppDomain.GetAssemblies(); /// <inheritdoc/> public event EventHandler<EventArgs> ProcessExit { add { AppDomain.ProcessExit += value; AppDomain.DomainUnload += value; } remove { AppDomain.DomainUnload -= value; AppDomain.ProcessExit -= value; } } #pragma warning restore CS0618 // Type or member is obsolete /// <inheritdoc/> public string UserTempFilePath => Path.GetTempPath(); [Obsolete("For unit testing only. Marked obsolete on NLog 5.0")] public IAppDomain AppDomain { get; internal set; } #pragma warning disable CS0618 // Type or member is obsolete public AppEnvironmentWrapper(IAppDomain appDomain) { AppDomain = appDomain; } #pragma warning restore CS0618 // Type or member is obsolete /// <inheritdoc/> public bool FileExists(string path) { return File.Exists(path); } /// <inheritdoc/> public XmlReader LoadXmlFile(string path) { return XmlReader.Create(path); } #if !NETSTANDARD1_3 private static string LookupEntryAssemblyLocation() { var entryAssembly = System.Reflection.Assembly.GetEntryAssembly(); var entryLocation = entryAssembly?.Location; if (!string.IsNullOrEmpty(entryLocation)) { return Path.GetDirectoryName(entryLocation); } #pragma warning disable CS0618 // Type or member is obsolete return AssemblyHelpers.GetAssemblyFileLocation(entryAssembly); #pragma warning restore CS0618 // Type or member is obsolete } private static string LookupEntryAssemblyFileName() { try { var entryAssembly = System.Reflection.Assembly.GetEntryAssembly(); var entryLocation = entryAssembly?.Location; if (!string.IsNullOrEmpty(entryLocation)) { return Path.GetFileName(entryLocation); } // Fallback to the Assembly-Name when unable to extract FileName from Location var assemblyName = entryAssembly?.GetName()?.Name; if (!string.IsNullOrEmpty(assemblyName)) return assemblyName + ".dll"; else return string.Empty; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; InternalLogger.Debug("LookupEntryAssemblyFileName Failed - {0}", ex.Message); return string.Empty; } } private static string LookupCurrentProcessFilePathWithFallback() { try { var processFilePath = LookupCurrentProcessFilePath(); return processFilePath ?? LookupCurrentProcessFilePathNative(); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; InternalLogger.Debug("LookupCurrentProcessFilePath Failed - {0}", ex.Message); return LookupCurrentProcessFilePathNative(); } } private static string LookupCurrentProcessFilePath() { try { var currentProcess = Process.GetCurrentProcess(); return currentProcess?.MainModule.FileName; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; // May throw a SecurityException or Access Denied when running from an IIS app. pool process InternalLogger.Debug("LookupCurrentProcessFilePath Managed Failed - {0}", ex.Message); return null; } } private static int LookupCurrentProcessIdWithFallback() { try { var processId = LookupCurrentProcessId(); return processId ?? LookupCurrentProcessIdNative(); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; // May throw a SecurityException if running from an IIS app. pool process (Cannot compile method) InternalLogger.Debug("LookupCurrentProcessId Failed - {0}", ex.Message); return LookupCurrentProcessIdNative(); } } private static int? LookupCurrentProcessId() { try { var currentProcess = Process.GetCurrentProcess(); return currentProcess?.Id; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; // May throw a SecurityException or Access Denied when running from an IIS app. pool process InternalLogger.Debug("LookupCurrentProcessId Managed Failed - {0}", ex.Message); return null; } } private static string LookupCurrentProcessNameWithFallback() { try { var processName = LookupCurrentProcessName(); return processName ?? LookupCurrentProcessNameNative(); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; // May throw a SecurityException if running from an IIS app. pool process (Cannot compile method) InternalLogger.Debug("LookupCurrentProcessName Failed - {0}", ex.Message); return LookupCurrentProcessNameNative(); } } private static string LookupCurrentProcessName() { try { var currentProcess = Process.GetCurrentProcess(); var currentProcessName = currentProcess?.ProcessName; if (!string.IsNullOrEmpty(currentProcessName)) return currentProcessName; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; InternalLogger.Debug("LookupCurrentProcessName Managed Failed - {0}", ex.Message); } return null; } private static string LookupCurrentProcessNameNative() { var currentProcessFilePath = LookupCurrentProcessFilePath(); if (!string.IsNullOrEmpty(currentProcessFilePath)) { var currentProcessName = Path.GetFileNameWithoutExtension(currentProcessFilePath); if (!string.IsNullOrEmpty(currentProcessName)) return currentProcessName; } return UnknownProcessName; } #endif #if !NETSTANDARD private static string LookupCurrentProcessFilePathNative() { try { if (!PlatformDetector.IsWin32) return string.Empty; return LookupCurrentProcessFilePathWin32(); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; InternalLogger.Debug("LookupCurrentProcessFilePath Native Failed - {0}", ex.Message); return string.Empty; } } [System.Security.SecuritySafeCritical] private static string LookupCurrentProcessFilePathWin32() { try { var sb = new System.Text.StringBuilder(512); if (0 == NativeMethods.GetModuleFileName(IntPtr.Zero, sb, sb.Capacity)) { throw new InvalidOperationException("Cannot determine program name."); } return sb.ToString(); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; InternalLogger.Debug("LookupCurrentProcessFilePath Win32 Failed - {0}", ex.Message); return string.Empty; } } private static int LookupCurrentProcessIdNative() { try { if (!PlatformDetector.IsWin32) return 0; return LookupCurrentProcessIdWin32(); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; InternalLogger.Debug("LookupCurrentProcessId Native Failed - {0}", ex.Message); return 0; } } [System.Security.SecuritySafeCritical] private static int LookupCurrentProcessIdWin32() { try { return NativeMethods.GetCurrentProcessId(); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; InternalLogger.Debug("LookupCurrentProcessId Win32 Failed - {0}", ex.Message); return 0; } } #else private static string LookupCurrentProcessFilePathNative() { return string.Empty; } private static int LookupCurrentProcessIdNative() { return 0; } #endif } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; namespace NLog.Internal { /// <summary> /// Controls a single allocated object for reuse (only one active user) /// </summary> internal class ReusableObjectCreator<T> where T : class { protected T _reusableObject; private readonly Action<T> _clearObject; private readonly Func<int, T> _createObject; private readonly int _initialCapacity; protected ReusableObjectCreator(int initialCapacity, Func<int, T> createObject, Action<T> clearObject) { _reusableObject = createObject(initialCapacity); _clearObject = clearObject; _createObject = createObject; _initialCapacity = initialCapacity; } /// <summary> /// Creates handle to the reusable char[]-buffer for active usage /// </summary> /// <returns>Handle to the reusable item, that can release it again</returns> public LockOject Allocate() { var reusableObject = _reusableObject ?? _createObject(_initialCapacity); System.Diagnostics.Debug.Assert(_reusableObject != null); _reusableObject = null; return new LockOject(this, reusableObject); } private void Deallocate(T reusableObject) { _clearObject(reusableObject); _reusableObject = reusableObject; } public struct LockOject : IDisposable { /// <summary> /// Access the acquired reusable object /// </summary> public readonly T Result; private readonly ReusableObjectCreator<T> _owner; public LockOject(ReusableObjectCreator<T> owner, T reusableObject) { Result = reusableObject; _owner = owner; } public void Dispose() { _owner?.Deallocate(Result); } } } } <file_sep>using System; using NLog; using NLog.Targets; using NLog.Targets.Wrappers; using System.Diagnostics; class Example { static void Main(string[] args) { FileTarget wrappedTarget = new FileTarget(); wrappedTarget.FileName = "${basedir}/file.txt"; BufferingTargetWrapper target = new BufferingTargetWrapper(); target.BufferSize = 100; target.WrappedTarget = wrappedTarget; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Linq; using NLog.MessageTemplates; using Xunit; namespace NLog.UnitTests.MessageTemplates { public class MessageTemplateParameterTests { [Theory] [InlineData("0", 0)] //all single numbers for all code branches [InlineData("1", 1)] [InlineData("2", 2)] [InlineData("3", 3)] [InlineData("4", 4)] [InlineData("5", 5)] [InlineData("6", 6)] [InlineData("7", 7)] [InlineData("8", 8)] [InlineData("9", 9)] [InlineData(" 1 ", null)] //no trim [InlineData("100", 100)] //parse test [InlineData(" 100 ", null)] //no trim in parse test [InlineData("a", null)] //no parse test [InlineData("a1", null)] //no partial parse test [InlineData("0a", null)] //condition branch 1 [InlineData("1a", null)] //condition branch 1b [InlineData("9a", null)] //condition branch 2a [InlineData("8a", null)] //condition branch 2b public void PositionalIndexTest(string name, int? expected) { // Arrange var parameter = new MessageTemplateParameter(name, null, null); // Act var positionalIndex = parameter.PositionalIndex; // Assert Assert.Equal(expected, positionalIndex); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 && !NETSTANDARD1_5 namespace NLog.LayoutRenderers { using System.Security.Principal; using System.Text; /// <summary> /// Thread identity information (name and authentication information). /// </summary> [LayoutRenderer("identity")] public class IdentityLayoutRenderer : LayoutRenderer { /// <summary> /// Gets or sets the separator to be used when concatenating /// parts of identity information. /// </summary> /// <docgen category='Layout Options' order='50' /> public string Separator { get; set; } = ":"; /// <summary> /// Gets or sets a value indicating whether to render Thread.CurrentPrincipal.Identity.Name. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool Name { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether to render Thread.CurrentPrincipal.Identity.AuthenticationType. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool AuthType { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether to render Thread.CurrentPrincipal.Identity.IsAuthenticated. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IsAuthenticated { get; set; } = true; /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { IIdentity identity = GetValue(); if (identity != null) { string separator = string.Empty; if (IsAuthenticated) { builder.Append(separator); separator = Separator; builder.Append(identity.IsAuthenticated ? "auth" : "notauth"); } if (AuthType) { builder.Append(separator); separator = Separator; builder.Append(identity.AuthenticationType); } if (Name) { builder.Append(separator); builder.Append(identity.Name); } } } private static IIdentity GetValue() { var currentPrincipal = System.Threading.Thread.CurrentPrincipal; return currentPrincipal?.Identity; } } } #endif <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if NETSTANDARD1_3 || NETSTANDARD1_5 namespace NLog.Internal { using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Threading; static class NetStandardHelpers { public static void Close(this IDisposable disposable) { disposable.Dispose(); } #pragma warning disable S2953 // Methods named "Dispose" should implement "IDisposable.Dispose" public static bool Dispose(this IDisposable disposable, EventWaitHandle waitHandle) #pragma warning restore S2953 // Methods named "Dispose" should implement "IDisposable.Dispose" { disposable.Dispose(); return false; } public static bool IsDefined(this Type type, Type other, bool inherit) { return type.GetTypeInfo().IsDefined(other, inherit); } public static bool IsSubclassOf(this Type type, Type other) { return type.GetTypeInfo().IsSubclassOf(other); } public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingAttr, object binder, Type[] types, object[] modifiers) { if (binder != null) throw new ArgumentException("Not supported", nameof(binder)); if (modifiers != null) throw new ArgumentException("Not supported", nameof(modifiers)); foreach (MethodInfo method in type.GetMethods(bindingAttr)) { if (method.Name != name) continue; var parameters = method.GetParameters(); if (parameters is null || parameters.Length != types.Length) continue; for (int i = 0; i < parameters.Length; ++i) { if (parameters[i].ParameterType != types[i]) { parameters = null; break; } } if (parameters != null) { return method; } } return null; } public static byte[] GetBuffer(this MemoryStream memoryStream) { ArraySegment<byte> bytes; if (memoryStream.TryGetBuffer(out bytes)) { return bytes.Array; } return memoryStream.ToArray(); } public static StackFrame GetFrame(this StackTrace strackTrace, int number) { return strackTrace.GetFrames()[number]; } } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Collections.Generic; using System.Text; using NLog.Common; using NLog.Config; using NLog.Internal; /// <summary> /// Exception information provided through /// a call to one of the Logger.*Exception() methods. /// </summary> [LayoutRenderer("exception")] [ThreadAgnostic] public class ExceptionLayoutRenderer : LayoutRenderer, IRawValue { private string _format; private string _innerFormat = string.Empty; private static readonly Dictionary<string, ExceptionRenderingFormat> _formatsMapping = new Dictionary<string, ExceptionRenderingFormat>(StringComparer.OrdinalIgnoreCase) { {"MESSAGE",ExceptionRenderingFormat.Message}, {"TYPE", ExceptionRenderingFormat.Type}, {"SHORTTYPE",ExceptionRenderingFormat.ShortType}, {"TOSTRING",ExceptionRenderingFormat.ToString}, {"METHOD",ExceptionRenderingFormat.Method}, {"TARGETSITE",ExceptionRenderingFormat.Method}, {"SOURCE",ExceptionRenderingFormat.Source}, {"STACKTRACE", ExceptionRenderingFormat.StackTrace}, {"DATA",ExceptionRenderingFormat.Data}, {"@",ExceptionRenderingFormat.Serialize}, {"HRESULT",ExceptionRenderingFormat.HResult}, {"PROPERTIES",ExceptionRenderingFormat.Properties}, }; private static readonly Dictionary<ExceptionRenderingFormat, Action<ExceptionLayoutRenderer, StringBuilder, Exception, Exception>> _renderingfunctions = new Dictionary<ExceptionRenderingFormat, Action<ExceptionLayoutRenderer, StringBuilder, Exception, Exception>>() { {ExceptionRenderingFormat.Message, (layout, sb, ex, aggex) => layout.AppendMessage(sb, ex)}, {ExceptionRenderingFormat.Type, (layout, sb, ex, aggex) => layout.AppendType(sb, ex)}, { ExceptionRenderingFormat.ShortType, (layout, sb, ex, aggex) => layout.AppendShortType(sb, ex)}, { ExceptionRenderingFormat.ToString, (layout, sb, ex, aggex) => layout.AppendToString(sb, ex)}, { ExceptionRenderingFormat.Method, (layout, sb, ex, aggex) => layout.AppendMethod(sb, ex)}, { ExceptionRenderingFormat.Source, (layout, sb, ex, aggex) => layout.AppendSource(sb, ex)}, { ExceptionRenderingFormat.StackTrace, (layout, sb, ex, aggex) => layout.AppendStackTrace(sb, ex)}, { ExceptionRenderingFormat.Data, (layout, sb, ex, aggex) => layout.AppendData(sb, ex, aggex)}, { ExceptionRenderingFormat.Serialize, (layout, sb, ex, aggex) => layout.AppendSerializeObject(sb, ex)}, { ExceptionRenderingFormat.HResult, (layout, sb, ex, aggex) => layout.AppendHResult(sb, ex)}, { ExceptionRenderingFormat.Properties, (layout, sb, ex, aggex) => layout.AppendProperties(sb, ex)}, }; private static readonly HashSet<string> ExcludeDefaultProperties = new HashSet<string>(new[] { "Type", nameof(Exception.Data), nameof(Exception.HelpLink), "HResult", // Not available on NET35 + NET40 nameof(Exception.InnerException), nameof(Exception.Message), nameof(Exception.Source), nameof(Exception.StackTrace), "TargetSite",// Not available on NETSTANDARD1_3 OR NETSTANDARD1_5 }, StringComparer.Ordinal); private ObjectReflectionCache ObjectReflectionCache => _objectReflectionCache ?? (_objectReflectionCache = new ObjectReflectionCache(LoggingConfiguration.GetServiceProvider())); private ObjectReflectionCache _objectReflectionCache; /// <summary> /// Initializes a new instance of the <see cref="ExceptionLayoutRenderer" /> class. /// </summary> public ExceptionLayoutRenderer() { Format = "TOSTRING,DATA"; } /// <summary> /// Gets or sets the format of the output. Must be a comma-separated list of exception /// properties: Message, Type, ShortType, ToString, Method, StackTrace. /// This parameter value is case-insensitive. /// </summary> /// <see cref="Formats"/> /// <see cref="ExceptionRenderingFormat"/> /// <docgen category='Layout Options' order='10' /> [DefaultParameter] public string Format { get => _format; set { _format = value; Formats = CompileFormat(value, nameof(Format)); } } /// <summary> /// Gets or sets the format of the output of inner exceptions. Must be a comma-separated list of exception /// properties: Message, Type, ShortType, ToString, Method, StackTrace. /// This parameter value is case-insensitive. /// </summary> /// <docgen category='Layout Options' order='50' /> public string InnerFormat { get => _innerFormat; set { _innerFormat = value; InnerFormats = CompileFormat(value, nameof(InnerFormat)); } } /// <summary> /// Gets or sets the separator used to concatenate parts specified in the Format. /// </summary> /// <docgen category='Layout Options' order='50' /> public string Separator { get => _seperator; set => _seperator = new NLog.Layouts.SimpleLayout(value).Render(LogEventInfo.CreateNullEvent()); } private string _seperator = " "; /// <summary> /// Gets or sets the separator used to concatenate exception data specified in the Format. /// </summary> /// <docgen category='Layout Options' order='50' /> public string ExceptionDataSeparator { get => _exceptionDataSeparator; set => _exceptionDataSeparator = new NLog.Layouts.SimpleLayout(value).Render(LogEventInfo.CreateNullEvent()); } private string _exceptionDataSeparator = ";"; /// <summary> /// Gets or sets the maximum number of inner exceptions to include in the output. /// By default inner exceptions are not enabled for compatibility with NLog 1.0. /// </summary> /// <docgen category='Layout Options' order='50' /> public int MaxInnerExceptionLevel { get; set; } /// <summary> /// Gets or sets the separator between inner exceptions. /// </summary> /// <docgen category='Layout Options' order='50' /> public string InnerExceptionSeparator { get; set; } = EnvironmentHelper.NewLine; /// <summary> /// Gets or sets whether to render innermost Exception from <see cref="Exception.GetBaseException()"/> /// </summary> /// <docgen category='Layout Options' order='50' /> public bool BaseException { get; set; } #if !NET35 /// <summary> /// Gets or sets whether to collapse exception tree using <see cref="AggregateException.Flatten()"/> /// </summary> /// <docgen category='Layout Options' order='50' /> #else /// <summary> /// Gets or sets whether to collapse exception tree using AggregateException.Flatten() /// </summary> /// <docgen category='Layout Options' order='50' /> #endif public bool FlattenException { get; set; } = true; /// <summary> /// Gets the formats of the output of inner exceptions to be rendered in target. <see cref="ExceptionRenderingFormat"/> /// </summary> /// <docgen category='Layout Options' order='50' /> public List<ExceptionRenderingFormat> Formats { get; private set; } /// <summary> /// Gets the formats of the output to be rendered in target. <see cref="ExceptionRenderingFormat"/> /// </summary> /// <docgen category='Layout Options' order='50' /> public List<ExceptionRenderingFormat> InnerFormats { get; private set; } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = GetTopException(logEvent); return true; } private Exception GetTopException(LogEventInfo logEvent) { return BaseException ? logEvent.Exception?.GetBaseException() : logEvent.Exception; } /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { Exception primaryException = GetTopException(logEvent); if (primaryException != null) { int currentLevel = 0; #if !NET35 if (logEvent.Exception is AggregateException aggregateException) { primaryException = FlattenException ? GetPrimaryException(aggregateException) : aggregateException; AppendException(primaryException, Formats, builder, aggregateException); if (currentLevel < MaxInnerExceptionLevel) { currentLevel = AppendInnerExceptionTree(primaryException, currentLevel, builder); if (currentLevel < MaxInnerExceptionLevel && aggregateException.InnerExceptions?.Count > 1) { AppendAggregateException(aggregateException, currentLevel, builder); } } } else #endif { AppendException(primaryException, Formats, builder); if (currentLevel < MaxInnerExceptionLevel) { AppendInnerExceptionTree(primaryException, currentLevel, builder); } } } } #if !NET35 private static Exception GetPrimaryException(AggregateException aggregateException) { if (aggregateException.InnerExceptions.Count == 1) { var innerException = aggregateException.InnerExceptions[0]; if (!(innerException is AggregateException)) return innerException; // Skip calling Flatten() } aggregateException = aggregateException.Flatten(); if (aggregateException.InnerExceptions.Count == 1) { return aggregateException.InnerExceptions[0]; } return aggregateException; } private void AppendAggregateException(AggregateException primaryException, int currentLevel, StringBuilder builder) { var asyncException = primaryException.Flatten(); if (asyncException.InnerExceptions != null) { for (int i = 0; i < asyncException.InnerExceptions.Count && currentLevel < MaxInnerExceptionLevel; i++, currentLevel++) { var currentException = asyncException.InnerExceptions[i]; if (ReferenceEquals(currentException, primaryException.InnerException)) continue; // Skip firstException when it is innerException if (currentException is null) { InternalLogger.Debug("Skipping rendering exception as exception is null"); continue; } AppendInnerException(currentException, builder); currentLevel++; currentLevel = AppendInnerExceptionTree(currentException, currentLevel, builder); } } } #endif private int AppendInnerExceptionTree(Exception currentException, int currentLevel, StringBuilder sb) { currentException = currentException.InnerException; while (currentException != null && currentLevel < MaxInnerExceptionLevel) { AppendInnerException(currentException, sb); currentLevel++; currentException = currentException.InnerException; } return currentLevel; } private void AppendInnerException(Exception currentException, StringBuilder builder) { // separate inner exceptions builder.Append(InnerExceptionSeparator); AppendException(currentException, InnerFormats ?? Formats, builder); } private void AppendException(Exception currentException, List<ExceptionRenderingFormat> renderFormats, StringBuilder builder, Exception aggregateException = null) { int currentLength = builder.Length; foreach (ExceptionRenderingFormat renderingFormat in renderFormats) { int beforeRenderLength = builder.Length; var currentRenderFunction = _renderingfunctions[renderingFormat]; currentRenderFunction(this, builder, currentException, aggregateException); if (builder.Length != beforeRenderLength) { currentLength = builder.Length; builder.Append(Separator); } } builder.Length = currentLength; } /// <summary> /// Appends the Message of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The exception containing the Message to append.</param> protected virtual void AppendMessage(StringBuilder sb, Exception ex) { try { sb.Append(ex.Message); } catch (Exception exception) { var message = $"Exception in {typeof(ExceptionLayoutRenderer).FullName}.AppendMessage(): {exception.GetType().FullName}."; sb.Append("NLog message: "); sb.Append(message); InternalLogger.Warn(exception, message); } } /// <summary> /// Appends the method name from Exception's stack trace to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose method name should be appended.</param> [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming - Allow callsite logic", "IL2026")] protected virtual void AppendMethod(StringBuilder sb, Exception ex) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 sb.Append(ex.TargetSite?.ToString()); #else sb.Append(ParseMethodNameFromStackTrace(ex.StackTrace)); #endif } /// <summary> /// Appends the stack trace from an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose stack trace should be appended.</param> protected virtual void AppendStackTrace(StringBuilder sb, Exception ex) { sb.Append(ex.StackTrace); } /// <summary> /// Appends the result of calling ToString() on an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose call to ToString() should be appended.</param> protected virtual void AppendToString(StringBuilder sb, Exception ex) { try { sb.Append(ex.ToString()); } catch (Exception exception) { var message = $"Exception in {typeof(ExceptionLayoutRenderer).FullName}.AppendToString(): {exception.GetType().FullName}."; sb.Append("NLog message: "); sb.Append(message); InternalLogger.Warn(exception, message); } } /// <summary> /// Appends the type of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose type should be appended.</param> protected virtual void AppendType(StringBuilder sb, Exception ex) { sb.Append(ex.GetType().FullName); } /// <summary> /// Appends the short type of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose short type should be appended.</param> protected virtual void AppendShortType(StringBuilder sb, Exception ex) { sb.Append(ex.GetType().Name); } /// <summary> /// Appends the application source of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose source should be appended.</param> protected virtual void AppendSource(StringBuilder sb, Exception ex) { sb.Append(ex.Source); } /// <summary> /// Appends the HResult of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose HResult should be appended.</param> protected virtual void AppendHResult(StringBuilder sb, Exception ex) { #if !NET35 && !NET40 const int S_OK = 0; // Carries no information, so skip const int S_FALSE = 1; // Carries no information, so skip if (ex.HResult != S_OK && ex.HResult != S_FALSE) { sb.AppendFormat("0x{0:X8}", ex.HResult); } #endif } private void AppendData(StringBuilder builder, Exception ex, Exception aggregateException) { if (aggregateException?.Data?.Count > 0 && !ReferenceEquals(ex, aggregateException)) { AppendData(builder, aggregateException); builder.Append(Separator); } AppendData(builder, ex); } /// <summary> /// Appends the contents of an Exception's Data property to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose Data property elements should be appended.</param> protected virtual void AppendData(StringBuilder sb, Exception ex) { if (ex.Data?.Count > 0) { string separator = string.Empty; foreach (var key in ex.Data.Keys) { sb.Append(separator); sb.AppendFormat("{0}: {1}", key, ex.Data[key]); separator = ExceptionDataSeparator; } } } /// <summary> /// Appends all the serialized properties of an Exception into the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose properties should be appended.</param> protected virtual void AppendSerializeObject(StringBuilder sb, Exception ex) { ValueFormatter.FormatValue(ex, null, MessageTemplates.CaptureType.Serialize, null, sb); } /// <summary> /// Appends all the additional properties of an Exception like Data key-value-pairs /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose properties should be appended.</param> protected virtual void AppendProperties(StringBuilder sb, Exception ex) { string separator = string.Empty; var exceptionProperties = ObjectReflectionCache.LookupObjectProperties(ex); foreach (var property in exceptionProperties) { if (ExcludeDefaultProperties.Contains(property.Name)) continue; var propertyValue = property.Value?.ToString(); if (string.IsNullOrEmpty(propertyValue)) continue; sb.Append(separator); sb.AppendFormat("{0}: {1}", property.Name, propertyValue); separator = ExceptionDataSeparator; } } /// <summary> /// Split the string and then compile into list of Rendering formats. /// </summary> private static List<ExceptionRenderingFormat> CompileFormat(string formatSpecifier, string propertyName) { List<ExceptionRenderingFormat> formats = new List<ExceptionRenderingFormat>(); string[] parts = formatSpecifier.SplitAndTrimTokens(','); foreach (string s in parts) { ExceptionRenderingFormat renderingFormat; if (_formatsMapping.TryGetValue(s, out renderingFormat)) { formats.Add(renderingFormat); } else { InternalLogger.Warn("Exception-LayoutRenderer assigned unknown {0}: {1}", propertyName, s); // TODO Delay parsing to Initialize and check ThrowConfigExceptions } } return formats; } #if NETSTANDARD1_3 || NETSTANDARD1_5 /// <summary> /// Find name of method on stracktrace. /// </summary> /// <param name="stackTrace">Full stracktrace</param> /// <returns></returns> protected static string ParseMethodNameFromStackTrace(string stackTrace) { if (string.IsNullOrEmpty(stackTrace)) return string.Empty; // get the first line of the stack trace string stackFrameLine; int p = stackTrace.IndexOfAny(new[] { '\r', '\n' }); if (p >= 0) { stackFrameLine = stackTrace.Substring(0, p); } else { stackFrameLine = stackTrace; } // stack trace is composed of lines which look like this // // at NLog.UnitTests.LayoutRenderers.ExceptionTests.GenericClass`3.Method2[T1,T2,T3](T1 aaa, T2 b, T3 o, Int32 i, DateTime now, Nullable`1 gfff, List`1[] something) // // "at " prefix can be localized so we cannot hard-code it but it's followed by a space, class name (which does not have a space in it) and opening parenthesis int lastSpace = -1; int startPos = 0; int endPos = stackFrameLine.Length; for (int i = 0; i < stackFrameLine.Length; ++i) { switch (stackFrameLine[i]) { case ' ': lastSpace = i; break; case '(': startPos = lastSpace + 1; break; case ')': endPos = i + 1; // end the loop i = stackFrameLine.Length; break; } } return stackTrace.Substring(startPos, endPos - startPos); } #endif } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Reflection; using NLog.Common; using NLog.Conditions; using NLog.Internal; /// <summary> /// Factory for locating methods. /// </summary> internal class MethodFactory : #pragma warning disable CS0618 // Type or member is obsolete INamedItemFactory<MethodInfo, MethodInfo>, #pragma warning restore CS0618 // Type or member is obsolete IFactory { private readonly MethodFactory _globalDefaultFactory; private readonly Dictionary<string, MethodDetails> _nameToMethodDetails = new Dictionary<string, MethodDetails>(StringComparer.OrdinalIgnoreCase); struct MethodDetails { public readonly MethodInfo MethodInfo; public readonly Func<LogEventInfo, object> NoParameters; public readonly Func<LogEventInfo, object, object> OneParameter; public readonly Func<LogEventInfo, object, object, object> TwoParameters; public readonly Func<LogEventInfo, object, object, object, object> ThreeParameters; public readonly Func<object[], object> ManyParameters; public readonly int ManyParameterMinCount; public readonly int ManyParameterMaxCount; public readonly bool ManyParameterWithLogEvent; public MethodDetails( MethodInfo methodInfo, Func<LogEventInfo, object> noParameters, Func<LogEventInfo, object, object> oneParameter, Func<LogEventInfo, object, object, object> twoParameters, Func<LogEventInfo, object, object, object, object> threeParameters, Func<object[], object> manyParameters, int manyParameterMinCount, int manyParameterMaxCount, bool manyParameterWithLogEvent) { MethodInfo = methodInfo; NoParameters = noParameters; OneParameter = oneParameter; TwoParameters = twoParameters; ThreeParameters = threeParameters; ManyParameters = manyParameters; ManyParameterMinCount = manyParameterMinCount; ManyParameterMaxCount = manyParameterMaxCount; ManyParameterWithLogEvent = manyParameterWithLogEvent; } } /// <summary> /// Initializes a new instance of the <see cref="MethodFactory"/> class. /// </summary> public MethodFactory(MethodFactory globalDefaultFactory) { _globalDefaultFactory = globalDefaultFactory; } /// <summary> /// Scans the assembly for classes marked with expected class <see cref="Attribute"/> /// and methods marked with expected <see cref="NameBaseAttribute"/> and adds them /// to the factory. /// </summary> /// <param name="types">The types to scan.</param> /// <param name="assemblyName">The assembly name for the type.</param> /// <param name="itemNamePrefix">The item name prefix.</param> [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2072")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2062")] public void ScanTypes(Type[] types, string assemblyName, string itemNamePrefix) { foreach (Type t in types) { try { if (t.IsClass()) { RegisterType(t, itemNamePrefix); } } catch (Exception exception) { InternalLogger.Error(exception, "Failed to add type '{0}'.", t.FullName); if (exception.MustBeRethrown()) { throw; } } } } /// <summary> /// Registers the type. /// </summary> /// <param name="type">The type to register.</param> /// <param name="itemNamePrefix">The item name prefix.</param> void IFactory.RegisterType([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicMethods)] Type type, string itemNamePrefix) { RegisterType(type, itemNamePrefix); } /// <summary> /// Registers the type. /// </summary> /// <param name="type">The type to register.</param> /// <param name="itemNamePrefix">The item name prefix.</param> private void RegisterType([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type, string itemNamePrefix) { var extractedMethods = ExtractClassMethods<ConditionMethodsAttribute, ConditionMethodAttribute>(type); if (extractedMethods?.Count > 0) { for (int i = 0; i < extractedMethods.Count; ++i) { string methodName = string.IsNullOrEmpty(itemNamePrefix) ? extractedMethods[i].Key : itemNamePrefix + extractedMethods[i].Key; RegisterDefinition(methodName, extractedMethods[i].Value); } } } /// <summary> /// Scans a type for relevant methods with their symbolic names /// </summary> /// <typeparam name="TClassAttributeType">Include types that are marked with this attribute</typeparam> /// <typeparam name="TMethodAttributeType">Include methods that are marked with this attribute</typeparam> /// <param name="type">Class Type to scan</param> /// <returns>Collection of methods with their symbolic names</returns> private static IList<KeyValuePair<string, MethodInfo>> ExtractClassMethods<TClassAttributeType, TMethodAttributeType>([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) where TClassAttributeType : Attribute where TMethodAttributeType : NameBaseAttribute { if (!type.IsDefined(typeof(TClassAttributeType), false)) return ArrayHelper.Empty<KeyValuePair<string, MethodInfo>>(); var conditionMethods = new List<KeyValuePair<string, MethodInfo>>(); foreach (MethodInfo mi in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) { var methodAttributes = (TMethodAttributeType[])mi.GetCustomAttributes(typeof(TMethodAttributeType), false); foreach (var attr in methodAttributes) { conditionMethods.Add(new KeyValuePair<string, MethodInfo>(attr.Name, mi)); } } return conditionMethods; } /// <summary> /// Clears contents of the factory. /// </summary> public void Clear() { lock (_nameToMethodDetails) { _nameToMethodDetails.Clear(); } } /// <summary> /// Registers the definition of a single method. /// </summary> /// <param name="itemName">The method name.</param> /// <param name="itemDefinition">The method info.</param> [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] void INamedItemFactory<MethodInfo, MethodInfo>.RegisterDefinition(string itemName, MethodInfo itemDefinition) { RegisterDefinition(itemName, itemDefinition); } internal void RegisterDefinition(string methodName, MethodInfo methodInfo) { object[] defaultMethodParameters = ResolveDefaultMethodParameters(methodInfo, out var manyParameterMinCount, out var manyParameterMaxCount, out var includeLogEvent); if (manyParameterMaxCount > 0) RegisterManyParameters(methodName, (inputArgs) => InvokeMethodInfo(methodInfo, ResolveMethodParameters(defaultMethodParameters, inputArgs)), manyParameterMinCount, manyParameterMaxCount, includeLogEvent, methodInfo); if (manyParameterMinCount == 0) { if (!includeLogEvent) RegisterNoParameters(methodName, (logEvent) => InvokeMethodInfo(methodInfo, defaultMethodParameters), methodInfo); else RegisterNoParameters(methodName, (logEvent) => InvokeMethodInfo(methodInfo, ResolveMethodParameters(defaultMethodParameters, logEvent)), methodInfo); } if (manyParameterMinCount <= 1 && manyParameterMaxCount >= 1) { if (!includeLogEvent) RegisterOneParameter(methodName, (logEvent, arg1) => InvokeMethodInfo(methodInfo, ResolveMethodParameters(defaultMethodParameters, arg1)), methodInfo); else RegisterOneParameter(methodName, (logEvent, arg1) => InvokeMethodInfo(methodInfo, ResolveMethodParameters(defaultMethodParameters, logEvent, arg1)), methodInfo); } if (manyParameterMinCount <= 2 && manyParameterMaxCount >= 2) { if (!includeLogEvent) RegisterTwoParameters(methodName, (logEvent, arg1, arg2) => InvokeMethodInfo(methodInfo, ResolveMethodParameters(defaultMethodParameters, arg1, arg2)), methodInfo); else RegisterTwoParameters(methodName, (logEvent, arg1, arg2) => InvokeMethodInfo(methodInfo, ResolveMethodParameters(defaultMethodParameters, logEvent, arg1, arg2)), methodInfo); } if (manyParameterMinCount <= 3 && manyParameterMaxCount >= 3) { if (!includeLogEvent) RegisterThreeParameters(methodName, (logEvent, arg1, arg2, arg3) => InvokeMethodInfo(methodInfo, ResolveMethodParameters(defaultMethodParameters, arg1, arg2, arg3)), methodInfo); else RegisterThreeParameters(methodName, (logEvent, arg1, arg2, arg3) => InvokeMethodInfo(methodInfo, ResolveMethodParameters(defaultMethodParameters, logEvent, arg1, arg2, arg3)), methodInfo); } } private static object InvokeMethodInfo(MethodInfo methodInfo, object[] methodArgs) { try { return methodInfo.Invoke(null, methodArgs); } catch (TargetInvocationException ex) { if (ex.InnerException is null) throw; throw ex.InnerException; } } private static object[] ResolveDefaultMethodParameters(MethodInfo methodInfo, out int manyParameterMinCount, out int manyParameterMaxCount, out bool includeLogEvent) { var methodParameters = methodInfo.GetParameters(); manyParameterMinCount = 0; manyParameterMaxCount = methodParameters.Length; var defaultMethodParameters = new object[methodParameters.Length]; for (int i = 0; i < defaultMethodParameters.Length; ++i) { if (methodParameters[i].IsOptional) defaultMethodParameters[i] = methodParameters[i].DefaultValue; else ++manyParameterMinCount; } includeLogEvent = methodParameters.Length > 0 && methodParameters[0].ParameterType == typeof(LogEventInfo); if (includeLogEvent) { --manyParameterMaxCount; if (manyParameterMinCount > 0) --manyParameterMinCount; } return defaultMethodParameters; } private static object[] ResolveMethodParameters(object[] defaultMethodParameters, object[] inputParameters) { if (defaultMethodParameters.Length == inputParameters.Length) return inputParameters; object[] methodParameters = new object[defaultMethodParameters.Length]; for (int i = 0; i < inputParameters.Length; ++i) methodParameters[i] = inputParameters[i]; for (int i = inputParameters.Length; i < defaultMethodParameters.Length; ++i) methodParameters[i] = defaultMethodParameters[i]; return methodParameters; } private static object[] ResolveMethodParameters(object[] defaultMethodParameters, object inputParameterArg1) { object[] methodParameters = new object[defaultMethodParameters.Length]; methodParameters[0] = inputParameterArg1; for (int i = 1; i < defaultMethodParameters.Length; ++i) methodParameters[i] = defaultMethodParameters[i]; return methodParameters; } private static object[] ResolveMethodParameters(object[] defaultMethodParameters, object inputParameterArg1, object inputParameterArg2) { object[] methodParameters = new object[defaultMethodParameters.Length]; methodParameters[0] = inputParameterArg1; methodParameters[1] = inputParameterArg2; for (int i = 2; i < defaultMethodParameters.Length; ++i) methodParameters[i] = defaultMethodParameters[i]; return methodParameters; } private static object[] ResolveMethodParameters(object[] defaultMethodParameters, object inputParameterArg1, object inputParameterArg2, object inputParameterArg3) { object[] methodParameters = new object[defaultMethodParameters.Length]; methodParameters[0] = inputParameterArg1; methodParameters[1] = inputParameterArg2; methodParameters[2] = inputParameterArg3; for (int i = 3; i < defaultMethodParameters.Length; ++i) methodParameters[i] = defaultMethodParameters[i]; return methodParameters; } private static object[] ResolveMethodParameters(object[] defaultMethodParameters, object inputParameterArg1, object inputParameterArg2, object inputParameterArg3, object inputParameterArg4) { object[] methodParameters = new object[defaultMethodParameters.Length]; methodParameters[0] = inputParameterArg1; methodParameters[1] = inputParameterArg2; methodParameters[2] = inputParameterArg3; methodParameters[3] = inputParameterArg4; for (int i = 4; i < defaultMethodParameters.Length; ++i) methodParameters[i] = defaultMethodParameters[i]; return methodParameters; } /// <summary> /// Tries to retrieve method by name. /// </summary> /// <param name="itemName">The method name.</param> /// <param name="result">The result.</param> /// <returns>A value of <c>true</c> if the method was found, <c>false</c> otherwise.</returns> [Obsolete("Use TryCreateInstance instead. Marked obsolete with NLog v5.2")] bool INamedItemFactory<MethodInfo, MethodInfo>.TryCreateInstance(string itemName, out MethodInfo result) { return TryGetDefinition(itemName, out result); } /// <summary> /// Retrieves method by name. /// </summary> /// <param name="itemName">Method name.</param> /// <returns>MethodInfo object.</returns> [Obsolete("Use TryCreateInstance instead. Marked obsolete with NLog v5.2")] MethodInfo INamedItemFactory<MethodInfo, MethodInfo>.CreateInstance(string itemName) { if (TryGetDefinition(itemName, out MethodInfo result)) { return result; } throw new NLogConfigurationException($"Unknown function: '{itemName}'"); } /// <summary> /// Tries to get method definition. /// </summary> /// <param name="itemName">The method name.</param> /// <param name="result">The result.</param> /// <returns>A value of <c>true</c> if the method was found, <c>false</c> otherwise.</returns> [Obsolete("Use TryCreateInstance instead. Marked obsolete with NLog v5.2")] public bool TryGetDefinition(string itemName, out MethodInfo result) { lock (_nameToMethodDetails) { if (_nameToMethodDetails.TryGetValue(itemName, out var methodDetails)) { result = methodDetails.MethodInfo; return result != null; } } result = null; return _globalDefaultFactory?.TryGetDefinition(itemName, out result) ?? false; } public void RegisterNoParameters(string methodName, Func<LogEventInfo, object> noParameters, MethodInfo legacyMethodInfo = null) { lock (_nameToMethodDetails) { _nameToMethodDetails.TryGetValue(methodName, out var methodDetails); legacyMethodInfo = legacyMethodInfo ?? methodDetails.MethodInfo ?? noParameters.GetDelegateInfo(); _nameToMethodDetails[methodName] = new MethodDetails(legacyMethodInfo, noParameters, methodDetails.OneParameter, methodDetails.TwoParameters, methodDetails.ThreeParameters, methodDetails.ManyParameters, methodDetails.ManyParameterMinCount, methodDetails.ManyParameterMaxCount, methodDetails.ManyParameterWithLogEvent); } } public void RegisterOneParameter(string methodName, Func<LogEventInfo, object, object> oneParameter, MethodInfo legacyMethodInfo = null) { lock (_nameToMethodDetails) { _nameToMethodDetails.TryGetValue(methodName, out var methodDetails); legacyMethodInfo = legacyMethodInfo ?? methodDetails.MethodInfo ?? oneParameter.GetDelegateInfo(); _nameToMethodDetails[methodName] = new MethodDetails(legacyMethodInfo, methodDetails.NoParameters, oneParameter, methodDetails.TwoParameters, methodDetails.ThreeParameters, methodDetails.ManyParameters, methodDetails.ManyParameterMinCount, methodDetails.ManyParameterMaxCount, methodDetails.ManyParameterWithLogEvent); } } public void RegisterTwoParameters(string methodName, Func<LogEventInfo, object, object, object> twoParameters, MethodInfo legacyMethodInfo = null) { lock (_nameToMethodDetails) { _nameToMethodDetails.TryGetValue(methodName, out var methodDetails); legacyMethodInfo = legacyMethodInfo ?? methodDetails.MethodInfo ?? twoParameters.GetDelegateInfo(); _nameToMethodDetails[methodName] = new MethodDetails(legacyMethodInfo, methodDetails.NoParameters, methodDetails.OneParameter, twoParameters, methodDetails.ThreeParameters, methodDetails.ManyParameters, methodDetails.ManyParameterMinCount, methodDetails.ManyParameterMaxCount, methodDetails.ManyParameterWithLogEvent); } } public void RegisterThreeParameters(string methodName, Func<LogEventInfo, object, object, object, object> threeParameters, MethodInfo legacyMethodInfo = null) { lock (_nameToMethodDetails) { _nameToMethodDetails.TryGetValue(methodName, out var methodDetails); legacyMethodInfo = legacyMethodInfo ?? methodDetails.MethodInfo ?? threeParameters.GetDelegateInfo(); _nameToMethodDetails[methodName] = new MethodDetails(legacyMethodInfo, methodDetails.NoParameters, methodDetails.OneParameter, methodDetails.TwoParameters, threeParameters, methodDetails.ManyParameters, methodDetails.ManyParameterMinCount, methodDetails.ManyParameterMaxCount, methodDetails.ManyParameterWithLogEvent); } } public void RegisterManyParameters(string methodName, Func<object[], object> manyParameters, int manyParameterMinCount, int manyParameterMaxCount, bool manyParameterWithLogEvent, MethodInfo legacyMethodInfo = null) { lock (_nameToMethodDetails) { _nameToMethodDetails.TryGetValue(methodName, out var methodDetails); legacyMethodInfo = legacyMethodInfo ?? methodDetails.MethodInfo ?? manyParameters.GetDelegateInfo(); _nameToMethodDetails[methodName] = new MethodDetails(legacyMethodInfo, methodDetails.NoParameters, methodDetails.OneParameter, methodDetails.TwoParameters, methodDetails.ThreeParameters, manyParameters, manyParameterMinCount, manyParameterMaxCount, manyParameterWithLogEvent); } } public Func<LogEventInfo, object> TryCreateInstanceWithNoParameters(string methodName) { lock (_nameToMethodDetails) { if (_nameToMethodDetails.TryGetValue(methodName, out var methodDetails)) return methodDetails.NoParameters; else return null; } } public Func<LogEventInfo, object, object> TryCreateInstanceWithOneParameter(string methodName) { lock (_nameToMethodDetails) { if (_nameToMethodDetails.TryGetValue(methodName, out var methodDetails)) return methodDetails.OneParameter; else return null; } } public Func<LogEventInfo, object, object, object> TryCreateInstanceWithTwoParameters(string methodName) { lock (_nameToMethodDetails) { if (_nameToMethodDetails.TryGetValue(methodName, out var methodDetails)) return methodDetails.TwoParameters; else return null; } } public Func<LogEventInfo, object, object, object, object> TryCreateInstanceWithThreeParameters(string methodName) { lock (_nameToMethodDetails) { if (_nameToMethodDetails.TryGetValue(methodName, out var methodDetails)) return methodDetails.ThreeParameters; else return null; } } public Func<object[], object> TryCreateInstanceWithManyParameters(string methodName, out int manyParameterMinCount, out int manyParameterMaxCount, out bool manyParameterWithLogEvent) { lock (_nameToMethodDetails) { if (_nameToMethodDetails.TryGetValue(methodName, out var methodDetails)) { if (methodDetails.ManyParameters != null) { manyParameterMaxCount = methodDetails.ManyParameterMaxCount; manyParameterMinCount = methodDetails.ManyParameterMinCount; manyParameterWithLogEvent = methodDetails.ManyParameterWithLogEvent; return methodDetails.ManyParameters; } else if (methodDetails.ThreeParameters != null) { manyParameterMaxCount = 3; manyParameterMinCount = methodDetails.TwoParameters is null ? 3 : 2; manyParameterWithLogEvent = true; return new Func<object[], object>(args => methodDetails.ThreeParameters((LogEventInfo)args[0], args[1], args[2], args[3])); } else if (methodDetails.TwoParameters != null) { manyParameterMaxCount = 2; manyParameterMinCount = methodDetails.OneParameter is null ? 2 : 1; manyParameterWithLogEvent = true; return new Func<object[], object>(args => methodDetails.TwoParameters((LogEventInfo)args[0], args[1], args[2])); } else if (methodDetails.OneParameter != null) { manyParameterMaxCount = 1; manyParameterMinCount = methodDetails.NoParameters is null ? 1 : 0; manyParameterWithLogEvent = true; return new Func<object[], object>(args => methodDetails.OneParameter((LogEventInfo)args[0], args[1])); } else if (methodDetails.NoParameters != null) { manyParameterMaxCount = 0; manyParameterMinCount = 0; manyParameterWithLogEvent = true; return new Func<object[], object>(args => methodDetails.NoParameters((LogEventInfo)args[0])); } } manyParameterMinCount = 0; manyParameterMaxCount = 0; manyParameterWithLogEvent = false; return null; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Collections.Generic; namespace NLog.Internal { internal struct ScopeContextPropertyEnumerator<TValue> : IEnumerator<KeyValuePair<string, object>> { readonly IEnumerator<KeyValuePair<string, object>> _scopeEnumerator; #if !NET35 && !NET40 readonly IReadOnlyList<KeyValuePair<string, object>> _scopeList; int _scopeIndex; #endif Dictionary<string, object>.Enumerator _dicationaryEnumerator; public ScopeContextPropertyEnumerator(IEnumerable<KeyValuePair<string, TValue>> scopeProperties) { #if !NET35 && !NET40 if (scopeProperties is IReadOnlyList<KeyValuePair<string, object>> scopeList) { _scopeEnumerator = null; _scopeList = scopeList; _scopeIndex = -1; _dicationaryEnumerator = default(Dictionary<string, object>.Enumerator); return; } else { _scopeList = null; _scopeIndex = 0; } #endif if (scopeProperties is Dictionary<string, object> scopeDictionary) { _scopeEnumerator = null; _dicationaryEnumerator = scopeDictionary.GetEnumerator(); } else if (scopeProperties is IEnumerable<KeyValuePair<string, object>> scopeEnumerator) { _scopeEnumerator = scopeEnumerator.GetEnumerator(); _dicationaryEnumerator = default(Dictionary<string, object>.Enumerator); } else { _scopeEnumerator = CreateScopeEnumerable(scopeProperties).GetEnumerator(); _dicationaryEnumerator = default(Dictionary<string, object>.Enumerator); } } #if !NET35 && !NET40 public static void CopyScopePropertiesToDictionary(IReadOnlyCollection<KeyValuePair<string, TValue>> parentContext, Dictionary<string, object> scopeDictionary) { using (var propertyEnumerator = new ScopeContextPropertyEnumerator<TValue>(parentContext)) { while (propertyEnumerator.MoveNext()) { var item = propertyEnumerator.Current; scopeDictionary[item.Key] = item.Value; } } } #endif public static bool HasUniqueCollectionKeys(IEnumerable<KeyValuePair<string, TValue>> scopeProperties, IEqualityComparer<string> keyComparer) { int startIndex = 1; using (var leftEnumerator = new ScopeContextPropertyEnumerator<TValue>(scopeProperties)) { while (leftEnumerator.MoveNext()) { ++startIndex; int currentIndex = 0; var left = leftEnumerator.Current; using (var rightEnumerator = new ScopeContextPropertyEnumerator<TValue>(scopeProperties)) { while (rightEnumerator.MoveNext()) { if (++currentIndex < startIndex) continue; var right = rightEnumerator.Current; if (keyComparer.Equals(left.Key, right.Key)) { return false; } if (currentIndex > 10) { return false; // Too many comparisons } } } } } return true; } private static IEnumerable<KeyValuePair<string, object>> CreateScopeEnumerable(IEnumerable<KeyValuePair<string, TValue>> scopeProperties) { foreach (var property in scopeProperties) yield return new KeyValuePair<string, object>(property.Key, property.Value); } public KeyValuePair<string, object> Current { get { #if !NET35 && !NET40 if (_scopeList != null) { return _scopeList[_scopeIndex]; } else #endif if (_scopeEnumerator != null) { return _scopeEnumerator.Current; } else { return _dicationaryEnumerator.Current; } } } object System.Collections.IEnumerator.Current => Current; public void Dispose() { if (_scopeEnumerator != null) _scopeEnumerator.Dispose(); else #if !NET35 && !NET40 if (_scopeList is null) #endif _dicationaryEnumerator.Dispose(); } public bool MoveNext() { #if !NET35 && !NET40 if (_scopeList != null) { if (_scopeIndex < _scopeList.Count - 1) { ++_scopeIndex; return true; } return false; } else #endif if (_scopeEnumerator != null) { return _scopeEnumerator.MoveNext(); } else { return _dicationaryEnumerator.MoveNext(); } } public void Reset() { #if !NET35 && !NET40 if (_scopeList != null) { _scopeIndex = -1; } else #endif if (_scopeEnumerator != null) { _scopeEnumerator.Reset(); } else { _dicationaryEnumerator = default(Dictionary<string, object>.Enumerator); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.ComponentModel; using JetBrains.Annotations; /// <content> /// Auto-generated Logger members for binary compatibility with NLog 1.0. /// </content> public partial class Logger : ILogger { // the following code has been automatically generated by a PERL script #region Log() overloads /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="value">A <see langword="object" /> to be written.</param> [EditorBrowsable(EditorBrowsableState.Never)] public void Log(LogLevel level, object value) { if (IsEnabled(level)) { WriteToTargets(level, Factory.DefaultCultureInfo, value); } } /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">A <see langword="object" /> to be written.</param> [EditorBrowsable(EditorBrowsableState.Never)] public void Log(LogLevel level, IFormatProvider formatProvider, object value) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, value); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2) { if (IsEnabled(level)) { WriteToTargets(level, message, new[] { arg1, arg2 }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> /// <param name="arg3">Third argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2, object arg3) { if (IsEnabled(level)) { WriteToTargets(level, message, new[] { arg1, arg2, arg3 }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, string argument) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider formatProvider, string message, int argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, object argument) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified value as a parameter. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument }); } } #endregion #region Trace() overloads /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level. /// </summary> /// <param name="value">A <see langword="object" /> to be written.</param> [EditorBrowsable(EditorBrowsableState.Never)] public void Trace(object value) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, Factory.DefaultCultureInfo, value); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">A <see langword="object" /> to be written.</param> [EditorBrowsable(EditorBrowsableState.Never)] public void Trace(IFormatProvider formatProvider, object value) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, value); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, message, new[] { arg1, arg2 }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> /// <param name="arg3">Third argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2, object arg3) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, message, new[] { arg1, arg2, arg3 }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, string argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider formatProvider, string message, int argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, object argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, message, new object[] { argument }); } } #endregion #region Debug() overloads /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// </summary> /// <param name="value">A <see langword="object" /> to be written.</param> [EditorBrowsable(EditorBrowsableState.Never)] public void Debug(object value) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, Factory.DefaultCultureInfo, value); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">A <see langword="object" /> to be written.</param> [EditorBrowsable(EditorBrowsableState.Never)] public void Debug(IFormatProvider formatProvider, object value) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, value); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, message, new[] { arg1, arg2 }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> /// <param name="arg3">Third argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2, object arg3) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, message, new[] { arg1, arg2, arg3 }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, string argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, object argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, message, new object[] { argument }); } } #endregion #region Info() overloads /// <summary> /// Writes the diagnostic message at the <c>Info</c> level. /// </summary> /// <param name="value">A <see langword="object" /> to be written.</param> [EditorBrowsable(EditorBrowsableState.Never)] public void Info(object value) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, Factory.DefaultCultureInfo, value); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">A <see langword="object" /> to be written.</param> [EditorBrowsable(EditorBrowsableState.Never)] public void Info(IFormatProvider formatProvider, object value) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, value); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, message, new[] { arg1, arg2 }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> /// <param name="arg3">Third argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2, object arg3) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, message, new[] { arg1, arg2, arg3 }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, string argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, object argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, message, new object[] { argument }); } } #endregion #region Warn() overloads /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level. /// </summary> /// <param name="value">A <see langword="object" /> to be written.</param> [EditorBrowsable(EditorBrowsableState.Never)] public void Warn(object value) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, Factory.DefaultCultureInfo, value); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">A <see langword="object" /> to be written.</param> [EditorBrowsable(EditorBrowsableState.Never)] public void Warn(IFormatProvider formatProvider, object value) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, value); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, message, new[] { arg1, arg2 }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> /// <param name="arg3">Third argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2, object arg3) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, message, new[] { arg1, arg2, arg3 }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, string argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, object argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, message, new object[] { argument }); } } #endregion #region Error() overloads /// <summary> /// Writes the diagnostic message at the <c>Error</c> level. /// </summary> /// <param name="value">A <see langword="object" /> to be written.</param> [EditorBrowsable(EditorBrowsableState.Never)] public void Error(object value) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, Factory.DefaultCultureInfo, value); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">A <see langword="object" /> to be written.</param> [EditorBrowsable(EditorBrowsableState.Never)] public void Error(IFormatProvider formatProvider, object value) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, value); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, message, new[] { arg1, arg2 }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> /// <param name="arg3">Third argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2, object arg3) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, message, new[] { arg1, arg2, arg3 }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, string argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, object argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, message, new object[] { argument }); } } #endregion #region Fatal() overloads /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level. /// </summary> /// <param name="value">A <see langword="object" /> to be written.</param> [EditorBrowsable(EditorBrowsableState.Never)] public void Fatal(object value) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, Factory.DefaultCultureInfo, value); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">A <see langword="object" /> to be written.</param> [EditorBrowsable(EditorBrowsableState.Never)] public void Fatal(IFormatProvider formatProvider, object value) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, value); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, message, new[] { arg1, arg2 }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> /// <param name="arg3">Third argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2, object arg3) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, message, new[] { arg1, arg2, arg3 }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, string argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, object argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified value as a parameter. /// </summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, message, new object[] { argument }); } } #endregion // end of generated code void ILoggerBase.LogException(LogLevel level, [Localizable(false)] string message, Exception exception) { Log(level, exception, message, NLog.Internal.ArrayHelper.Empty<object>()); } void ILoggerBase.Log(LogLevel level, [Localizable(false)] string message, Exception exception) { Log(level, exception, message, NLog.Internal.ArrayHelper.Empty<object>()); } /// <inheritdoc/> [Obsolete("Use Trace(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] public void TraceException([Localizable(false)] string message, Exception exception) { Trace(exception, message); } void ILogger.Trace([Localizable(false)] string message, Exception exception) { Trace(exception, message); } /// <inheritdoc/> [Obsolete("Use Debug(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] public void DebugException([Localizable(false)] string message, Exception exception) { Debug(exception, message); } void ILogger.Debug([Localizable(false)] string message, Exception exception) { Debug(exception, message); } /// <inheritdoc/> [Obsolete("Use Info(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] public void InfoException([Localizable(false)] string message, Exception exception) { Info(exception, message); } void ILogger.Info([Localizable(false)] string message, Exception exception) { Info(exception, message); } /// <inheritdoc/> [Obsolete("Use Warn(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] public void WarnException([Localizable(false)] string message, Exception exception) { Warn(exception, message); } void ILogger.Warn([Localizable(false)] string message, Exception exception) { Warn(exception, message); } /// <inheritdoc/> [Obsolete("Use Error(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] public void ErrorException([Localizable(false)] string message, Exception exception) { Error(exception, message); } void ILogger.Error([Localizable(false)] string message, Exception exception) { Error(exception, message); } /// <inheritdoc/> [Obsolete("Use Fatal(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] public void FatalException([Localizable(false)] string message, Exception exception) { Fatal(exception, message); } void ILogger.Fatal([Localizable(false)] string message, Exception exception) { Fatal(exception, message); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using NLog.Config; using NLog.Layouts; namespace NLog.Internal { [DebuggerDisplay("Count = {Count}")] internal class ConfigVariablesDictionary : IDictionary<string, Layout> { private readonly ThreadSafeDictionary<string, Layout> _variables = new ThreadSafeDictionary<string, Layout>(StringComparer.OrdinalIgnoreCase); private readonly LoggingConfiguration _configuration; private ThreadSafeDictionary<string, Layout> _dynamicVariables; private ThreadSafeDictionary<string, bool> _apiVariables; public ConfigVariablesDictionary(LoggingConfiguration configuration) { _configuration = configuration; } public void InsertParsedConfigVariable(string key, Layout value, bool keepVariablesOnReload) { if (keepVariablesOnReload && _apiVariables?.ContainsKey(key)==true && _variables.ContainsKey(key)) return; _variables[key] = value; _dynamicVariables?.Remove(key); } public bool TryLookupDynamicVariable(string key, out Layout dynamicLayout) { if (_dynamicVariables is null) { if (!_variables.TryGetValue(key, out dynamicLayout)) return false; System.Threading.Interlocked.CompareExchange(ref _dynamicVariables, new ThreadSafeDictionary<string, Layout>(_variables.Comparer), null); } bool variableExists = true; if (!_dynamicVariables.TryGetValue(key, out dynamicLayout)) { variableExists = false; if (_variables.TryGetValue(key, out dynamicLayout)) { variableExists = true; if (dynamicLayout != null) { dynamicLayout.Initialize(_configuration); } _dynamicVariables[key] = dynamicLayout; } } return variableExists; } public void PrepareForReload(ConfigVariablesDictionary oldVariables) { if (oldVariables._apiVariables != null) { foreach (var item in oldVariables._apiVariables) { if (oldVariables._variables.TryGetValue(item.Key, out var value)) { _variables[item.Key] = value; // Reload will close the old-config and initialize the new-config (disconnects layout from old-config) RegisterApiVariable(item.Key); } } } } public int Count => _variables.Count; public ICollection<string> Keys => _variables.Keys; public ICollection<Layout> Values => _variables.Values; public bool ContainsKey(string key) => _variables.ContainsKey(key); public bool TryGetValue(string key, out Layout value) => _variables.TryGetValue(key, out value); IEnumerator<KeyValuePair<string, Layout>> IEnumerable<KeyValuePair<string, Layout>>.GetEnumerator() => _variables.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _variables.GetEnumerator(); public ThreadSafeDictionary<string, Layout>.Enumerator GetEnumerator() => _variables.GetEnumerator(); public Layout this[string key] { get { return _variables[key]; } set { _variables[key] = value; RegisterApiVariable(key); } } public void Add(string key, Layout value) { _variables.Add(key, value); RegisterApiVariable(key); } public bool Remove(string key) { _apiVariables?.Remove(key); _dynamicVariables?.Remove(key); return _variables.Remove(key); } public void Clear() { _variables.Clear(); _apiVariables?.Clear(); _dynamicVariables?.Clear(); } bool ICollection<KeyValuePair<string, Layout>>.IsReadOnly => false; bool ICollection<KeyValuePair<string, Layout>>.Contains(KeyValuePair<string, Layout> item) => _variables.Contains(item); void ICollection<KeyValuePair<string, Layout>>.CopyTo(KeyValuePair<string, Layout>[] array, int arrayIndex) => _variables.CopyTo(array, arrayIndex); void ICollection<KeyValuePair<string, Layout>>.Add(KeyValuePair<string, Layout> item) => Add(item.Key, item.Value); bool ICollection<KeyValuePair<string, Layout>>.Remove(KeyValuePair<string, Layout> item) => Remove(item.Key); private void RegisterApiVariable(string key) { if (_apiVariables is null) { System.Threading.Interlocked.CompareExchange(ref _apiVariables, new ThreadSafeDictionary<string, bool>(_variables.Comparer), null); } _apiVariables[key] = true; _dynamicVariables?.Remove(key); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Conditions { using System; using System.Text; using NLog.Internal; /// <summary> /// Hand-written tokenizer for conditions. /// </summary> internal sealed class ConditionTokenizer { private static readonly ConditionTokenType[] CharIndexToTokenType = BuildCharIndexToTokenType(); private readonly SimpleStringReader _stringReader; /// <summary> /// Initializes a new instance of the <see cref="ConditionTokenizer"/> class. /// </summary> /// <param name="stringReader">The string reader.</param> public ConditionTokenizer(SimpleStringReader stringReader) { _stringReader = stringReader; TokenType = ConditionTokenType.BeginningOfInput; GetNextToken(); } /// <summary> /// Gets the type of the token. /// </summary> /// <value>The type of the token.</value> public ConditionTokenType TokenType { get; private set; } /// <summary> /// Gets the token value. /// </summary> /// <value>The token value.</value> public string TokenValue { get; private set; } /// <summary> /// Gets the value of a string token. /// </summary> /// <value>The string token value.</value> public string StringTokenValue { get { string s = TokenValue; return s.Substring(1, s.Length - 2).Replace("''", "'"); } } /// <summary> /// Asserts current token type and advances to the next token. /// </summary> /// <param name="tokenType">Expected token type.</param> /// <remarks>If token type doesn't match, an exception is thrown.</remarks> public void Expect(ConditionTokenType tokenType) { if (TokenType != tokenType) { throw new ConditionParseException($"Expected token of type: {tokenType}, got {TokenType} ({TokenValue})."); } GetNextToken(); } /// <summary> /// Asserts that current token is a keyword and returns its value and advances to the next token. /// </summary> /// <returns>Keyword value.</returns> public string EatKeyword() { if (TokenType != ConditionTokenType.Keyword) { throw new ConditionParseException("Identifier expected"); } string s = TokenValue; GetNextToken(); return s; } /// <summary> /// Gets or sets a value indicating whether current keyword is equal to the specified value. /// </summary> /// <param name="keyword">The keyword.</param> /// <returns> /// A value of <c>true</c> if current keyword is equal to the specified value; otherwise, <c>false</c>. /// </returns> public bool IsKeyword(string keyword) { if (TokenType != ConditionTokenType.Keyword) { return false; } return TokenValue.Equals(keyword, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Gets or sets a value indicating whether the tokenizer has reached the end of the token stream. /// </summary> /// <returns> /// A value of <c>true</c> if the tokenizer has reached the end of the token stream; otherwise, <c>false</c>. /// </returns> public bool IsEOF() { return TokenType == ConditionTokenType.EndOfInput; } /// <summary> /// Gets or sets a value indicating whether current token is a number. /// </summary> /// <returns> /// A value of <c>true</c> if current token is a number; otherwise, <c>false</c>. /// </returns> public bool IsNumber() { return TokenType == ConditionTokenType.Number; } /// <summary> /// Gets or sets a value indicating whether the specified token is of specified type. /// </summary> /// <param name="tokenType">The token type.</param> /// <returns> /// A value of <c>true</c> if current token is of specified type; otherwise, <c>false</c>. /// </returns> public bool IsToken(ConditionTokenType tokenType) { return TokenType == tokenType; } /// <summary> /// Gets the next token and sets <see cref="TokenType"/> and <see cref="TokenValue"/> properties. /// </summary> public void GetNextToken() { if (TokenType == ConditionTokenType.EndOfInput) { throw new ConditionParseException("Cannot read past end of stream."); } SkipWhitespace(); int i = PeekChar(); if (i == -1) { TokenType = ConditionTokenType.EndOfInput; return; } char ch = (char)i; if (char.IsDigit(ch)) { ParseNumber(ch); return; } if (ch == '\'') { ParseSingleQuotedString(ch); return; } if (ch == '_' || char.IsLetter(ch)) { ParseKeyword(ch); return; } if (ch == '}' || ch == ':') { // when condition is embedded TokenType = ConditionTokenType.EndOfInput; return; } TokenValue = ch.ToString(); var success = TryGetComparisonToken(ch); if (success) return; success = TryGetLogicalToken(ch); if (success) return; if (ch >= 32 && ch < 128) { ConditionTokenType tt = CharIndexToTokenType[ch]; if (tt != ConditionTokenType.Invalid) { TokenType = tt; TokenValue = new string(ch, 1); ReadChar(); return; } throw new ConditionParseException($"Invalid punctuation: {ch}"); } throw new ConditionParseException($"Invalid token: {ch}"); } /// <summary> /// Try the comparison tokens (greater, smaller, greater-equals, smaller-equals) /// </summary> /// <param name="ch">current char</param> /// <returns>is match</returns> private bool TryGetComparisonToken(char ch) { if (ch == '<') { ReadChar(); int nextChar = PeekChar(); if (nextChar == '>') { TokenType = ConditionTokenType.NotEqual; TokenValue = "<>"; ReadChar(); return true; } if (nextChar == '=') { TokenType = ConditionTokenType.LessThanOrEqualTo; TokenValue = "<="; ReadChar(); return true; } TokenType = ConditionTokenType.LessThan; TokenValue = "<"; return true; } if (ch == '>') { ReadChar(); int nextChar = PeekChar(); if (nextChar == '=') { TokenType = ConditionTokenType.GreaterThanOrEqualTo; TokenValue = ">="; ReadChar(); return true; } TokenType = ConditionTokenType.GreaterThan; TokenValue = ">"; return true; } return false; } /// <summary> /// Try the logical tokens (and, or, not, equals) /// </summary> /// <param name="ch">current char</param> /// <returns>is match</returns> private bool TryGetLogicalToken(char ch) { if (ch == '!') { ReadChar(); int nextChar = PeekChar(); if (nextChar == '=') { TokenType = ConditionTokenType.NotEqual; TokenValue = "!="; ReadChar(); return true; } TokenType = ConditionTokenType.Not; TokenValue = "!"; return true; } if (ch == '&') { ReadChar(); int nextChar = PeekChar(); if (nextChar == '&') { TokenType = ConditionTokenType.And; TokenValue = "&&"; ReadChar(); return true; } throw new ConditionParseException("Expected '&&' but got '&'"); } if (ch == '|') { ReadChar(); int nextChar = PeekChar(); if (nextChar == '|') { TokenType = ConditionTokenType.Or; TokenValue = "||"; ReadChar(); return true; } throw new ConditionParseException("Expected '||' but got '|'"); } if (ch == '=') { ReadChar(); int nextChar = PeekChar(); if (nextChar == '=') { TokenType = ConditionTokenType.EqualTo; TokenValue = "=="; ReadChar(); return true; } TokenType = ConditionTokenType.EqualTo; TokenValue = "="; return true; } return false; } private static ConditionTokenType[] BuildCharIndexToTokenType() { CharToTokenType[] charToTokenType = { new CharToTokenType('(', ConditionTokenType.LeftParen), new CharToTokenType(')', ConditionTokenType.RightParen), new CharToTokenType('.', ConditionTokenType.Dot), new CharToTokenType(',', ConditionTokenType.Comma), new CharToTokenType('!', ConditionTokenType.Not), new CharToTokenType('-', ConditionTokenType.Minus), }; var result = new ConditionTokenType[128]; for (int i = 0; i < 128; ++i) { result[i] = ConditionTokenType.Invalid; } foreach (CharToTokenType cht in charToTokenType) { result[cht.Character] = cht.TokenType; } return result; } private void ParseSingleQuotedString(char ch) { int i; TokenType = ConditionTokenType.String; StringBuilder sb = new StringBuilder(); sb.Append(ch); ReadChar(); while ((i = PeekChar()) != -1) { ch = (char)i; sb.Append((char)ReadChar()); if (ch == '\'') { if (PeekChar() == '\'') { sb.Append('\''); ReadChar(); } else { break; } } } if (i == -1) { throw new ConditionParseException("String literal is missing a closing quote character."); } TokenValue = sb.ToString(); } private void ParseKeyword(char ch) { int i; TokenType = ConditionTokenType.Keyword; StringBuilder sb = new StringBuilder(); sb.Append(ch); ReadChar(); while ((i = PeekChar()) != -1) { if ((char)i == '_' || (char)i == '-' || char.IsLetterOrDigit((char)i)) { sb.Append((char)ReadChar()); } else { break; } } TokenValue = sb.ToString(); } private void ParseNumber(char ch) { int i; TokenType = ConditionTokenType.Number; StringBuilder sb = new StringBuilder(); sb.Append(ch); ReadChar(); while ((i = PeekChar()) != -1) { ch = (char)i; if (char.IsDigit(ch) || (ch == '.')) { sb.Append((char)ReadChar()); } else { break; } } TokenValue = sb.ToString(); } private void SkipWhitespace() { int ch; while ((ch = PeekChar()) != -1) { if (!char.IsWhiteSpace((char)ch)) { break; } ReadChar(); } } private int PeekChar() { return _stringReader.Peek(); } private int ReadChar() { return _stringReader.Read(); } /// <summary> /// Mapping between characters and token types for punctuations. /// </summary> private struct CharToTokenType { public readonly char Character; public readonly ConditionTokenType TokenType; /// <summary> /// Initializes a new instance of the CharToTokenType struct. /// </summary> /// <param name="character">The character.</param> /// <param name="tokenType">Type of the token.</param> public CharToTokenType(char character, ConditionTokenType tokenType) { Character = character; TokenType = tokenType; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Reflection; using NLog.Common; using NLog.Config; using NLog.Internal; /// <summary> /// Calls the specified static method on each log message and passes contextual parameters to it. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/MethodCall-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/MethodCall-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/MethodCall/NLog.config" /> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/MethodCall/Simple/Example.cs" /> /// </example> [Target("MethodCall")] public sealed class MethodCallTarget : MethodCallTargetBase { /// <summary> /// Gets or sets the class name. /// </summary> /// <docgen category='Invocation Options' order='10' /> public string ClassName { get; set; } /// <summary> /// Gets or sets the method name. The method must be public and static. /// /// Use the AssemblyQualifiedName , https://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname(v=vs.110).aspx /// e.g. /// </summary> /// <docgen category='Invocation Options' order='10' /> public string MethodName { get; set; } Action<LogEventInfo, object[]> _logEventAction; /// <summary> /// Initializes a new instance of the <see cref="MethodCallTarget" /> class. /// </summary> public MethodCallTarget() : base() { } /// <summary> /// Initializes a new instance of the <see cref="MethodCallTarget" /> class. /// </summary> /// <param name="name">Name of the target.</param> public MethodCallTarget(string name) : this(name, null) { } /// <summary> /// Initializes a new instance of the <see cref="MethodCallTarget" /> class. /// </summary> /// <param name="name">Name of the target.</param> /// <param name="logEventAction">Method to call on logevent.</param> public MethodCallTarget(string name, Action<LogEventInfo, object[]> logEventAction) : this() { Name = name; _logEventAction = logEventAction; } /// <inheritdoc/> protected override void InitializeTarget() { base.InitializeTarget(); if (!string.IsNullOrEmpty(ClassName) && !string.IsNullOrEmpty(MethodName)) { _logEventAction = BuildLogEventAction(ClassName, MethodName); } else if (_logEventAction is null) { throw new NLogConfigurationException($"MethodCallTarget: Missing configuration of ClassName and MethodName"); } } [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming - Allow method lookup from config", "IL2075")] private static Action<LogEventInfo, object[]> BuildLogEventAction(string className, string methodName) { var targetType = PropertyTypeConverter.ConvertToType(className.Trim(), false); if (targetType is null) { throw new NLogConfigurationException($"MethodCallTarget: failed to get type from ClassName={className}"); } else { var methodInfo = targetType.GetMethod(methodName); if (methodInfo is null) { throw new NLogConfigurationException($"MethodCallTarget: MethodName={methodName} not found in ClassName={className} - and must be static method"); } else if (!methodInfo.IsStatic) { throw new NLogConfigurationException($"MethodCallTarget: MethodName={methodName} found in ClassName={className} - but not static method"); } else { return BuildLogEventAction(methodInfo); } } } private static Action<LogEventInfo, object[]> BuildLogEventAction(MethodInfo methodInfo) { var neededParameters = methodInfo.GetParameters().Length; ReflectionHelpers.LateBoundMethod lateBoundMethod = null; return (logEvent, parameters) => { var missingParameters = neededParameters - parameters.Length; if (missingParameters > 0) { //fill missing parameters with Type.Missing var newParams = new object[neededParameters]; for (int i = 0; i < parameters.Length; ++i) newParams[i] = parameters[i]; for (int i = parameters.Length; i < neededParameters; ++i) newParams[i] = Type.Missing; parameters = newParams; methodInfo.Invoke(null, parameters); } else if (parameters.Length != neededParameters && neededParameters != 0) { methodInfo.Invoke(null, parameters); } else { parameters = neededParameters == 0 ? ArrayHelper.Empty<object>() : parameters; if (lateBoundMethod is null) lateBoundMethod = CreateFastInvoke(methodInfo, parameters) ?? CreateNormalInvoke(methodInfo, parameters); else lateBoundMethod.Invoke(null, parameters); } }; } private static ReflectionHelpers.LateBoundMethod CreateFastInvoke(MethodInfo methodInfo, object[] parameters) { try { var lateBoundMethod = ReflectionHelpers.CreateLateBoundMethod(methodInfo); lateBoundMethod.Invoke(null, parameters); return lateBoundMethod; } catch (Exception ex) { InternalLogger.Warn(ex, "MethodCallTarget: Failed to create expression method {0} - {1}", methodInfo.Name, ex.Message); return null; } } private static ReflectionHelpers.LateBoundMethod CreateNormalInvoke(MethodInfo methodInfo, object[] parameters) { ReflectionHelpers.LateBoundMethod reflectionMethod = (target, args) => methodInfo.Invoke(null, args); try { reflectionMethod.Invoke(null, parameters); return reflectionMethod; } catch (Exception ex) { InternalLogger.Warn(ex, "MethodCallTarget: Failed to invoke reflection method {0} - {1}", methodInfo.Name, ex.Message); return reflectionMethod; } } /// <summary> /// Calls the specified Method. /// </summary> /// <param name="parameters">Method parameters.</param> /// <param name="logEvent">The logging event.</param> protected override void DoInvoke(object[] parameters, AsyncLogEventInfo logEvent) { try { ExecuteLogMethod(parameters, logEvent.LogEvent); logEvent.Continuation(null); } catch (Exception ex) { if (ExceptionMustBeRethrown(ex)) { throw; } logEvent.Continuation(ex); } } /// <summary> /// Calls the specified Method. /// </summary> /// <param name="parameters">Method parameters.</param> protected override void DoInvoke(object[] parameters) { ExecuteLogMethod(parameters, null); } private void ExecuteLogMethod(object[] parameters, LogEventInfo logEvent) { if (_logEventAction is null) { InternalLogger.Trace("{0}: No invoke because class/method was not found or set", this); } else { try { _logEventAction.Invoke(logEvent, parameters); } catch (TargetInvocationException ex) { InternalLogger.Warn("{0}: Failed to invoke method - {1}", this, ex.Message); throw ex.InnerException; } } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections.Generic; using System.Globalization; using System.Text; using JetBrains.Annotations; using MessageTemplates; using NLog.Config; internal sealed class LogMessageTemplateFormatter : ILogMessageFormatter { private static readonly StringBuilderPool _builderPool = new StringBuilderPool(Environment.ProcessorCount * 2); private readonly IServiceProvider _serviceProvider; private IValueFormatter ValueFormatter => _valueFormatter ?? (_valueFormatter = _serviceProvider.GetService<IValueFormatter>()); private IValueFormatter _valueFormatter; /// <summary> /// When true: Do not fallback to StringBuilder.Format for positional templates /// </summary> private readonly bool _forceTemplateRenderer; private readonly bool _singleTargetOnly; /// <summary> /// New formatter /// </summary> /// <param name="serviceProvider"></param> /// <param name="forceTemplateRenderer">When true: Do not fallback to StringBuilder.Format for positional templates</param> /// <param name="singleTargetOnly"></param> public LogMessageTemplateFormatter([NotNull] IServiceProvider serviceProvider, bool forceTemplateRenderer, bool singleTargetOnly) { _serviceProvider = serviceProvider; _forceTemplateRenderer = forceTemplateRenderer; _singleTargetOnly = singleTargetOnly; MessageFormatter = FormatMessage; } /// <summary> /// The MessageFormatter delegate /// </summary> public LogMessageFormatter MessageFormatter { get; } public bool? MessageTemplateParser => _forceTemplateRenderer ? true : default(bool?); /// <inheritDoc/> public bool HasProperties(LogEventInfo logEvent) { if (!LogMessageStringFormatter.HasParameters(logEvent)) return false; if (_singleTargetOnly) { // Perform quick check for valid message template parameter names (No support for rewind if mixed message-template) TemplateEnumerator holeEnumerator = new TemplateEnumerator(logEvent.Message); if (holeEnumerator.MoveNext() && holeEnumerator.Current.MaybePositionalTemplate) { return false; // Skip allocation of PropertiesDictionary } } return true; // Parse message template and allocate PropertiesDictionary } public void AppendFormattedMessage(LogEventInfo logEvent, StringBuilder builder) { if (_singleTargetOnly) { Render(logEvent.Message, logEvent.FormatProvider ?? CultureInfo.CurrentCulture, logEvent.Parameters, builder, out _); } else { builder.Append(logEvent.FormattedMessage); } } public string FormatMessage(LogEventInfo logEvent) { if (LogMessageStringFormatter.HasParameters(logEvent)) { using (var builder = _builderPool.Acquire()) { AppendToBuilder(logEvent, builder.Item); return builder.Item.ToString(); } } return logEvent.Message; } private void AppendToBuilder(LogEventInfo logEvent, StringBuilder builder) { Render(logEvent.Message, logEvent.FormatProvider ?? CultureInfo.CurrentCulture, logEvent.Parameters, builder, out var messageTemplateParameterList); logEvent.CreateOrUpdatePropertiesInternal(false, messageTemplateParameterList ?? ArrayHelper.Empty<MessageTemplateParameter>()); } /// <summary> /// Render a template to a string. /// </summary> /// <param name="template">The template.</param> /// <param name="formatProvider">Culture.</param> /// <param name="parameters">Parameters for the holes.</param> /// <param name="sb">The String Builder destination.</param> /// <param name="messageTemplateParameters">Parameters for the holes.</param> private void Render(string template, IFormatProvider formatProvider, object[] parameters, StringBuilder sb, out IList<MessageTemplateParameter> messageTemplateParameters) { int pos = 0; int holeIndex = 0; int holeStartPosition = 0; messageTemplateParameters = null; int originalLength = sb.Length; TemplateEnumerator templateEnumerator = new TemplateEnumerator(template); while (templateEnumerator.MoveNext()) { if (holeIndex == 0 && !_forceTemplateRenderer && templateEnumerator.Current.MaybePositionalTemplate && sb.Length == originalLength) { // Not a structured template sb.AppendFormat(formatProvider, template, parameters); return; } var literal = templateEnumerator.Current.Literal; sb.Append(template, pos, literal.Print); pos += literal.Print; if (literal.Skip == 0) { pos++; } else { pos += literal.Skip; var hole = templateEnumerator.Current.Hole; if (hole.Alignment != 0) holeStartPosition = sb.Length; if (hole.Index != -1 && messageTemplateParameters is null) { holeIndex++; RenderHole(sb, hole, formatProvider, parameters[hole.Index], true); } else { var holeParameter = parameters[holeIndex]; if (messageTemplateParameters is null) { messageTemplateParameters = new MessageTemplateParameter[parameters.Length]; if (holeIndex != 0) { // rewind and try again templateEnumerator = new TemplateEnumerator(template); sb.Length = originalLength; holeIndex = 0; pos = 0; continue; } } messageTemplateParameters[holeIndex++] = new MessageTemplateParameter(hole.Name, holeParameter, hole.Format, hole.CaptureType); RenderHole(sb, hole, formatProvider, holeParameter); } if (hole.Alignment != 0) RenderPadding(sb, hole.Alignment, holeStartPosition); } } if (messageTemplateParameters != null && holeIndex != messageTemplateParameters.Count) { var truncateParameters = new MessageTemplateParameter[holeIndex]; for (int i = 0; i < truncateParameters.Length; ++i) truncateParameters[i] = messageTemplateParameters[i]; messageTemplateParameters = truncateParameters; } } private void RenderHole(StringBuilder sb, Hole hole, IFormatProvider formatProvider, object value, bool legacy = false) { RenderHole(sb, hole.CaptureType, hole.Format, formatProvider, value, legacy); } private void RenderHole(StringBuilder sb, CaptureType captureType, string holeFormat, IFormatProvider formatProvider, object value, bool legacy = false) { if (value is null) { sb.Append("NULL"); return; } if (captureType == CaptureType.Normal && legacy) { MessageTemplates.ValueFormatter.FormatToString(value, holeFormat, formatProvider, sb); } else { ValueFormatter.FormatValue(value, holeFormat, captureType, formatProvider, sb); } } private static void RenderPadding(StringBuilder sb, int holeAlignment, int holeStartPosition) { int holeWidth = sb.Length - holeStartPosition; int holePadding = Math.Abs(holeAlignment) - holeWidth; if (holePadding > 0) { if (holeAlignment < 0 || holeWidth == 0) { sb.Append(' ', holePadding); } else { string holeFormatVaue = sb.ToString(holeStartPosition, holeWidth); sb.Length = holeStartPosition; sb.Append(' ', holePadding); sb.Append(holeFormatVaue); } } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using NLog.Config; using NLog.Layouts; using NLog.Targets; using NLog.Targets.Wrappers; using NLog.Time; using NSubstitute; using Xunit; public class FileTargetTests : NLogTestBase { private readonly Logger logger = LogManager.GetLogger("NLog.UnitTests.Targets.FileTargetTests"); public static IEnumerable<object[]> SimpleFileTest_TestParameters { get { var booleanValues = new[] { true, false }; return from concurrentWrites in booleanValues from keepFileOpen in booleanValues from networkWrites in booleanValues from forceMutexConcurrentWrites in booleanValues where UniqueBaseAppender(concurrentWrites, keepFileOpen, networkWrites, forceMutexConcurrentWrites) from forceManaged in booleanValues select new object[] { concurrentWrites, keepFileOpen, networkWrites, forceManaged, forceMutexConcurrentWrites }; } } private static bool UniqueBaseAppender(bool concurrentWrites, bool keepFileOpen, bool networkWrites, bool forceMutexConcurrentWrites) { if (networkWrites && !keepFileOpen && !concurrentWrites && !forceMutexConcurrentWrites) return true; if (concurrentWrites && !networkWrites && !keepFileOpen && !forceMutexConcurrentWrites) return true; if (keepFileOpen && !networkWrites && !forceMutexConcurrentWrites) return true; return false; } [Fact] public void SetupBuilder_WriteToFile() { var tempDir = Path.Combine(Path.GetTempPath(), "nlog_" + Guid.NewGuid().ToString()); LogFactory logFactory = null; try { logFactory = new LogFactory().Setup().LoadConfiguration(c => { c.ForLogger().WriteToFile(Path.Combine(tempDir, "${logger}.txt"), "${message}", Encoding.UTF8, LineEndingMode.LF); }).LogFactory; logFactory.GetLogger("SetupBuilder").Info("Hello"); AssertFileContents(Path.Combine(tempDir, "SetupBuilder.txt"), "Hello\n", Encoding.UTF8); } finally { logFactory?.Shutdown(); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Theory] [MemberData(nameof(SimpleFileTest_TestParameters))] public void SimpleFileTest(bool concurrentWrites, bool keepFileOpen, bool networkWrites, bool forceManaged, bool forceMutexConcurrentWrites) { var logFile = Path.GetTempFileName(); try { var fileTarget = new FileTarget { FileName = SimpleLayout.Escape(logFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", OpenFileCacheTimeout = 0, ConcurrentWrites = concurrentWrites, KeepFileOpen = keepFileOpen, NetworkWrites = networkWrites, ForceManaged = forceManaged, ForceMutexConcurrentWrites = forceMutexConcurrentWrites, }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; // Flush AssertFileContents(logFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } finally { if (File.Exists(logFile)) File.Delete(logFile); } } [Theory] [MemberData(nameof(SimpleFileTest_TestParameters))] public void SimpleFileDeleteTest(bool concurrentWrites, bool keepFileOpen, bool networkWrites, bool forceManaged, bool forceMutexConcurrentWrites) { bool isSimpleKeepFileOpen = keepFileOpen && !networkWrites && !concurrentWrites #if !NETSTANDARD && !MONO && IsLinux() #endif ; #if MONO if (IsLinux() && concurrentWrites && keepFileOpen && !networkWrites) { Console.WriteLine("[SKIP] FileTargetTests.SimpleFileDeleteTest Not supported on MONO on Travis, because of FileSystemWatcher not working"); return; } #endif foreach (var archiveSameFolder in new[] { true, false }) { RetryingIntegrationTest(3, () => { var logPath = Path.Combine(Path.GetTempPath(), "nlog_" + Guid.NewGuid().ToString(), "Archive"); var logFile = Path.GetFullPath(Path.Combine(logPath, "..", "nlogA.txt")); //var arhiveFile = archiveSameFolder ? Path.GetFullPath(Path.Combine(logPath, "..", "nlogB.txt")) : Path.GetFullPath(Path.Combine(logPath, "nlogB.txt")); var arhiveFile = Path.GetFullPath(Path.Combine(logPath, archiveSameFolder ? ".." : ".", "nlogB.txt")); try { var fileTarget = new FileTarget { FileName = SimpleLayout.Escape(logFile), ArchiveFileName = SimpleLayout.Escape(arhiveFile), ArchiveEvery = FileArchivePeriod.Year, LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", OpenFileCacheTimeout = 0, EnableFileDelete = true, ConcurrentWrites = concurrentWrites, KeepFileOpen = keepFileOpen, NetworkWrites = networkWrites, ForceManaged = forceManaged, ForceMutexConcurrentWrites = forceMutexConcurrentWrites, ArchiveAboveSize = archiveSameFolder ? 1000000 : 0, }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("aaa"); LogManager.Flush(); Directory.CreateDirectory(Path.GetDirectoryName(arhiveFile)); File.Move(logFile, arhiveFile); if (isSimpleKeepFileOpen) Thread.Sleep(1500); // Ensure EnableFileDeleteSimpleMonitor will trigger else if (keepFileOpen && !networkWrites) Thread.Sleep(150); // Allow AutoClose-Timer-Thread to react (FileWatcher schedules timer after 50 msec) logger.Info("bbb"); LogManager.Configuration = null; AssertFileContents(logFile, "Info bbb\n", Encoding.UTF8); } finally { if (File.Exists(arhiveFile)) { File.Delete(arhiveFile); } if (File.Exists(logFile)) { File.Delete(logFile); } if (Directory.Exists(Path.GetDirectoryName(arhiveFile))) { Directory.Delete(Path.GetDirectoryName(arhiveFile)); } if (Directory.Exists(Path.GetDirectoryName(logFile))) { Directory.Delete(Path.GetDirectoryName(logFile)); } } }); } } /// <summary> /// There was a bug when creating the file in the root. /// /// Please note that this test can fail because the unit test doesn't have write access in the root. /// </summary> [Fact] public void SimpleFileTestInRoot() { if (NLog.Internal.PlatformDetector.IsWin32) { var dirPath = "C:\\"; var directoryInfo = new DirectoryInfo(dirPath); if (directoryInfo.Exists) { return; } var logFile = dirPath + "nlog-test.log"; SimpleFileWriteLogTest(logFile); } } [Fact] public void SimpleFileWithSpecialCharsTest() { var logFile = Path.Combine(Path.GetTempPath(), "nlog_" + Guid.NewGuid() + "!@#$%^&()_-=+ .log"); SimpleFileWriteLogTest(logFile); } private void SimpleFileWriteLogTest(string logFile) { try { var fileTarget = new FileTarget { FileName = SimpleLayout.Escape(logFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; // Flush AssertFileContents(logFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } finally { if (File.Exists(logFile)) File.Delete(logFile); } } [Fact] public void SimpleFileTestWriteBom() { var logFile = Path.GetTempFileName(); try { var fileTarget = new FileTarget { FileName = SimpleLayout.Escape(logFile), LineEnding = LineEndingMode.LF, Encoding = Encoding.UTF8, WriteBom = true, Layout = "${level} ${message}", }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("aaa"); LogManager.Configuration = null; // Flush AssertFileContents(logFile, "Debug aaa\n", Encoding.UTF8, true); } finally { if (File.Exists(logFile)) File.Delete(logFile); } } #if !MONO /// <summary> /// If a drive doesn't existing, before repeatably creating a dir was tried. This test was taking +60 seconds /// </summary> [Theory] [MemberData(nameof(SimpleFileTest_TestParameters))] public void NonExistingDriveShouldNotDelayMuch(bool concurrentWrites, bool keepFileOpen, bool networkWrites, bool forceManaged, bool forceMutexConcurrentWrites) { var nonExistingDrive = GetFirstNonExistingDriveWindows(); var logFile = nonExistingDrive + "://dont-extist/no-timeout.log"; DateTime start = DateTime.UtcNow; try { using (new NoThrowNLogExceptions()) { var fileTarget = new FileTarget { FileName = logFile, Layout = "${level} ${message}", ConcurrentWrites = concurrentWrites, KeepFileOpen = keepFileOpen, NetworkWrites = networkWrites, ForceManaged = forceManaged, ForceMutexConcurrentWrites = forceMutexConcurrentWrites, }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); for (int i = 0; i < 300; i++) { logger.Debug("aaa"); } LogManager.Configuration = null; // Flush Assert.True(DateTime.UtcNow - start < TimeSpan.FromSeconds(5)); } } finally { //should not be necessary if (File.Exists(logFile)) File.Delete(logFile); } } /// <summary> /// Get first drive letter of non-existing drive /// </summary> /// <returns></returns> private static char GetFirstNonExistingDriveWindows() { var existingDrives = new HashSet<string>(Environment.GetLogicalDrives().Select(d => d[0].ToString()), StringComparer.OrdinalIgnoreCase); var nonExistingDrive = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToList().First(driveLetter => !existingDrives.Contains(driveLetter.ToString())); return nonExistingDrive; } #endif [Fact] public void RollingArchiveEveryMonth() { var tempDir = Path.Combine(Path.GetTempPath(), "nlog_" + Guid.NewGuid().ToString()); var defaultTimeSource = TimeSource.Current; try { var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local); if (timeSource.Time.Minute == 59) { // Avoid double-archive due to overflow of the hour. timeSource.AddToLocalTime(TimeSpan.FromMinutes(1)); timeSource.AddToSystemTime(TimeSpan.FromMinutes(1)); } TimeSource.Current = timeSource; var fileTarget = new FileTarget { FileName = Path.Combine(tempDir, "${date:format=dd}_AppName.log"), LineEnding = LineEndingMode.LF, Layout = "${message}", ArchiveNumbering = ArchiveNumberingMode.Rolling, ArchiveEvery = FileArchivePeriod.Month, MaxArchiveFiles = 1, }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); for (int i = 0; i < 12; ++i) { for (int j = 0; j < 31; ++j) { logger.Debug("aaa"); timeSource.AddToLocalTime(TimeSpan.FromDays(1)); timeSource.AddToSystemTime(TimeSpan.FromDays(1)); } } var files = Directory.GetFiles(tempDir); // Cleanup doesn't work, as all file names has the same timestamp if (files.Length < 28 || files.Length > 31) Assert.Equal(30, files.Length); foreach (var file in files) { Assert.Equal(14, Path.GetFileName(file).Length); } fileTarget.Close(); } finally { TimeSource.Current = defaultTimeSource; if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } #if !MONO [Theory] #else [Theory(Skip="Not supported on MONO on Travis, because of File birthtime not working")] #endif [InlineData(false, false, ArchiveNumberingMode.DateAndSequence)] [InlineData(false, true, ArchiveNumberingMode.DateAndSequence)] [InlineData(false, false, ArchiveNumberingMode.Sequence)] [InlineData(false, true, ArchiveNumberingMode.Sequence)] [InlineData(true, false, ArchiveNumberingMode.DateAndSequence)] [InlineData(true, true, ArchiveNumberingMode.DateAndSequence)] [InlineData(true, false, ArchiveNumberingMode.Sequence)] [InlineData(true, true, ArchiveNumberingMode.Sequence)] public void DatedArchiveEveryMonth(bool archiveSubFolder, bool maxArchiveDays, ArchiveNumberingMode archiveNumberingMode) { if (IsLinux()) { Console.WriteLine("[SKIP] FileTargetTests.DatedArchiveEveryMonth because SetCreationTime is not working on Travis"); return; } var tempDir = Path.Combine(Path.GetTempPath(), "nlog_" + Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "AppName.log"); var archiveDir = archiveSubFolder ? Path.Combine(tempDir, "Archive") : tempDir; var defaultTimeSource = TimeSource.Current; try { var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local); if (timeSource.Time.Minute == 59) { // Avoid double-archive due to overflow of the hour. timeSource.AddToLocalTime(TimeSpan.FromMinutes(1)); timeSource.AddToSystemTime(TimeSpan.FromMinutes(1)); } TimeSource.Current = timeSource; // Generate 4 files with the following contents // 000 - 6 Months Old (Deleted) // 111 - 4 Months Old // 222 - 2 Months Old // 333 - Current List<string> createdFiles = new List<string>(); List<string> currentFiles = new List<string>(); for (int i = 0; i < 4; ++i) { if (i != 0) { // Make the files 2 months older, and lets try again for (int x = 0; x < createdFiles.Count; ++x) { var existingFile = createdFiles[x]; var monthsOld = x == 0 ? 2 : ((i - x) * 2 + 2); File.SetCreationTime(existingFile, DateTime.Now.AddDays(-(32 * monthsOld))); } timeSource.AddToLocalTime(TimeSpan.FromDays(32 * 3)); timeSource.AddToSystemTime(TimeSpan.FromDays(32 * 3)); } var fileTarget = new FileTarget { FileName = logFile, LineEnding = LineEndingMode.LF, Encoding = Encoding.ASCII, Layout = "${message}", KeepFileOpen = i % 2 != 0, ArchiveFileName = archiveSubFolder ? Path.Combine(archiveDir, "AppName.{#}.log") : (Layout)null, ArchiveNumbering = archiveNumberingMode, ArchiveEvery = FileArchivePeriod.Month, ArchiveDateFormat = "yyyyMMdd", MaxArchiveFiles = maxArchiveDays ? 0 : 2, MaxArchiveDays = maxArchiveDays ? 5 * 30 : 0 }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug($"{i.ToString()}{i.ToString()}{i.ToString()}"); LogManager.Configuration = null; // Flush currentFiles = Directory.GetFiles(tempDir).ToList(); if (archiveSubFolder && Directory.Exists(archiveDir)) currentFiles.AddRange(Directory.GetFiles(archiveDir)); string newFile = string.Empty; foreach (var fileName in currentFiles) { if (!createdFiles.Contains(fileName)) { Assert.Empty(newFile); newFile = fileName; if (archiveNumberingMode == ArchiveNumberingMode.DateAndSequence && createdFiles.Count > 1) { // Verify it used the last-modified-time (And not file-creation-time) string dateName = string.Empty; dateName = Path.GetFileName(fileName); dateName = dateName.Replace("AppName.", ""); dateName = dateName.Replace(".0.log", ""); dateName = dateName.Replace("log", ""); Assert.NotEmpty(dateName); Assert.Equal(timeSource.Time.Month, DateTime.ParseExact(dateName, "yyyyMMdd", null).Month); } } } Assert.False(string.IsNullOrEmpty(newFile), $"Missing new file. OldFileCount={createdFiles.Count}, NewFileCount={currentFiles.Count}"); createdFiles.Add(newFile); } Assert.Equal(3, currentFiles.Count); AssertFileContents(logFile, "333\n", Encoding.ASCII); } finally { TimeSource.Current = defaultTimeSource; if (Directory.Exists(archiveDir)) Directory.Delete(archiveDir, true); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void CsvHeaderTest() { var tempDir = Path.Combine(Path.GetTempPath(), "nlog_" + Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "log.log"); if (Path.DirectorySeparatorChar == '\\') logFile = logFile.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); try { for (var i = 0; i < 2; i++) { var layout = new CsvLayout { Delimiter = CsvColumnDelimiterMode.Semicolon, WithHeader = true, Columns = { new CsvColumn("name", "${logger}"), new CsvColumn("level", "${level}"), new CsvColumn("message", "${message}"), } }; var fileTarget = new FileTarget { FileName = SimpleLayout.Escape(logFile), LineEnding = LineEndingMode.LF, Layout = layout, OpenFileCacheTimeout = 0, ReplaceFileContentsOnEachWrite = false, ArchiveAboveSize = 120, // Only 2 LogEvents per file MaxArchiveFiles = 1, }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); if (i == 0) { for (int j = 0; j < 3; j++) logger.Debug("aaa"); LogManager.Configuration = null; // Flush // See that the 3rd LogEvent was placed in its own file AssertFileContents(logFile, "name;level;message\nNLog.UnitTests.Targets.FileTargetTests;Debug;aaa\n", Encoding.UTF8); } else { logger.Debug("aaa"); } } // See that opening closing AssertFileContents(logFile, "name;level;message\nNLog.UnitTests.Targets.FileTargetTests;Debug;aaa\nNLog.UnitTests.Targets.FileTargetTests;Debug;aaa\n", Encoding.UTF8); Assert.NotEqual(3, Directory.GetFiles(tempDir).Length); // See that archive cleanup worked LogManager.Configuration = null; // Close } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void DeleteFileOnStartTest() { var logFile = Path.GetTempFileName(); try { var fileTarget = new FileTarget { DeleteOldFileOnStartup = false, FileName = SimpleLayout.Escape(logFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(logFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); // configure again, without // DeleteOldFileOnStartup fileTarget = new FileTarget { DeleteOldFileOnStartup = false, FileName = SimpleLayout.Escape(logFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(logFile, "Debug aaa\nInfo bbb\nWarn ccc\nDebug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); // configure again, this time with // DeleteOldFileOnStartup fileTarget = new FileTarget { FileName = SimpleLayout.Escape(logFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", DeleteOldFileOnStartup = true }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; // Flush AssertFileContents(logFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } finally { if (File.Exists(logFile)) File.Delete(logFile); } } /// <summary> /// todo not needed to execute twice. /// </summary> [Fact] public void DeleteFileOnStartTest_noExceptionWhenMissing() { var tempDir = Path.Combine(Path.GetTempPath(), "nlog_" + Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "log.log"); try { LogManager.Setup().LoadConfigurationFromXml($@" <nlog throwExceptions='true'> <targets> <target name='file1' encoding='UTF-8' type='File' deleteOldFileOnStartup='true' fileName='{logFile}' /> </targets> <rules> <logger name='*' minlevel='Trace' writeTo='file1' /> </rules> </nlog>"); Assert.False(File.Exists(logFile)); var logger = LogManager.GetCurrentClassLogger(); logger.Trace("running test"); Assert.NotNull(LogManager.Configuration); LogManager.Configuration = null; // Flush } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } #if !NETSTANDARD public static IEnumerable<object[]> ArchiveFileOnStartTests_TestParameters { get { var booleanValues = new[] { true, false }; return from enableCompression in booleanValues from customFileCompressor in booleanValues select new object[] { enableCompression, customFileCompressor }; } } #else public static IEnumerable<object[]> ArchiveFileOnStartTests_TestParameters { get { var booleanValues = new[] { true, false }; return from enableCompression in booleanValues select new object[] { enableCompression, false }; } } #endif [Theory] [MemberData(nameof(ArchiveFileOnStartTests_TestParameters))] public void ArchiveFileOnStartTests(bool enableCompression, bool customFileCompressor) { var logFile = Path.GetTempFileName() + ".txt"; var tempArchiveFolder = Path.Combine(Path.GetTempPath(), "Archive"); var archiveExtension = enableCompression ? "zip" : "txt"; IFileCompressor fileCompressor = null; try { if (customFileCompressor) { fileCompressor = FileTarget.FileCompressor; FileTarget.FileCompressor = new CustomFileCompressor(); } // Configure first time with ArchiveOldFileOnStartup = false. var fileTarget = new FileTarget { ArchiveOldFileOnStartup = false, FileName = SimpleLayout.Escape(logFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(logFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); // Configure second time with ArchiveOldFileOnStartup = false again. // Expected behavior: Extra content to be appended to the file. fileTarget = new FileTarget { ArchiveOldFileOnStartup = false, FileName = SimpleLayout.Escape(logFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; // Flush AssertFileContents(logFile, "Debug aaa\nInfo bbb\nWarn ccc\nDebug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); // Configure third time with ArchiveOldFileOnStartup = true again. // Expected behavior: Extra content will be stored in a new file; the // old content should be moved into a new location. var archiveTempName = Path.Combine(tempArchiveFolder, "archive." + archiveExtension); FileTarget ft; fileTarget = ft = new FileTarget { EnableArchiveFileCompression = enableCompression, FileName = SimpleLayout.Escape(logFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", ArchiveOldFileOnStartup = true, ArchiveFileName = archiveTempName, ArchiveNumbering = ArchiveNumberingMode.Sequence, MaxArchiveFiles = 1 }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("ddd"); logger.Info("eee"); logger.Warn("fff"); LogManager.Configuration = null; // Flush AssertFileContents(logFile, "Debug ddd\nInfo eee\nWarn fff\n", Encoding.UTF8); Assert.True(File.Exists(archiveTempName)); var assertFileContents = ft.EnableArchiveFileCompression ? new Action<string, string, string, Encoding>(AssertZipFileContents) : AssertFileContents; #if !NET35 string expectedEntryName = Path.GetFileNameWithoutExtension(archiveTempName) + ".txt"; #else string expectedEntryName = Path.GetFileName(logFile); #endif assertFileContents(archiveTempName, expectedEntryName, "Debug aaa\nInfo bbb\nWarn ccc\nDebug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } finally { if (customFileCompressor) FileTarget.FileCompressor = fileCompressor; if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempArchiveFolder)) Directory.Delete(tempArchiveFolder, true); } } [Fact] public void ArchiveOldFileOnStartupAboveSize() { var logFile = Path.GetTempFileName(); var tempArchiveFolder = Path.Combine(Path.GetTempPath(), "Archive"); var archiveTempName = Path.Combine(tempArchiveFolder, "archive_size_threshold.txt"); FileTarget CreateTestTarget(long threshold) { return new FileTarget { FileName = SimpleLayout.Escape(logFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", ArchiveOldFileOnStartupAboveSize = threshold, ArchiveFileName = archiveTempName, ArchiveNumbering = ArchiveNumberingMode.Sequence, MaxArchiveFiles = 1 }; } try { // No archive on startup (ignoring threshold) LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(CreateTestTarget(1000))); logger.Info("aaa"); LogManager.Shutdown(); AssertFileContents(logFile, "Info aaa\n", Encoding.UTF8); Assert.False(File.Exists(archiveTempName)); // Archive on startup with small threshold -> Must be archived LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(CreateTestTarget(3))); logger.Info("ccc"); LogManager.Flush(); AssertFileContents(logFile, "Info ccc\n", Encoding.UTF8); Assert.True(File.Exists(archiveTempName)); AssertFileContents(archiveTempName, "Info aaa\n", Encoding.UTF8); } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempArchiveFolder)) Directory.Delete(tempArchiveFolder, true); } } [Fact] public void ArchiveOldFileOnStartupAboveSizeWhenFileLocked() { var logFile = Path.GetTempFileName(); var tempArchiveFolder = Path.Combine(Path.GetTempPath(), "Archive"); var archiveTempName = Path.Combine(tempArchiveFolder, "archive_size_threshold.zip"); FileTarget CreateTestTarget(long threshold) { return new FileTarget { FileName = SimpleLayout.Escape(logFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", ArchiveOldFileOnStartupAboveSize = threshold, ArchiveFileName = archiveTempName, ArchiveNumbering = ArchiveNumberingMode.Sequence, EnableArchiveFileCompression = true, MaxArchiveFiles = 1 }; } try { // No archive on startup (ignoring threshold) LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(CreateTestTarget(1000))); logger.Info("aaa"); LogManager.Shutdown(); AssertFileContents(logFile, "Info aaa\n", Encoding.UTF8); Assert.False(File.Exists(archiveTempName)); NLog.LogManager.ThrowExceptions = false; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(CreateTestTarget(3))); using (var fileStream = new FileStream(logFile, FileMode.Open, FileAccess.Write, FileShare.None)) { // Archive on startup with small threshold -> Must be archived logger.Info("ccc"); LogManager.Flush(); fileStream.Close(); AssertFileContents(logFile, "Info aaa\n", Encoding.UTF8); Assert.False(File.Exists(archiveTempName)); } } finally { NLog.LogManager.ThrowExceptions = true; if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempArchiveFolder)) Directory.Delete(tempArchiveFolder, true); } } public static IEnumerable<object[]> ReplaceFileContentsOnEachWriteTest_TestParameters { get { bool[] boolValues = new[] { false, true }; return from useHeader in boolValues from useFooter in boolValues select new object[] { useHeader, useFooter }; } } [Theory] [MemberData(nameof(ReplaceFileContentsOnEachWriteTest_TestParameters))] public void ReplaceFileContentsOnEachWriteTest(bool useHeader, bool useFooter) { const string header = "Headerline", footer = "Footerline"; var logFile = Path.GetTempFileName(); try { var fileTarget = new FileTarget { DeleteOldFileOnStartup = false, FileName = SimpleLayout.Escape(logFile), ReplaceFileContentsOnEachWrite = true, LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; if (useHeader) fileTarget.Header = header; if (useFooter) fileTarget.Footer = footer; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); string headerPart = useHeader ? header + LineEndingMode.LF.NewLineCharacters : string.Empty; string footerPart = useFooter ? footer + LineEndingMode.LF.NewLineCharacters : string.Empty; logger.Debug("aaa"); LogManager.Flush(); AssertFileContents(logFile, headerPart + "Debug aaa\n" + footerPart, Encoding.UTF8); logger.Info("bbb"); LogManager.Flush(); AssertFileContents(logFile, headerPart + "Info bbb\n" + footerPart, Encoding.UTF8); logger.Warn("ccc"); LogManager.Flush(); AssertFileContents(logFile, headerPart + "Warn ccc\n" + footerPart, Encoding.UTF8); } finally { if (File.Exists(logFile)) File.Delete(logFile); } } [Theory] [InlineData(true)] [InlineData(false)] public void ReplaceFileContentsOnEachWrite_CreateDirs(bool createDirs) { var tempDir = Path.Combine(Path.GetTempPath(), "dir_" + Guid.NewGuid().ToString()); var logfile = Path.Combine(tempDir, "log.log"); try { using (new NoThrowNLogExceptions()) { var target = new FileTarget { FileName = logfile, ReplaceFileContentsOnEachWrite = true, CreateDirs = createDirs }; var config = new LoggingConfiguration(); config.AddTarget("logfile", target); config.AddRuleForAllLevels(target); LogManager.Configuration = config; var logger = LogManager.GetLogger("A"); logger.Info("a"); Assert.Equal(createDirs, Directory.Exists(tempDir)); } } finally { if (File.Exists(logfile)) File.Delete(logfile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void CreateDirsTest() { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "file.txt"); try { var fileTarget = new FileTarget { FileName = logFile, LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; // Flush AssertFileContents(logFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } finally { LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Theory] [InlineData(true, 0)] [InlineData(false, 0)] [InlineData(false, 1)] public void AutoFlushTest(bool autoFlush, int autoFlushTimeout) { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "file.txt"); try { var fileTarget = new FileTarget { FileName = logFile, LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", KeepFileOpen = true, ConcurrentWrites = false, AutoFlush = autoFlush, OpenFileFlushTimeout = autoFlushTimeout, }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); if (autoFlush) { AssertFileContents(logFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } else { AssertFileContents(logFile, string.Empty, Encoding.UTF8); if (autoFlushTimeout > 0) { Thread.Sleep(TimeSpan.FromSeconds(autoFlushTimeout * 1.5)); AssertFileContents(logFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } } LogManager.Configuration = null; // Flush AssertFileContents(logFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } finally { LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void SequentialArchiveTest() { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "file.txt"); try { string archiveFolder = Path.Combine(tempDir, "archive"); var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(archiveFolder, "{####}.txt"), ArchiveAboveSize = 100, LineEnding = LineEndingMode.LF, Layout = "${message}", MaxArchiveFiles = 3, ArchiveNumbering = ArchiveNumberingMode.Sequence }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); // we emit 5 * 25 *(3 x aaa + \n) bytes // so that we should get a full file + 3 archives Generate100BytesLog('a'); Generate100BytesLog('b'); Generate100BytesLog('c'); Generate100BytesLog('d'); Generate100BytesLog('e'); LogManager.Configuration = null; // Flush var times = 25; AssertFileContents(logFile, StringRepeat(times, "eee\n"), Encoding.UTF8); AssertFileContents( Path.Combine(archiveFolder, "0001.txt"), StringRepeat(times, "bbb\n"), Encoding.UTF8); AssertFileContents( Path.Combine(archiveFolder, "0002.txt"), StringRepeat(times, "ccc\n"), Encoding.UTF8); AssertFileContents( Path.Combine(archiveFolder, "0003.txt"), StringRepeat(times, "ddd\n"), Encoding.UTF8); //0000 should not exists because of MaxArchiveFiles=3 Assert.True(!File.Exists(Path.Combine(archiveFolder, "0000.txt"))); Assert.True(!File.Exists(Path.Combine(archiveFolder, "0004.txt"))); } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void SequentialArchiveTest_MaxArchiveFiles_0() { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "file.txt"); try { string archiveFolder = Path.Combine(tempDir, "archive"); var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(archiveFolder, "{####}.txt"), ArchiveAboveSize = 100, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Sequence, Layout = "${message}", MaxArchiveFiles = 0 }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); // we emit 5 * 25 *(3 x aaa + \n) bytes // so that we should get a full file + 4 archives Generate100BytesLog('a'); Generate100BytesLog('b'); Generate100BytesLog('c'); Generate100BytesLog('d'); Generate100BytesLog('e'); LogManager.Configuration = null; // Flush AssertFileContents(logFile, StringRepeat(25, "eee\n"), Encoding.UTF8); AssertFileContents( Path.Combine(archiveFolder, "0000.txt"), StringRepeat(25, "aaa\n"), Encoding.UTF8); AssertFileContents( Path.Combine(archiveFolder, "0001.txt"), StringRepeat(25, "bbb\n"), Encoding.UTF8); AssertFileContents( Path.Combine(archiveFolder, "0002.txt"), StringRepeat(25, "ccc\n"), Encoding.UTF8); AssertFileContents( Path.Combine(archiveFolder, "0003.txt"), StringRepeat(25, "ddd\n"), Encoding.UTF8); Assert.True(!File.Exists(Path.Combine(archiveFolder, "0004.txt"))); } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void ArchiveAboveSizeWithArchiveNumberingModeDate_maxfiles_o() { var tempDir = Path.Combine(Path.GetTempPath(), "ArchiveEveryCombinedWithArchiveAboveSize_" + Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "file.txt"); try { string archiveFolder = Path.Combine(tempDir, "archive"); var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(archiveFolder, "{####}.txt"), ArchiveAboveSize = 100, LineEnding = LineEndingMode.LF, Layout = "${message}", ArchiveNumbering = ArchiveNumberingMode.Date }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); //e.g. 20150804 var archiveFileName = DateTime.Now.ToString("yyyyMMdd"); // we emit 5 * 25 *(3 x aaa + \n) bytes // so that we should get a full file + 3 archives var times = 25; for (var i = 0; i < times; ++i) { logger.Debug("aaa"); } for (var i = 0; i < times; ++i) { logger.Debug("bbb"); } for (var i = 0; i < times; ++i) { logger.Debug("ccc"); } for (var i = 0; i < times; ++i) { logger.Debug("ddd"); } for (var i = 0; i < times; ++i) { logger.Debug("eee"); } LogManager.Configuration = null; // Flush //we expect only eee and all other in the archive AssertFileContents(logFile, StringRepeat(times, "eee\n"), Encoding.UTF8); //DUNNO what to expected! //try (which fails) AssertFileContents( Path.Combine(archiveFolder, $"{archiveFileName}.txt"), StringRepeat(times, "aaa\n") + StringRepeat(times, "bbb\n") + StringRepeat(times, "ccc\n") + StringRepeat(times, "ddd\n"), Encoding.UTF8); } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void DeleteArchiveFilesByDate() { const int maxArchiveFiles = 3; var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "file.txt"); try { string archiveFolder = Path.Combine(tempDir, "archive"); var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(archiveFolder, "{#}.txt"), ArchiveAboveSize = 50, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Date, ArchiveDateFormat = "yyyyMMddHHmmssfff", //make sure the milliseconds are set in the filename Layout = "${message}", MaxArchiveFiles = maxArchiveFiles }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); //writing 19 times 10 bytes (9 char + linefeed) will result in 3 archive files and 1 current file for (var i = 0; i < 19; ++i) { logger.Debug("123456789"); //build in a small sleep to make sure the current time is reflected in the filename //do this every 5 entries if (i % 5 == 0) Thread.Sleep(50); } //Setting the Configuration to [null] will result in a 'Dump' of the current log entries LogManager.Configuration = null; // Flush var files = Directory.GetFiles(archiveFolder).OrderBy(s => s); //the amount of archived files may not exceed the set 'MaxArchiveFiles' Assert.Equal(maxArchiveFiles, files.Count()); LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); //writing just one line of 11 bytes will trigger the cleanup of old archived files //as stated by the MaxArchiveFiles property, but will only delete the oldest file logger.Debug("1234567890"); LogManager.Configuration = null; // Flush var files2 = Directory.GetFiles(archiveFolder).OrderBy(s => s); Assert.Equal(maxArchiveFiles, files2.Count()); //the oldest file should be deleted Assert.DoesNotContain(files.ElementAt(0), files2); //two files should still be there Assert.Equal(files.ElementAt(1), files2.ElementAt(0)); Assert.Equal(files.ElementAt(2), files2.ElementAt(1)); //one new archive file should be created Assert.DoesNotContain(files2.ElementAt(2), files); } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void DeleteArchiveFilesByDateWithDateName() { const int maxArchiveFiles = 3; LogManager.ThrowExceptions = true; var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); try { var logFile = Path.Combine(tempDir, "${date:format=yyyyMMddHHmmssfff}.txt"); var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(tempDir, "{#}.txt"), ArchiveEvery = FileArchivePeriod.Year, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Date, ArchiveDateFormat = "yyyyMMddHHmmssfff", //make sure the milliseconds are set in the filename Layout = "${message}", MaxArchiveFiles = maxArchiveFiles }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); for (var i = 0; i < 4; ++i) { logger.Debug("123456789"); //build in a sleep to make sure the current time is reflected in the filename Thread.Sleep(50); } //Setting the Configuration to [null] will result in a 'Dump' of the current log entries LogManager.Configuration = null; // Flush var files = Directory.GetFiles(tempDir).OrderBy(s => s); //we expect 3 archive files, plus one current file Assert.Equal(maxArchiveFiles + 1, files.Count()); LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); //writing 50ms later will trigger the cleanup of old archived files //as stated by the MaxArchiveFiles property, but will only delete the oldest file Thread.Sleep(50); logger.Debug("123456789"); LogManager.Configuration = null; // Flush var files2 = Directory.GetFiles(tempDir).OrderBy(s => s); Assert.Equal(maxArchiveFiles + 1, files2.Count()); //the oldest file should be deleted Assert.DoesNotContain(files.ElementAt(0), files2); //two files should still be there Assert.Equal(files.ElementAt(1), files2.ElementAt(0)); Assert.Equal(files.ElementAt(2), files2.ElementAt(1)); Assert.Equal(files.ElementAt(3), files2.ElementAt(2)); //one new file should be created Assert.DoesNotContain(files2.ElementAt(3), files); } finally { if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } public static IEnumerable<object[]> DateArchive_UsesDateFromCurrentTimeSource_TestParameters { get { var maxArchiveDays = false; var booleanValues = new[] { true, false }; var timeKindValues = new[] { DateTimeKind.Utc, DateTimeKind.Local }; return from timeKind in timeKindValues from includeDateInLogFilePath in booleanValues from concurrentWrites in booleanValues from keepFileOpen in booleanValues from networkWrites in booleanValues from forceMutexConcurrentWrites in booleanValues where UniqueBaseAppender(concurrentWrites, keepFileOpen, networkWrites, forceMutexConcurrentWrites) from includeSequenceInArchive in booleanValues from forceManaged in booleanValues select new object[] { timeKind, includeDateInLogFilePath, concurrentWrites, keepFileOpen, networkWrites, includeSequenceInArchive, forceManaged, forceMutexConcurrentWrites, maxArchiveDays }; } } [Theory] [MemberData(nameof(DateArchive_UsesDateFromCurrentTimeSource_TestParameters))] public void DateArchive_UsesDateFromCurrentTimeSource(DateTimeKind timeKind, bool includeDateInLogFilePath, bool concurrentWrites, bool keepFileOpen, bool networkWrites, bool includeSequenceInArchive, bool forceManaged, bool forceMutexConcurrentWrites, bool maxArhiveDays) { #if NETSTANDARD || MONO if (IsLinux()) { Console.WriteLine("[SKIP] FileTargetTests.DateArchive_UsesDateFromCurrentTimeSource because SetLastWriteTime is not working on Travis"); return; } #endif const string archiveDateFormat = "yyyyMMdd"; const int maxArchiveFiles = 3; var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, includeDateInLogFilePath ? "file_${shortdate}.txt" : "file.txt"); var defaultTimeSource = TimeSource.Current; try { var timeSource = new TimeSourceTests.ShiftedTimeSource(timeKind); TimeSource.Current = timeSource; string archiveFolder = Path.Combine(tempDir, "archive"); string archiveFileNameTemplate = Path.Combine(archiveFolder, "{#}.txt"); var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = archiveFileNameTemplate, LineEnding = LineEndingMode.LF, ArchiveNumbering = includeSequenceInArchive ? ArchiveNumberingMode.DateAndSequence : ArchiveNumberingMode.Date, ArchiveEvery = FileArchivePeriod.Day, ArchiveDateFormat = archiveDateFormat, Layout = "${date:format=O}|${message}", MaxArchiveFiles = maxArhiveDays ? 0 : maxArchiveFiles, MaxArchiveDays = maxArhiveDays ? maxArchiveFiles : 0, ConcurrentWrites = concurrentWrites, KeepFileOpen = keepFileOpen, NetworkWrites = networkWrites, ForceManaged = forceManaged, ForceMutexConcurrentWrites = forceMutexConcurrentWrites, Header = "header", }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("123456789"); DateTime previousWriteTime = timeSource.Time; const int daysToTestLogging = 3; const int intervalsPerDay = 24; var loggingInterval = TimeSpan.FromHours(1); for (var i = 0; i < daysToTestLogging * intervalsPerDay; ++i) { timeSource.AddToLocalTime(loggingInterval); if (timeSource.Time.Date != previousWriteTime.Date) { string currentLogFile = includeDateInLogFilePath ? logFile.Replace("${shortdate}", timeSource.Time.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)) : logFile; // Simulate that previous file write began in previous day and ended on current day. try { File.SetLastWriteTime(currentLogFile, timeSource.SystemTime); } catch { } } var eventInfo = new LogEventInfo(LogLevel.Debug, logger.Name, "123456789"); logger.Log(eventInfo); LogManager.Flush(); var dayIsChanged = eventInfo.TimeStamp.Date != previousWriteTime.Date; // ensure new archive is created only when the day part of time is changed var archiveFileName = archiveFileNameTemplate.Replace("{#}", previousWriteTime.ToString(archiveDateFormat) + (includeSequenceInArchive ? ".0" : string.Empty)); var archiveExists = File.Exists(archiveFileName); if (dayIsChanged) Assert.True(archiveExists, $"new archive should be created when the day part of {timeKind} time is changed"); else Assert.False(archiveExists, $"new archive should not be create when day part of {timeKind} time is unchanged"); previousWriteTime = eventInfo.TimeStamp.Date; if (dayIsChanged) timeSource.AddToSystemTime(TimeSpan.FromDays(1)); } //Setting the Configuration to [null] will result in a 'Dump' of the current log entries LogManager.Configuration = null; // Flush var files = Directory.GetFiles(archiveFolder); //the amount of archived files may not exceed the set 'MaxArchiveFiles' Assert.Equal(maxArchiveFiles, files.Length); foreach (var file in files) AssertFileContentsStartsWith(file, "header", Encoding.UTF8); LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); //writing one line on a new day will trigger the cleanup of old archived files //as stated by the MaxArchiveFiles property, but will only delete the oldest file timeSource.AddToLocalTime(TimeSpan.FromDays(1)); logger.Debug("1234567890"); LogManager.Configuration = null; // Flush var files2 = Directory.GetFiles(archiveFolder); Assert.Equal(maxArchiveFiles, files2.Length); //the oldest file should be deleted Assert.DoesNotContain(files[0], files2); //two files should still be there Assert.Equal(files[1], files2[0]); Assert.Equal(files[2], files2[1]); //one new archive file should be created Assert.DoesNotContain(files2[2], files); } finally { TimeSource.Current = defaultTimeSource; // restore default time source if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Theory] [InlineData(DateTimeKind.Utc, false, false)] [InlineData(DateTimeKind.Local, false, false)] [InlineData(DateTimeKind.Utc, true, false)] [InlineData(DateTimeKind.Local, true, false)] [InlineData(DateTimeKind.Utc, false, true)] [InlineData(DateTimeKind.Local, false, true)] [InlineData(DateTimeKind.Utc, true, true)] [InlineData(DateTimeKind.Local, true, true)] public void DateArchive_UsesDateFromCurrentTimeSource_MaxArchiveDays(DateTimeKind timeKind, bool includeDateInLogFilePath, bool includeSequenceInArchive) { const bool MaxArchiveDays = true; DateArchive_UsesDateFromCurrentTimeSource(timeKind, includeDateInLogFilePath, false, false, false, includeSequenceInArchive, false, false, MaxArchiveDays); } public static IEnumerable<object[]> DateArchive_ArchiveOnceOnly_TestParameters { get { var booleanValues = new[] { true, false }; return from concurrentWrites in booleanValues from keepFileOpen in booleanValues from networkWrites in booleanValues from forceMutexConcurrentWrites in booleanValues where UniqueBaseAppender(concurrentWrites, keepFileOpen, networkWrites, forceMutexConcurrentWrites) from includeDateInLogFilePath in booleanValues from includeSequenceInArchive in booleanValues from forceManaged in booleanValues select new object[] { concurrentWrites, keepFileOpen, networkWrites, includeDateInLogFilePath, includeSequenceInArchive, forceManaged, forceMutexConcurrentWrites }; } } [Theory] [MemberData(nameof(DateArchive_ArchiveOnceOnly_TestParameters))] public void DateArchive_ArchiveOnceOnly(bool concurrentWrites, bool keepFileOpen, bool networkWrites, bool dateInLogFilePath, bool includeSequenceInArchive, bool forceManaged, bool forceMutexConcurrentWrites) { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, dateInLogFilePath ? "file_${shortdate}.txt" : "file.txt"); var defaultTimeSource = TimeSource.Current; try { var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local); if (timeSource.Time.Minute == 59) { // Avoid double-archive due to overflow of the hour. timeSource.AddToLocalTime(TimeSpan.FromMinutes(1)); timeSource.AddToSystemTime(TimeSpan.FromMinutes(1)); } TimeSource.Current = timeSource; string archiveFolder = Path.Combine(tempDir, "archive"); var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(archiveFolder, "{#}.txt"), LineEnding = LineEndingMode.LF, ArchiveNumbering = includeSequenceInArchive ? ArchiveNumberingMode.DateAndSequence : ArchiveNumberingMode.Date, ArchiveEvery = FileArchivePeriod.Day, ArchiveDateFormat = "yyyyMMdd", Layout = "${message}", ConcurrentWrites = concurrentWrites, KeepFileOpen = keepFileOpen, NetworkWrites = networkWrites, ForceManaged = forceManaged, ForceMutexConcurrentWrites = forceMutexConcurrentWrites, }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("123456789"); LogManager.Flush(); timeSource.AddToLocalTime(TimeSpan.FromDays(1)); // This should archive the log before logging. logger.Debug("123456789"); timeSource.AddToSystemTime(TimeSpan.FromDays(1)); // Archive only once // This must not archive. logger.Debug("123456789"); LogManager.Configuration = null; // Flush Assert.Single(Directory.GetFiles(archiveFolder)); var prevLogFile = Directory.GetFiles(archiveFolder)[0]; AssertFileContents(prevLogFile, StringRepeat(1, "123456789\n"), Encoding.UTF8); var currentLogFile = Directory.GetFiles(tempDir)[0]; AssertFileContents(currentLogFile, StringRepeat(2, "123456789\n"), Encoding.UTF8); } finally { TimeSource.Current = defaultTimeSource; // restore default time source if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } public static IEnumerable<object[]> DateArchive_SkipPeriod_TestParameters { get { var timeKindValues = new[] { DateTimeKind.Utc, DateTimeKind.Local }; var archivePeriodValues = new[] { FileArchivePeriod.Day, FileArchivePeriod.Hour }; var booleanValues = new[] { true, false }; return from timeKind in timeKindValues from archivePeriod in archivePeriodValues from includeDateInLogFilePath in booleanValues from includeSequenceInArchive in booleanValues select new object[] { timeKind, archivePeriod, includeDateInLogFilePath, includeSequenceInArchive }; } } [Theory] [MemberData(nameof(DateArchive_SkipPeriod_TestParameters))] public void DateArchive_SkipPeriod(DateTimeKind timeKind, FileArchivePeriod archivePeriod, bool includeDateInLogFilePath, bool includeSequenceInArchive) { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, includeDateInLogFilePath ? "file_${date:format=yyyyMMddHHmm}.txt" : "file.txt"); var defaultTimeSource = TimeSource.Current; try { // Avoid inconsistency in file's last-write-time due to overflow of the minute during test run. while (DateTime.Now.Second > 55) Thread.Sleep(1000); var timeSource = new TimeSourceTests.ShiftedTimeSource(timeKind); if (timeSource.Time.Minute == 59) { // Avoid double-archive due to overflow of the hour. timeSource.AddToLocalTime(TimeSpan.FromMinutes(1)); timeSource.AddToSystemTime(TimeSpan.FromMinutes(1)); } TimeSource.Current = timeSource; var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(tempDir, "archive", "{#}.txt"), LineEnding = LineEndingMode.LF, ArchiveNumbering = includeSequenceInArchive ? ArchiveNumberingMode.DateAndSequence : ArchiveNumberingMode.Date, ArchiveEvery = archivePeriod, ArchiveDateFormat = "yyyyMMddHHmm", Layout = "${date:format=O}|${message}", }; string archiveDateFormat = fileTarget.ArchiveDateFormat; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("1234567890"); timeSource.AddToLocalTime(TimeSpan.FromMinutes(1)); logger.Debug("1234567890"); // The archive file name must be based on the last time the file was written. string archiveFileName = $"{timeSource.Time.ToString(archiveDateFormat) + (includeSequenceInArchive ? ".0" : string.Empty)}.txt"; // Effectively update the file's last-write-time. timeSource.AddToSystemTime(TimeSpan.FromMinutes(1)); timeSource.AddToLocalTime(TimeSpan.FromDays(2)); logger.Debug("1234567890"); LogManager.Configuration = null; // Flush string archivePath = Path.Combine(tempDir, "archive"); var archiveFiles = Directory.GetFiles(archivePath); Assert.Single(archiveFiles); Assert.Equal(archiveFileName, Path.GetFileName(archiveFiles[0])); } finally { TimeSource.Current = defaultTimeSource; // restore default time source if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } public static IEnumerable<object[]> DateArchive_AllLoggersTransferToCurrentLogFile_TestParameters { get { var booleanValues = new[] { true, false }; return from concurrentWrites in booleanValues from keepFileOpen in booleanValues from networkWrites in booleanValues from forceMutexConcurrentWrites in booleanValues where UniqueBaseAppender(concurrentWrites, keepFileOpen, networkWrites, forceMutexConcurrentWrites) from includeDateInLogFilePath in booleanValues from includeSequenceInArchive in booleanValues from enableArchiveCompression in booleanValues from forceManaged in booleanValues select new object[] { concurrentWrites, keepFileOpen, networkWrites, includeDateInLogFilePath, includeSequenceInArchive, enableArchiveCompression, forceManaged, forceMutexConcurrentWrites }; } } [Theory] [MemberData(nameof(DateArchive_AllLoggersTransferToCurrentLogFile_TestParameters))] public void DateArchive_AllLoggersTransferToCurrentLogFile(bool concurrentWrites, bool keepFileOpen, bool networkWrites, bool includeDateInLogFilePath, bool includeSequenceInArchive, bool enableArchiveCompression, bool forceManaged, bool forceMutexConcurrentWrites) { if (keepFileOpen && !networkWrites && !concurrentWrites) return; // This combination do not support two local FileTargets to the same file #if NET35 || NET40 if (enableArchiveCompression) return; // No need to test with compression #endif var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logfile = Path.Combine(tempDir, includeDateInLogFilePath ? "file_${shortdate}.txt" : "file.txt"); var defaultTimeSource = TimeSource.Current; #if NET35 || NET40 IFileCompressor fileCompressor = null; #endif try { var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local); if (timeSource.Time.Minute == 59) { // Avoid double-archive due to overflow of the hour. timeSource.AddToLocalTime(TimeSpan.FromMinutes(1)); timeSource.AddToSystemTime(TimeSpan.FromMinutes(1)); } TimeSource.Current = timeSource; var config = new LoggingConfiguration(); #if NET35 || NET40 if (enableArchiveCompression) { fileCompressor = FileTarget.FileCompressor; FileTarget.FileCompressor = new CustomFileCompressor(); } #endif string archiveFolder = Path.Combine(tempDir, "archive"); var fileTarget1 = new FileTarget { FileName = logfile, ArchiveFileName = Path.Combine(archiveFolder, "{#}.txt"), LineEnding = LineEndingMode.LF, ArchiveNumbering = includeSequenceInArchive ? ArchiveNumberingMode.DateAndSequence : ArchiveNumberingMode.Date, ArchiveEvery = FileArchivePeriod.Day, ArchiveDateFormat = "yyyyMMdd", EnableArchiveFileCompression = enableArchiveCompression, Layout = "${message}", ConcurrentWrites = concurrentWrites, KeepFileOpen = keepFileOpen, NetworkWrites = networkWrites, ForceManaged = forceManaged, ForceMutexConcurrentWrites = forceMutexConcurrentWrites, }; var logger1Rule = new LoggingRule("logger1", LogLevel.Debug, fileTarget1); config.LoggingRules.Add(logger1Rule); var fileTarget2 = new FileTarget { FileName = logfile, ArchiveFileName = Path.Combine(archiveFolder, "{#}.txt"), LineEnding = LineEndingMode.LF, ArchiveNumbering = includeSequenceInArchive ? ArchiveNumberingMode.DateAndSequence : ArchiveNumberingMode.Date, ArchiveEvery = FileArchivePeriod.Day, ArchiveDateFormat = "yyyyMMdd", EnableArchiveFileCompression = enableArchiveCompression, Layout = "${message}", ConcurrentWrites = concurrentWrites, KeepFileOpen = keepFileOpen, NetworkWrites = networkWrites, ForceManaged = forceManaged, ForceMutexConcurrentWrites = forceMutexConcurrentWrites, }; var logger2Rule = new LoggingRule("logger2", LogLevel.Debug, fileTarget2); config.LoggingRules.Add(logger2Rule); LogManager.Configuration = config; var logger1 = LogManager.GetLogger("logger1"); var logger2 = LogManager.GetLogger("logger2"); logger1.Debug("123456789"); logger2.Debug("123456789"); LogManager.Flush(); timeSource.AddToLocalTime(TimeSpan.FromDays(1)); // This should archive the log before logging. logger1.Debug("123456789"); timeSource.AddToSystemTime(TimeSpan.FromDays(1)); // Archive only once Thread.Sleep(10); logger2.Debug("123456789"); LogManager.Configuration = null; // Flush var files = Directory.GetFiles(archiveFolder); Assert.Single(files); if (!enableArchiveCompression) { string prevLogFile = Directory.GetFiles(archiveFolder)[0]; AssertFileContents(prevLogFile, StringRepeat(2, "123456789\n"), Encoding.UTF8); } string currentLogFile = Directory.GetFiles(tempDir)[0]; AssertFileContents(currentLogFile, StringRepeat(2, "123456789\n"), Encoding.UTF8); } finally { TimeSource.Current = defaultTimeSource; // restore default time source #if NET35 || NET40 if (enableArchiveCompression) { FileTarget.FileCompressor = fileCompressor; } #endif if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void DeleteArchiveFilesByDate_MaxArchiveFiles_0() { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "file.txt"); try { string archiveFolder = Path.Combine(tempDir, "archive"); var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(archiveFolder, "{#}.txt"), ArchiveAboveSize = 50, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Date, ArchiveDateFormat = "yyyyMMddHHmmssfff", //make sure the milliseconds are set in the filename Layout = "${message}", MaxArchiveFiles = 0 }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); //writing 19 times 10 bytes (9 char + linefeed) will result in 3 archive files and 1 current file for (var i = 0; i < 19; ++i) { logger.Debug("123456789"); //build in a small sleep to make sure the current time is reflected in the filename //do this every 5 entries if (i % 5 == 0) { Thread.Sleep(50); } } //Setting the Configuration to [null] will result in a 'Dump' of the current log entries LogManager.Configuration = null; // Flush var fileCount = Directory.EnumerateFiles(archiveFolder).Count(); Assert.Equal(3, fileCount); LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); //create 1 new file for archive logger.Debug("1234567890"); LogManager.Configuration = null; var fileCount2 = Directory.EnumerateFiles(archiveFolder).Count(); //there should be 1 more file Assert.Equal(4, fileCount2); } finally { if (File.Exists(logFile)) { File.Delete(logFile); } if (Directory.Exists(tempDir)) { Directory.Delete(tempDir, true); } } } [Fact] public void DeleteArchiveFilesByDate_AlteredMaxArchive() { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "file.txt"); try { string archiveFolder = Path.Combine(tempDir, "archive"); var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(archiveFolder, "{#}.txt"), ArchiveAboveSize = 50, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Date, ArchiveDateFormat = "yyyyMMddHHmmssfff", //make sure the milliseconds are set in the filename Layout = "${message}", MaxArchiveFiles = 5 }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); //writing 29 times 10 bytes (9 char + linefeed) will result in 3 archive files and 1 current file for (var i = 0; i < 29; ++i) { logger.Debug("123456789"); //build in a small sleep to make sure the current time is reflected in the filename //do this every 5 entries if (i % 5 == 0) Thread.Sleep(50); } //Setting the Configuration to [null] will result in a 'Dump' of the current log entries LogManager.Configuration = null; var files = Directory.GetFiles(archiveFolder).OrderBy(s => s); //the amount of archived files may not exceed the set 'MaxArchiveFiles' Assert.Equal(fileTarget.MaxArchiveFiles, files.Count()); //alter the MaxArchivedFiles fileTarget.MaxArchiveFiles = 2; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); //writing just one line of 11 bytes will trigger the cleanup of old archived files //as stated by the MaxArchiveFiles property, but will only delete the oldest files logger.Debug("1234567890"); LogManager.Configuration = null; // Flush var files2 = Directory.GetFiles(archiveFolder).OrderBy(s => s); Assert.Equal(fileTarget.MaxArchiveFiles, files2.Count()); //the oldest files should be deleted Assert.DoesNotContain(files.ElementAt(0), files2); Assert.DoesNotContain(files.ElementAt(1), files2); Assert.DoesNotContain(files.ElementAt(2), files2); Assert.DoesNotContain(files.ElementAt(3), files2); //one files should still be there Assert.Equal(files.ElementAt(4), files2.ElementAt(0)); //one new archive file should be created Assert.DoesNotContain(files2.ElementAt(1), files); } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void RepeatingHeaderTest() { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "file.txt"); try { const string header = "Headerline"; string archiveFolder = Path.Combine(tempDir, "archive"); var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(archiveFolder, "{####}.txt"), ArchiveAboveSize = 51, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Sequence, Layout = "${message}", Header = header, MaxArchiveFiles = 2, }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); // Writing 16 times 10 bytes = 160 bytes = 3 files for (var i = 0; i < 16; ++i) { logger.Debug("123456789"); } LogManager.Configuration = null; // Flush AssertFileContentsStartsWith(logFile, header, Encoding.UTF8); AssertFileContentsStartsWith(Path.Combine(archiveFolder, "0002.txt"), header, Encoding.UTF8); AssertFileContentsStartsWith(Path.Combine(archiveFolder, "0001.txt"), header, Encoding.UTF8); Assert.True(!File.Exists(Path.Combine(archiveFolder, "0000.txt"))); // MaxArchiveFiles = 2 (Removes the first file) } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Theory] [InlineData(false)] [InlineData(true)] public void RepeatingFooterTest(bool writeFooterOnArchivingOnly) { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "file.txt"); try { const string footer = "Footerline"; string archiveFolder = Path.Combine(tempDir, "archive"); var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(archiveFolder, "{####}.txt"), ArchiveAboveSize = 51, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Sequence, Layout = "${message}", Footer = footer, MaxArchiveFiles = 2, WriteFooterOnArchivingOnly = writeFooterOnArchivingOnly }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); // Writing 16 times 10 bytes = 160 bytes = 3 files for (var i = 0; i < 16; ++i) { logger.Debug("123456789"); } LogManager.Configuration = null; // Flush string expectedEnding = footer + fileTarget.LineEnding.NewLineCharacters; if (writeFooterOnArchivingOnly) Assert.False(File.ReadAllText(logFile).EndsWith(expectedEnding), "Footer was unexpectedly written to log file."); else AssertFileContentsEndsWith(logFile, expectedEnding, Encoding.UTF8); AssertFileContentsEndsWith(Path.Combine(archiveFolder, "0002.txt"), expectedEnding, Encoding.UTF8); AssertFileContentsEndsWith(Path.Combine(archiveFolder, "0001.txt"), expectedEnding, Encoding.UTF8); Assert.False(File.Exists(Path.Combine(archiveFolder, "0000.txt"))); // MaxArchiveFiles = 2 (Removes the first file) } finally { LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Theory] [InlineData(false)] [InlineData(true)] public void RollingArchiveTest(bool specifyArchiveFileName) { RollingArchiveTests(enableCompression: false, specifyArchiveFileName: specifyArchiveFileName); } [Theory] [InlineData(false)] [InlineData(true)] public void RollingArchiveCompressionTest(bool specifyArchiveFileName) { RollingArchiveTests(enableCompression: true, specifyArchiveFileName: specifyArchiveFileName); } private void RollingArchiveTests(bool enableCompression, bool specifyArchiveFileName) { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "file.txt"); var archiveExtension = enableCompression ? "zip" : "txt"; #if NET35 || NET40 IFileCompressor fileCompressor = null; #endif try { var fileTarget = new FileTarget { EnableArchiveFileCompression = enableCompression, FileName = logFile, ArchiveAboveSize = 100, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Rolling, Layout = "${message}", MaxArchiveFiles = 3 }; #if NET35 || NET40 if (enableCompression) { fileCompressor = FileTarget.FileCompressor; FileTarget.FileCompressor = new CustomFileCompressor(); } #endif if (specifyArchiveFileName) fileTarget.ArchiveFileName = Path.Combine(tempDir, "archive", "{####}." + archiveExtension); LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); // we emit 5 * 25 * (3 x aaa + \n) bytes // so that we should get a full file + 3 archives Generate100BytesLog('a'); Generate100BytesLog('b'); Generate100BytesLog('c'); Generate100BytesLog('d'); Generate100BytesLog('e'); LogManager.Configuration = null; // Flush var assertFileContents = enableCompression ? new Action<string, string, string, Encoding>(AssertZipFileContents) : AssertFileContents; var times = 25; AssertFileContents(logFile, StringRepeat(times, "eee\n"), Encoding.UTF8); string archiveFileNameFormat = specifyArchiveFileName ? Path.Combine("archive", "000{0}." + archiveExtension) : "file.{0}." + archiveExtension; assertFileContents( Path.Combine(tempDir, string.Format(archiveFileNameFormat, 0)), "file.txt", StringRepeat(times, "ddd\n"), Encoding.UTF8); assertFileContents( Path.Combine(tempDir, string.Format(archiveFileNameFormat, 1)), "file.txt", StringRepeat(times, "ccc\n"), Encoding.UTF8); assertFileContents( Path.Combine(tempDir, string.Format(archiveFileNameFormat, 2)), "file.txt", StringRepeat(times, "bbb\n"), Encoding.UTF8); Assert.True(!File.Exists(Path.Combine(tempDir, string.Format(archiveFileNameFormat, 3)))); } finally { #if NET35 || NET40 if (enableCompression) { FileTarget.FileCompressor = fileCompressor; } #endif if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [InlineData("/")] [InlineData("\\")] [Theory] public void RollingArchiveTest_MaxArchiveFiles_0(string slash) { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "file.txt"); try { var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(tempDir, "archive" + slash + "{####}.txt"), ArchiveAboveSize = 100, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Rolling, Layout = "${message}", MaxArchiveFiles = 0 }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); // we emit 5 * 25 * (3 x aaa + \n) bytes // so that we should get a full file + 4 archives Generate100BytesLog('a'); Generate100BytesLog('b'); Generate100BytesLog('c'); Generate100BytesLog('d'); Generate100BytesLog('e'); LogManager.Configuration = null; // Flush var times = 25; AssertFileContents(logFile, StringRepeat(times, "eee\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempDir, "archive" + slash + "0000.txt"), StringRepeat(times, "ddd\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempDir, "archive" + slash + "0001.txt"), StringRepeat(times, "ccc\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempDir, "archive" + slash + "0002.txt"), StringRepeat(times, "bbb\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempDir, "archive" + slash + "0003.txt"), StringRepeat(times, "aaa\n"), Encoding.UTF8); } finally { if (File.Exists(logFile)) { File.Delete(logFile); } if (Directory.Exists(tempDir)) { Directory.Delete(tempDir, true); } } } [Fact] public void MultiFileWrite() { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); try { var fileTarget = new FileTarget { FileName = Path.Combine(tempDir, "${level}.txt"), LineEnding = LineEndingMode.LF, Layout = "${message}" }; LogManager.Setup().LoadConfiguration(c => c.ForLogger(LogLevel.Debug).WriteTo(fileTarget)); var times = 25; for (var i = 0; i < times; ++i) { logger.Trace("@@@"); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); logger.Error("ddd"); logger.Fatal("eee"); } LogManager.Configuration = null; // Flush Assert.False(File.Exists(Path.Combine(tempDir, "Trace.txt"))); AssertFileContents(Path.Combine(tempDir, "Debug.txt"), StringRepeat(times, "aaa\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempDir, "Info.txt"), StringRepeat(times, "bbb\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempDir, "Warn.txt"), StringRepeat(times, "ccc\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempDir, "Error.txt"), StringRepeat(times, "ddd\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempDir, "Fatal.txt"), StringRepeat(times, "eee\n"), Encoding.UTF8); } finally { if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void BufferedMultiFileWrite() { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); try { var fileTarget = new FileTarget { FileName = Path.Combine(tempDir, "${level}.txt"), LineEnding = LineEndingMode.LF, Layout = "${message}" }; LogManager.Setup().LoadConfiguration(c => c.ForLogger(LogLevel.Debug).WriteTo(new BufferingTargetWrapper(fileTarget, 10))); var times = 25; for (var i = 0; i < times; ++i) { logger.Trace("@@@"); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); logger.Error("ddd"); logger.Fatal("eee"); } LogManager.Configuration = null; // Flush Assert.False(File.Exists(Path.Combine(tempDir, "Trace.txt"))); AssertFileContents(Path.Combine(tempDir, "Debug.txt"), StringRepeat(times, "aaa\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempDir, "Info.txt"), StringRepeat(times, "bbb\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempDir, "Warn.txt"), StringRepeat(times, "ccc\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempDir, "Error.txt"), StringRepeat(times, "ddd\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempDir, "Fatal.txt"), StringRepeat(times, "eee\n"), Encoding.UTF8); } finally { if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void AsyncMultiFileWrite() { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); try { var fileTarget = new FileTarget { FileName = Path.Combine(tempDir, "${level}.txt"), LineEnding = LineEndingMode.LF, Layout = "${message} ${threadid}" }; // this also checks that thread-volatile layouts // such as ${threadid} are properly cached and not recalculated // in logging threads. var threadID = Thread.CurrentThread.ManagedThreadId.ToString(); LogManager.Setup().LoadConfiguration(c => c.ForLogger(LogLevel.Debug).WriteTo(fileTarget).WithAsync()); var times = 25; for (var i = 0; i < times; ++i) { logger.Trace("@@@"); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); logger.Error("ddd"); logger.Fatal("eee"); } LogManager.Configuration = null; // Flush Assert.False(File.Exists(Path.Combine(tempDir, "Trace.txt"))); AssertFileContents(Path.Combine(tempDir, "Debug.txt"), StringRepeat(times, "aaa " + threadID + "\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempDir, "Info.txt"), StringRepeat(times, "bbb " + threadID + "\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempDir, "Warn.txt"), StringRepeat(times, "ccc " + threadID + "\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempDir, "Error.txt"), StringRepeat(times, "ddd " + threadID + "\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempDir, "Fatal.txt"), StringRepeat(times, "eee " + threadID + "\n"), Encoding.UTF8); } finally { if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void DisposingFileTarget_WhenNotIntialized_ShouldNotThrow() { var exceptionThrown = false; var fileTarget = new FileTarget(); try { fileTarget.Dispose(); } catch { exceptionThrown = true; } Assert.False(exceptionThrown); } [Fact] public void FileTarget_ArchiveNumbering_DateAndSequence() { FileTarget_ArchiveNumbering_DateAndSequenceTests(enableCompression: false, fileTxt: "file.txt", archiveFileName: Path.Combine("archive", "{#}.txt")); } [Fact] public void FileTarget_ArchiveNumbering_DateAndSequence_archive_same_as_log_name() { FileTarget_ArchiveNumbering_DateAndSequenceTests(enableCompression: false, fileTxt: "file-${date:format=yyyy-MM-dd}.txt", archiveFileName: "file-{#}.txt"); } [Fact] public void FileTarget_ArchiveNumbering_DateAndSequence_WithCompression() { FileTarget_ArchiveNumbering_DateAndSequenceTests(enableCompression: true, fileTxt: "file.txt", archiveFileName: Path.Combine("archive", "{#}.zip")); } private void FileTarget_ArchiveNumbering_DateAndSequenceTests(bool enableCompression, string fileTxt, string archiveFileName) { const string archiveDateFormat = "yyyy-MM-dd"; const int archiveAboveSize = 100; var tempDir = ArchiveFileNameHelper.GenerateTempPath(); Layout logFile = Path.Combine(tempDir, fileTxt); var logFileName = logFile.Render(LogEventInfo.CreateNullEvent()); #if NET35 || NET40 IFileCompressor fileCompressor = null; #endif try { var fileTarget = new FileTarget { EnableArchiveFileCompression = enableCompression, FileName = logFile, ArchiveFileName = Path.Combine(tempDir, archiveFileName), ArchiveDateFormat = archiveDateFormat, ArchiveAboveSize = archiveAboveSize, LineEnding = LineEndingMode.LF, Layout = "${message}", MaxArchiveFiles = 3, ArchiveNumbering = ArchiveNumberingMode.DateAndSequence, ArchiveEvery = FileArchivePeriod.Day }; #if NET35 || NET40 if (enableCompression) { fileCompressor = FileTarget.FileCompressor; FileTarget.FileCompressor = new CustomFileCompressor(); } #endif LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); // we emit 5 * 25 *(3 x aaa + \n) bytes // so that we should get a full file + 3 archives Generate100BytesLog('a'); Generate100BytesLog('b'); Generate100BytesLog('c'); Generate100BytesLog('d'); Generate100BytesLog('e'); string renderedArchiveFileName = archiveFileName.Replace("{#}", DateTime.Now.ToString(archiveDateFormat)); LogManager.Configuration = null; var assertFileContents = enableCompression ? new Action<string, string, string, Encoding>(AssertZipFileContents) : AssertFileContents; var extension = Path.GetExtension(renderedArchiveFileName); var fileNameWithoutExt = renderedArchiveFileName.Substring(0, renderedArchiveFileName.Length - extension.Length); ArchiveFileNameHelper helper = new ArchiveFileNameHelper(tempDir, fileNameWithoutExt, extension); var times = 25; AssertFileContents(logFileName, StringRepeat(times, "eee\n"), Encoding.UTF8); #if !NET35 string expectedEntry1Name = Path.GetFileNameWithoutExtension(helper.GetFullPath(1)) + ".txt"; string expectedEntry2Name = Path.GetFileNameWithoutExtension(helper.GetFullPath(2)) + ".txt"; string expectedEntry3Name = Path.GetFileNameWithoutExtension(helper.GetFullPath(3)) + ".txt"; #else string expectedEntry1Name = fileTxt; string expectedEntry2Name = fileTxt; string expectedEntry3Name = fileTxt; #endif assertFileContents(helper.GetFullPath(1), expectedEntry1Name, StringRepeat(times, "bbb\n"), Encoding.UTF8); assertFileContents(helper.GetFullPath(2), expectedEntry2Name, StringRepeat(times, "ccc\n"), Encoding.UTF8); assertFileContents(helper.GetFullPath(3), expectedEntry3Name, StringRepeat(times, "ddd\n"), Encoding.UTF8); Assert.False(helper.Exists(0), "First archive should have been deleted due to max archive count."); Assert.False(helper.Exists(4), "Fifth archive must not have been created yet."); } finally { #if NET35 || NET40 if (enableCompression) { FileTarget.FileCompressor = fileCompressor; } #endif if (File.Exists(logFileName)) File.Delete(logFileName); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Theory] [InlineData("archive/test.log.{####}", "archive/test.log.0000", ArchiveNumberingMode.Sequence)] [InlineData("archive\\test.log.{####}", "archive\\test.log.0000", ArchiveNumberingMode.Sequence)] [InlineData("file-${date:format=yyyyMMdd}.txt", "file-${date:format=yyyyMMdd}.txt", ArchiveNumberingMode.Sequence)] [InlineData("file-{#}.txt", "file-${date:format=yyyyMMdd}.txt", ArchiveNumberingMode.Date)] public void FileTargetArchiveFileNameTest(string archiveFileName, string expectedArchiveFileName, ArchiveNumberingMode archiveNumbering) { var subPath = Guid.NewGuid().ToString(); var tempDir = Path.Combine(Path.GetTempPath(), subPath); var logFile = Path.Combine(tempDir, "file-${date:format=yyyyMMdd}.txt"); try { var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(tempDir, "..", subPath, archiveFileName), ArchiveNumbering = archiveNumbering, ArchiveAboveSize = 1000, MaxArchiveFiles = 1000, }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); for (var i = 0; i < 25; ++i) { logger.Debug("a"); } LogManager.Configuration = null; logFile = new SimpleLayout(logFile).Render(LogEventInfo.CreateNullEvent()); expectedArchiveFileName = new SimpleLayout(expectedArchiveFileName).Render(LogEventInfo.CreateNullEvent()); Assert.True(File.Exists(logFile)); Assert.True(File.Exists(Path.Combine(tempDir, expectedArchiveFileName))); } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void FileTarget_InvalidFileNameCorrection() { var tempFile = Path.GetTempFileName(); var invalidLogFileName = tempFile + Path.GetInvalidFileNameChars()[0]; var expectedCorrectedTempFile = tempFile + "_"; try { var fileTarget = new FileTarget { FileName = SimpleLayout.Escape(invalidLogFileName), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", OpenFileCacheTimeout = 0 }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Fatal("aaa"); LogManager.Configuration = null; // Flush AssertFileContents(expectedCorrectedTempFile, "Fatal aaa\n", Encoding.UTF8); } finally { if (File.Exists(expectedCorrectedTempFile)) File.Delete(expectedCorrectedTempFile); if (File.Exists(invalidLogFileName)) File.Delete(invalidLogFileName); } } [Fact] public void FileTarget_LogAndArchiveFilesWithSameName_ShouldArchive() { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "Application.log"); var tempDirectory = new DirectoryInfo(tempDir); try { var archiveFile = Path.Combine(tempDir, "Application{#}.log"); var archiveFileMask = "Application*.log"; var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = archiveFile, ArchiveAboveSize = 1, //Force immediate archival ArchiveNumbering = ArchiveNumberingMode.DateAndSequence, MaxArchiveFiles = 5 }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); //Creates 5 archive files. for (int i = 0; i <= 5; i++) { logger.Debug("a"); } LogManager.Configuration = null; // Flush Assert.True(File.Exists(logFile)); //Five archive files, plus the log file itself. Assert.True(tempDirectory.GetFiles(archiveFileMask).Length == 5 + 1); } finally { if (tempDirectory.Exists) { tempDirectory.Delete(true); } } } [Fact] public void FileTarget_Handle_Other_Files_That_Match_Archive_Format() { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "Application.log"); var tempDirectory = new DirectoryInfo(tempDir); try { string archiveFileLayout = Path.Combine(Path.GetDirectoryName(logFile), Path.GetFileNameWithoutExtension(logFile) + "{#}" + Path.GetExtension(logFile)); var fileTarget = new FileTarget { FileName = logFile, Layout = "${message}", EnableFileDelete = false, Encoding = Encoding.UTF8, ArchiveFileName = archiveFileLayout, ArchiveEvery = FileArchivePeriod.Day, ArchiveNumbering = ArchiveNumberingMode.Date, ArchiveDateFormat = "___________yyyyMMddHHmm", MaxArchiveFiles = 10 // Get past the optimization to avoid deleting old files. }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); string existingFile = archiveFileLayout.Replace("{#}", "notadate"); Directory.CreateDirectory(Path.GetDirectoryName(logFile)); File.Create(existingFile).Close(); logger.Debug("test"); LogManager.Configuration = null; // Flush AssertFileContents(logFile, "test" + LineEndingMode.Default.NewLineCharacters, Encoding.UTF8); Assert.True(File.Exists(existingFile)); } finally { if (tempDirectory.Exists) { tempDirectory.Delete(true); } } } [Fact] public void SingleArchiveFileRollsCorrectly() { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "file.txt"); try { var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(tempDir, "archive", "file.txt2"), ArchiveAboveSize = 100, LineEnding = LineEndingMode.LF, Layout = "${message}", MaxArchiveFiles = 1, }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); // we emit 2 * 25 *(aaa + \n) bytes // so that we should get a full file + 1 archives var times = 25; for (var i = 0; i < times; ++i) { logger.Debug("aaa"); } for (var i = 0; i < times; ++i) { logger.Debug("bbb"); } LogManager.Flush(); AssertFileContents(logFile, StringRepeat(times, "bbb\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempDir, "archive", "file.txt2"), StringRepeat(times, "aaa\n"), Encoding.UTF8); for (var i = 0; i < times; ++i) { logger.Debug("ccc"); } LogManager.Configuration = null; // Flush AssertFileContents(logFile, StringRepeat(times, "ccc\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempDir, "archive", "file.txt2"), StringRepeat(times, "bbb\n"), Encoding.UTF8); } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void ArchiveFileRollsCorrectly() { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "file.txt"); try { var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(tempDir, "archive", "file.txt2"), ArchiveAboveSize = 100, LineEnding = LineEndingMode.LF, Layout = "${message}", MaxArchiveFiles = 2, }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); // we emit 3 * 25 *(aaa + \n) bytes // so that we should get a full file + 2 archives var times = 25; for (var i = 0; i < times; ++i) { logger.Debug("aaa"); } for (var i = 0; i < times; ++i) { logger.Debug("bbb"); } for (var i = 0; i < times; ++i) { logger.Debug("ccc"); } LogManager.Flush(); AssertFileContents(logFile, StringRepeat(times, "ccc\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempDir, "archive", "file.1.txt2"), StringRepeat(times, "bbb\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempDir, "archive", "file.txt2"), StringRepeat(times, "aaa\n"), Encoding.UTF8); for (var i = 0; i < times; ++i) { logger.Debug("ddd"); } LogManager.Configuration = null; // Flush AssertFileContents(logFile, StringRepeat(times, "ddd\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempDir, "archive", "file.2.txt2"), StringRepeat(times, "ccc\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempDir, "archive", "file.1.txt2"), StringRepeat(times, "bbb\n"), Encoding.UTF8); Assert.False(File.Exists(Path.Combine(tempDir, "archive", "file.txt2"))); } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void ArchiveFileRollsCorrectly_ExistingArchives() { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "file.txt"); try { Directory.CreateDirectory(Path.Combine(tempDir, "archive")); File.Create(Path.Combine(tempDir, "archive", "file.10.txt2")).Dispose(); File.Create(Path.Combine(tempDir, "archive", "file.9.txt2")).Dispose(); var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(tempDir, "archive", "file.txt2"), ArchiveAboveSize = 100, LineEnding = LineEndingMode.LF, Layout = "${message}", MaxArchiveFiles = 2, }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); // we emit 2 * 25 *(aaa + \n) bytes // so that we should get a full file + 1 archive var times = 25; for (var i = 0; i < times; ++i) { logger.Debug("aaa"); } for (var i = 0; i < times; ++i) { logger.Debug("bbb"); } LogManager.Configuration = null; // Flush AssertFileContents(logFile, StringRepeat(times, "bbb\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempDir, "archive", "file.11.txt2"), StringRepeat(times, "aaa\n"), Encoding.UTF8); Assert.True(File.Exists(Path.Combine(tempDir, "archive", "file.10.txt2"))); Assert.False(File.Exists(Path.Combine(tempDir, "archive", "file.9.txt2"))); } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } /// <summary> /// Remove archived files in correct order /// </summary> [Fact] public void FileTarget_ArchiveNumbering_remove_correct_order() { const int maxArchiveFiles = 10; var tempDir = ArchiveFileNameHelper.GenerateTempPath(); var logFile = Path.Combine(tempDir, "file.txt"); var archiveExtension = "txt"; try { var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(tempDir, "archive", "{#}." + archiveExtension), ArchiveDateFormat = "yyyy-MM-dd", ArchiveAboveSize = 100, LineEnding = LineEndingMode.LF, Layout = "${message}", MaxArchiveFiles = maxArchiveFiles, ArchiveNumbering = ArchiveNumberingMode.DateAndSequence, }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); ArchiveFileNameHelper helper = new ArchiveFileNameHelper(Path.Combine(tempDir, "archive"), DateTime.Now.ToString(fileTarget.ArchiveDateFormat), archiveExtension); Generate100BytesLog('a'); for (int i = 0; i < maxArchiveFiles; i++) { Generate100BytesLog('a'); Assert.True(helper.Exists(i), $"file {i} is missing"); } for (int i = maxArchiveFiles; i < 21; i++) { Generate100BytesLog('b'); var numberToBeRemoved = i - maxArchiveFiles; // number 11, we need to remove 1 etc Assert.True(!helper.Exists(numberToBeRemoved), $"archive file {numberToBeRemoved} has not been removed! We are created file {i}"); } LogManager.Configuration = null; } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } /// <summary> /// Allow multiple archives within the same directory /// </summary> [Fact] public void FileTarget_ArchiveNumbering_remove_correct_wildcard() { const int maxArchiveFiles = 5; var tempDir = ArchiveFileNameHelper.GenerateTempPath(); var logFile = Path.Combine(tempDir, "{0}{1}.txt"); var defaultTimeSource = TimeSource.Current; try { var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local); if (timeSource.Time.Minute == 59) { // Avoid double-archive due to overflow of the hour. timeSource.AddToLocalTime(TimeSpan.FromMinutes(1)); timeSource.AddToSystemTime(TimeSpan.FromMinutes(1)); } TimeSource.Current = timeSource; var fileTarget = new FileTarget { FileName = string.Format(logFile, "${logger}", "${shortdate}"), ArchiveAboveSize = 100, LineEnding = LineEndingMode.LF, Layout = "${message}", MaxArchiveFiles = maxArchiveFiles, }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); var logger1 = LogManager.GetLogger("log"); var logger2 = LogManager.GetLogger("log-other"); timeSource.AddToLocalTime(TimeSpan.Zero - TimeSpan.FromDays(1)); Generate100BytesLog((char)('0'), logger1); Generate100BytesLog((char)('0'), logger2); for (int i = 0; i <= maxArchiveFiles - 3; i++) { Generate100BytesLog((char)('1' + i), logger1); Generate100BytesLog((char)('1' + i), logger2); var logFile1 = string.Format(logFile, logger1.Name, TimeSource.Current.Time.Date.ToString("yyyy-MM-dd")); var logFile2 = string.Format(logFile, logger2.Name, TimeSource.Current.Time.Date.ToString("yyyy-MM-dd")); Assert.True(File.Exists(logFile1), $"{logFile1} is missing"); Assert.True(File.Exists(logFile2), $"{logFile2} is missing"); logFile1 = string.Format(logFile, logger1.Name, TimeSource.Current.Time.Date.ToString("yyyy-MM-dd") + "." + i.ToString()); logFile2 = string.Format(logFile, logger2.Name, TimeSource.Current.Time.Date.ToString("yyyy-MM-dd") + "." + i.ToString()); Assert.True(File.Exists(logFile1), $"{logFile1} is missing"); Assert.True(File.Exists(logFile2), $"{logFile2} is missing"); } TimeSource.Current = defaultTimeSource; // restore default time source Generate100BytesLog((char)('a'), logger1); Generate100BytesLog((char)('a'), logger2); for (int i = 0; i < maxArchiveFiles; i++) { Generate100BytesLog((char)('b' + i), logger1); Generate100BytesLog((char)('b' + i), logger2); var logFile1 = string.Format(logFile, logger1.Name, TimeSource.Current.Time.Date.ToString("yyyy-MM-dd") + "." + i.ToString()); var logFile2 = string.Format(logFile, logger2.Name, TimeSource.Current.Time.Date.ToString("yyyy-MM-dd") + "." + i.ToString()); Assert.True(File.Exists(logFile1), $"{logFile1} is missing"); Assert.True(File.Exists(logFile2), $"{logFile2} is missing"); } for (int i = maxArchiveFiles; i < 10; i++) { Generate100BytesLog((char)('b' + i), logger1); Generate100BytesLog((char)('b' + i), logger2); var numberToBeRemoved = i - maxArchiveFiles; var logFile1 = string.Format(logFile, logger1.Name, TimeSource.Current.Time.Date.ToString("yyyy-MM-dd") + "." + numberToBeRemoved.ToString()); var logFile2 = string.Format(logFile, logger2.Name, TimeSource.Current.Time.Date.ToString("yyyy-MM-dd") + "." + numberToBeRemoved.ToString()); Assert.False(File.Exists(logFile1), $"archive FirstFile {numberToBeRemoved} has not been removed! We are created file {i}"); Assert.False(File.Exists(logFile2), $"archive SecondFile {numberToBeRemoved} has not been removed! We are created file {i}"); logFile1 = string.Format(logFile, logger1.Name, TimeSource.Current.Time.Date.ToString("yyyy-MM-dd") + "." + i.ToString()); logFile2 = string.Format(logFile, logger2.Name, TimeSource.Current.Time.Date.ToString("yyyy-MM-dd") + "." + i.ToString()); Assert.True(File.Exists(logFile1), $"{logFile1} is missing"); Assert.True(File.Exists(logFile2), $"{logFile2} is missing"); } // Verify that archieve-cleanup after startup handles same folder archive correctly fileTarget.ArchiveAboveSize = 200; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger1.Info("Bye"); logger2.Info("Bye"); Assert.Equal(12, Directory.GetFiles(tempDir).Length); LogManager.Configuration = null; } finally { TimeSource.Current = defaultTimeSource; // restore default time source if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } /// <summary> /// See that dynamic sequence archive supports same-folder archiving. /// </summary> [Fact] public void FileTarget_SameDirectory_MaxArchiveFiles_One() { const int maxArchiveFiles = 1; var tempDir = ArchiveFileNameHelper.GenerateTempPath(); var logFile1 = Path.Combine(tempDir, "Log{0}.txt"); try { var fileTarget = new FileTarget { FileName = string.Format(logFile1, ""), ArchiveAboveSize = 100, LineEnding = LineEndingMode.LF, Layout = "${message}", MaxArchiveFiles = maxArchiveFiles, Encoding = Encoding.ASCII, }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); Generate100BytesLog('a'); Generate100BytesLog('b'); Generate100BytesLog('c'); var times = 25; AssertFileContents(string.Format(logFile1, ".0"), StringRepeat(times, "bbb\n"), Encoding.ASCII); AssertFileContents(string.Format(logFile1, ""), StringRepeat(times, "ccc\n"), Encoding.ASCII); LogManager.Configuration = null; } finally { if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } private void Generate100BytesLog(char c, Logger logger = null) { logger = logger ?? this.logger; for (var i = 0; i < 25; ++i) { //3 chars with newlines = 4 bytes logger.Debug(new string(c, 3)); } } /// <summary> /// Archive file helepr /// </summary> /// <remarks>TODO rewrite older test</remarks> private class ArchiveFileNameHelper { public string FolderName { get; private set; } public string FileName { get; private set; } /// <summary> /// Ext without dot /// </summary> public string Ext { get; set; } /// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> public ArchiveFileNameHelper(string folderName, string fileName, string ext) { Ext = ext.TrimStart('.'); FileName = fileName; FolderName = folderName; } public bool Exists(int number) { return File.Exists(GetFullPath(number)); } public string GetFullPath(int number) { return Path.Combine($"{FolderName}/{FileName}.{number}.{Ext}"); } public static string GenerateTempPath() { return Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); } } [Theory] [InlineData("##", 0, "00")] [InlineData("###", 1, "001")] [InlineData("#", 20, "20")] public void FileTarget_WithDateAndSequenceArchiveNumbering_ShouldPadSequenceNumberInArchiveFileName( string placeHolderSharps, int sequenceNumber, string expectedSequenceInArchiveFileName) { string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); const string archiveDateFormat = "yyyy-MM-dd"; string archiveFileName = Path.Combine(tempDir, $"{{{placeHolderSharps}}}.log"); string expectedArchiveFullName = $"{tempDir}/{DateTime.Now.ToString(archiveDateFormat)}.{expectedSequenceInArchiveFileName}.log"; GenerateArchives(count: sequenceNumber + 1, archiveDateFormat: archiveDateFormat, archiveFileName: archiveFileName, archiveNumbering: ArchiveNumberingMode.DateAndSequence); bool resultArchiveWithExpectedNameExists = File.Exists(expectedArchiveFullName); Assert.True(resultArchiveWithExpectedNameExists); } [Theory] [InlineData("yyyy-MM-dd HHmm")] [InlineData("y")] [InlineData("D")] public void FileTarget_WithDateAndSequenceArchiveNumbering_ShouldRespectArchiveDateFormat( string archiveDateFormat) { string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); string archiveFileName = Path.Combine(tempDir, "{#}.log"); string expectedDateInArchiveFileName = DateTime.Now.ToString(archiveDateFormat); string expectedArchiveFullName = $"{tempDir}/{expectedDateInArchiveFileName}.1.log"; // We generate 2 archives so that the algorithm that seeks old archives is also tested. GenerateArchives(count: 2, archiveDateFormat: archiveDateFormat, archiveFileName: archiveFileName, archiveNumbering: ArchiveNumberingMode.DateAndSequence); bool resultArchiveWithExpectedNameExists = File.Exists(expectedArchiveFullName); Assert.True(resultArchiveWithExpectedNameExists); } private void GenerateArchives(int count, string archiveDateFormat, string archiveFileName, ArchiveNumberingMode archiveNumbering) { string logFileName = Path.GetTempFileName(); const int logFileMaxSize = 1; var fileTarget = new FileTarget { FileName = logFileName, ArchiveFileName = archiveFileName, ArchiveDateFormat = archiveDateFormat, ArchiveNumbering = archiveNumbering, ArchiveAboveSize = logFileMaxSize }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); for (int currentSequenceNumber = 0; currentSequenceNumber < count; currentSequenceNumber++) logger.Debug("Test {0}", currentSequenceNumber); LogManager.Flush(); } [Fact] public void Dont_throw_Exception_when_archiving_is_enabled() { try { LogManager.Setup().LoadConfigurationFromXml(@"<?xml version='1.0' encoding='utf-8' ?> <nlog xmlns='http://www.nlog-project.org/schemas/NLog.xsd' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' throwExceptions='true' > <targets> <target name='logfile' xsi:type='File' fileName='${basedir}/log.txt' archiveFileName='${basedir}/log.${date}' archiveEvery='Day' archiveNumbering='Date' /> </targets> <rules> <logger name='*' writeTo='logfile' /> </rules> </nlog> "); LogManager.GetLogger("Test").Info("very important message"); Assert.NotNull(LogManager.Configuration); } finally { LogManager.Configuration = null; } } [Fact] public void Dont_throw_Exception_when_archiving_is_enabled_with_async() { try { LogManager.Setup().LoadConfigurationFromXml(@"<?xml version='1.0' encoding='utf-8' ?> <nlog xmlns='http://www.nlog-project.org/schemas/NLog.xsd' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' throwExceptions='true' > <targets async=""true"" > <target name='logfile' xsi:type='File' fileName='${basedir}/log.txt' archiveFileName='${basedir}/log.${date}' archiveEvery='Day' archiveNumbering='Date' /> </targets> <rules> <logger name='*' writeTo='logfile' /> </rules> </nlog> "); LogManager.GetLogger("Test").Info("very important message"); Assert.NotNull(LogManager.Configuration); } finally { LogManager.Configuration = null; } } [Fact] public void DatedArchiveForFileTargetWithMultipleFiles() { var defaultTimeSource = TimeSource.Current; var tempDir = Path.Combine(Path.GetTempPath(), "nlog_" + Guid.NewGuid().ToString()) + Path.DirectorySeparatorChar; try { var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local); if (timeSource.Time.Minute == 59) { // Avoid double-archive due to overflow of the hour. timeSource.AddToLocalTime(TimeSpan.FromMinutes(1)); timeSource.AddToSystemTime(TimeSpan.FromMinutes(1)); } TimeSource.Current = timeSource; GlobalDiagnosticsContext.Set("basedir", tempDir); LogManager.Setup().LoadConfigurationFromXml(@"<?xml version='1.0' encoding='utf-8' ?> <nlog> <variable name='basedir' value='' /> <targets> <target name='file' type='File' fileName='${gdc:item=basedir}${event-properties:item=serialNo}.txt' layout='${message}' archiveFileName='${gdc:item=basedir}${event-properties:item=serialNo}.{#}.txt' archiveNumbering='Date' archiveDateFormat='yyyy-MM-dd' archiveEvery='Day' /> </targets> <rules> <logger name='*' writeTo='file' /> </rules> </nlog> "); var fileLogger = LogManager.GetLogger(nameof(DatedArchiveForFileTargetWithMultipleFiles)); LogEventInfo logEvent = LogEventInfo.Create(LogLevel.Info, fileLogger.Name, "Very Important Message"); logEvent.Properties["serialNo"] = "M91803ED2172"; logger.Log(logEvent); LogEventInfo logEvent2 = LogEventInfo.Create(LogLevel.Info, fileLogger.Name, "Very Important Message"); logEvent2.Properties["serialNo"] = "M91803ED2137"; logger.Log(logEvent2); var currentDate = timeSource.Time.Date; timeSource.AddToLocalTime(TimeSpan.FromDays(5)); LogEventInfo logEvent3 = LogEventInfo.Create(LogLevel.Info, fileLogger.Name, "Very Important Message"); logEvent3.Properties["serialNo"] = logEvent.Properties["serialNo"]; logger.Log(logEvent3); LogEventInfo logEvent4 = LogEventInfo.Create(LogLevel.Info, fileLogger.Name, "Very Important Message"); logEvent4.Properties["serialNo"] = logEvent2.Properties["serialNo"]; logger.Log(logEvent4); var currentFiles = new DirectoryInfo(tempDir).GetFiles(); Assert.Equal(4, currentFiles.Length); Assert.Contains(logEvent.Properties["serialNo"] + ".txt", currentFiles.Select(f => f.Name)); Assert.Contains(logEvent.Properties["serialNo"] + "." + currentDate.ToString("yyyy-MM-dd") + ".txt", currentFiles.Select(f => f.Name)); Assert.Contains(logEvent2.Properties["serialNo"] + ".txt", currentFiles.Select(f => f.Name)); Assert.Contains(logEvent2.Properties["serialNo"] + "." + currentDate.ToString("yyyy-MM-dd") + ".txt", currentFiles.Select(f => f.Name)); } finally { TimeSource.Current = defaultTimeSource; LogManager.Configuration = null; if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void LoggingShouldNotTriggerTypeResolveEventTest() { var tempDir = Path.Combine(Path.GetTempPath(), "nlog_" + Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "log.log"); System.ResolveEventHandler noResolveTest = (s, args) => { Assert.True(false); return null; }; try { LogManager.Setup().LoadConfigurationFromXml(@"<nlog throwExceptions='true'> <targets> <target name='file1' encoding='UTF-8' type='File' fileName='" + logFile + @"'> <layout type='JsonLayout'> <attribute name='message' layout='${message}' /> <attribute name='xml'> <layout type='Log4JXmlEventLayout' /> </attribute> </layout> </target> </targets> <rules> <logger name='*' minlevel='Trace' writeTo='file1' /> </rules> </nlog>"); LogManager.GetLogger("Test").Info("very important message"); Assert.NotNull(LogManager.Configuration); AppDomain.CurrentDomain.TypeResolve += noResolveTest; AppDomain.CurrentDomain.AssemblyResolve += noResolveTest; LogManager.GetLogger("Test").Info("very important message"); } finally { AppDomain.CurrentDomain.TypeResolve -= noResolveTest; AppDomain.CurrentDomain.AssemblyResolve -= noResolveTest; LogManager.Configuration = null; if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Theory] [InlineData("yyyyMMdd-HHmm")] [InlineData("yyyyMMdd")] [InlineData("yyyy-MM-dd")] public void MaxArchiveFilesWithDateFormatTest(string archiveDateFormat) { TestMaxArchiveFilesWithDate(2, 2, archiveDateFormat, true); TestMaxArchiveFilesWithDate(2, 2, archiveDateFormat, false); } /// <summary> /// /// </summary> /// <param name="maxArchiveFilesConfig">max count of archived files</param> /// <param name="expectedArchiveFiles">expected count of archived files</param> /// <param name="dateFormat">date format</param> /// <param name="changeCreationAndWriteTime">change file creation/last write date</param> private static void TestMaxArchiveFilesWithDate(int maxArchiveFilesConfig, int expectedArchiveFiles, string dateFormat, bool changeCreationAndWriteTime) { string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); string archivePath = Path.Combine(tempDir, "archive"); var archiveDir = new DirectoryInfo(archivePath); try { archiveDir.Create(); //set-up, create files. //same dateformat as in config string fileExt = ".log"; DateTime now = DateTime.Now; int i = 0; foreach (string filePath in ArchiveFileNamesGenerator(archivePath, dateFormat, fileExt).Take(30)) { File.WriteAllLines(filePath, new[] { "test archive ", "=====", filePath }); var time = now.AddDays(i); if (changeCreationAndWriteTime) { File.SetCreationTime(filePath, time); File.SetLastWriteTime(filePath, time); } i--; } //create config with archiving var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true' > <targets> <target name='fileAll' type='File' fileName='" + tempDir + @"/${date:format=yyyyMMdd-HHmm}" + fileExt + @"' layout='${message}' archiveEvery='minute' maxArchiveFiles='" + maxArchiveFilesConfig + @"' archiveFileName='" + archivePath + @"/{#}.log' archiveDateFormat='" + dateFormat + @"' archiveNumbering='Date'/> </targets> <rules> <logger name='*' writeTo='fileAll' /> </rules> </nlog>"); LogManager.Configuration = configuration; var logger = LogManager.GetCurrentClassLogger(); logger.Info("test"); var currentFilesCount = archiveDir.GetFiles().Length; Assert.Equal(expectedArchiveFiles, currentFilesCount); LogManager.Configuration = null; // Flush } finally { //cleanup archiveDir.Delete(true); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } /// unit test for issue #1681. ///- When clearing out archive files exceeding maxArchiveFiles, NLog should /// not delete all files in the directory.Only files matching the target's /// archiveFileName pattern. ///- Create test for 2 applications sharing the same archive directory. ///- Create test for 2 applications sharing same archive directory and 1 /// application containing multiple targets to the same archive directory. /// *\* Expected outcome of this should be verified** [Theory] [InlineData(true)] [InlineData(false)] public void HandleArchiveFilesMultipleContextMultipleTargetTest(bool changeCreationAndWriteTime) { HandleArchiveFilesMultipleContextMultipleTargetsTest(2, 2, "yyyyMMdd-HHmm", changeCreationAndWriteTime); } [Theory] [InlineData(true)] [InlineData(false)] public void HandleArchiveFilesMultipleContextSingleTargetTest_ascii(bool changeCreationAndWriteTime) { HandleArchiveFilesMultipleContextSingleTargetsTest(2, 2, "yyyyMMdd-HHmm", changeCreationAndWriteTime); } /// <summary> /// Test the case when multiple applications are archiving to the same directory and using multiple targets. /// Only the archives for this application instance should be deleted per the target archive rules. /// </summary> /// <param name="maxArchiveFilesConfig"># to use for maxArchiveFiles in NLog configuration.</param> /// <param name="expectedArchiveFiles">Expected number of archive files after archiving has occured.</param> /// <param name="dateFormat">string to be used for formatting log file names</param> /// <param name="changeCreationAndWriteTime"></param> private static void HandleArchiveFilesMultipleContextMultipleTargetsTest( int maxArchiveFilesConfig, int expectedArchiveFiles, string dateFormat, bool changeCreationAndWriteTime) { string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); string archivePath = Path.Combine(tempDir, "archive"); var archiveDir = new DirectoryInfo(archivePath); try { archiveDir.Create(); //set-up, create files. var numberFilesCreatedPerTargetArchive = 30; // use same config vars for mock files, as for nlog config var fileExt = ".log"; var app1TraceNm = "App1_Trace"; var app1DebugNm = "App1_Debug"; var app2Nm = "App2"; var now = DateTime.Now; var i = 0; // create mock app1_trace archives (matches app1 config for trace target) foreach (string filePath in ArchiveFileNamesGenerator(archivePath, dateFormat, app1TraceNm + fileExt).Take(numberFilesCreatedPerTargetArchive)) { File.WriteAllLines(filePath, new[] { "test archive ", "=====", filePath }); var time = now.AddDays(i); if (changeCreationAndWriteTime) { File.SetCreationTime(filePath, time); File.SetLastWriteTime(filePath, time); } i--; } i = 0; // create mock app1_debug archives (matches app1 config for debug target) foreach (string filePath in ArchiveFileNamesGenerator(archivePath, dateFormat, app1DebugNm + fileExt).Take(numberFilesCreatedPerTargetArchive)) { File.WriteAllLines(filePath, new[] { "test archive ", "=====", filePath }); var time = now.AddDays(i); if (changeCreationAndWriteTime) { File.SetCreationTime(filePath, time); File.SetLastWriteTime(filePath, time); } i--; } i = 0; // create mock app2 archives (matches app2 config for target) foreach (string filePath in ArchiveFileNamesGenerator(archivePath, dateFormat, app2Nm + fileExt).Take(numberFilesCreatedPerTargetArchive)) { File.WriteAllLines(filePath, new[] { "test archive ", "=====", filePath }); var time = now.AddDays(i); if (changeCreationAndWriteTime) { File.SetCreationTime(filePath, time); File.SetLastWriteTime(filePath, time); } i--; } // Create same app1 Debug file as config defines. Will force archiving to happen on startup File.WriteAllLines(tempDir + "\\" + app1DebugNm + fileExt, new[] { "Write first app debug target. Startup will archive this file" }, Encoding.ASCII); var app1Config = XmlLoggingConfiguration.CreateFromXmlString(@"<nlog throwExceptions='true'> <targets> <target name='traceFile' type='File' fileName='" + Path.Combine(tempDir, app1TraceNm + fileExt) + @"' archiveFileName='" + Path.Combine(archivePath, @"${date:format=" + dateFormat + "}-" + app1TraceNm + fileExt) + @"' archiveEvery='minute' archiveOldFileOnStartup='true' maxArchiveFiles='" + maxArchiveFilesConfig + @"' layout='${longdate} [${level}] [${callsite}] ${message}' concurrentWrites='true' keepFileOpen='false' /> <target name='debugFile' type='File' fileName='" + Path.Combine(tempDir, app1DebugNm + fileExt) + @"' archiveFileName='" + Path.Combine(archivePath, @"${date:format=" + dateFormat + "}-" + app1DebugNm + fileExt) + @"' archiveEvery='minute' archiveOldFileOnStartup='true' maxArchiveFiles='" + maxArchiveFilesConfig + @"' layout='${longdate} [${level}] [${callsite}] ${message}' concurrentWrites='true' keepFileOpen='false' /> </targets> <rules> <logger name='*' minLevel='Trace' writeTo='traceFile' /> <logger name='*' minLevel='Debug' writeTo='debugFile' /> </rules> </nlog>"); var app2Config = XmlLoggingConfiguration.CreateFromXmlString(@"<nlog throwExceptions='true'> <targets> <target name='logfile' type='File' fileName='" + Path.Combine(tempDir, app2Nm + fileExt) + @"' archiveFileName='" + Path.Combine(archivePath, @"${date:format=" + dateFormat + "}-" + app2Nm + fileExt) + @"' archiveEvery='minute' archiveOldFileOnStartup='true' maxArchiveFiles='" + maxArchiveFilesConfig + @"' layout='${longdate} [${level}] [${callsite}] ${message}' concurrentWrites='true' keepFileOpen='false' /> </targets>; <rules> <logger name='*' minLevel='Trace' writeTo='logfile' /> </rules> </nlog>"); LogManager.Configuration = app1Config; var logger = LogManager.GetCurrentClassLogger(); // Trigger archive to happen on startup logger.Trace("Test 1 - Write to the log file that already exists; trigger archive to happen because archiveOldFileOnStartup='true'"); // TODO: perhaps extra App1 Debug and Trace files should both be deleted? (then app1TraceTargetFileCnt would be expected to = expectedArchiveFiles too) // I think it depends on how NLog works with logging to both of those files in the call to logger.Debug() above // verify file counts. EXPECTED OUTCOME: // app1 trace target: removed all extra // app1 debug target: has all extra files // app2: has all extra files var app1TraceTargetFileCnt = archiveDir.GetFiles("*" + app1TraceNm + "*").Length; var app1DebugTargetFileCnt = archiveDir.GetFiles("*" + app1DebugNm + "*").Length; var app2FileTargetCnt = archiveDir.GetFiles("*" + app2Nm + "*").Length; Assert.Equal(numberFilesCreatedPerTargetArchive, app1DebugTargetFileCnt); Assert.Equal(numberFilesCreatedPerTargetArchive, app2FileTargetCnt); Assert.Equal(expectedArchiveFiles, app1TraceTargetFileCnt); } finally { //cleanup LogManager.Configuration = null; archiveDir.Delete(true); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } /// <summary> /// Test the case when multiple applications are archiving to the same directory. /// Only the archives for this application instance should be deleted per the target archive rules. /// </summary> /// <param name="maxArchiveFilesConfig"># to use for maxArchiveFiles in NLog configuration.</param> /// <param name="expectedArchiveFiles">Expected number of archive files after archiving has occured.</param> /// <param name="dateFormat">string to be used for formatting log file names</param> /// <param name="changeCreationAndWriteTime"></param> private static void HandleArchiveFilesMultipleContextSingleTargetsTest( int maxArchiveFilesConfig, int expectedArchiveFiles, string dateFormat, bool changeCreationAndWriteTime) { string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); string archivePath = Path.Combine(tempDir, "archive"); var archiveDir = new DirectoryInfo(archivePath); try { archiveDir.Create(); var numberFilesCreatedPerTargetArchive = 30; // use same config vars for mock files, as for nlog config var fileExt = ".log"; var app1Nm = "App1"; var app2Nm = "App2"; var now = DateTime.Now; var i = 0; // create mock app1 archives (matches app1 config for target) foreach (string filePath in ArchiveFileNamesGenerator(archivePath, dateFormat, app1Nm + fileExt).Take(numberFilesCreatedPerTargetArchive)) { File.WriteAllLines(filePath, new[] { "test archive ", "=====", filePath }); var time = now.AddDays(i); if (changeCreationAndWriteTime) { File.SetCreationTime(filePath, time); File.SetLastWriteTime(filePath, time); } i--; } i = 0; // create mock app2 archives (matches app2 config for target) foreach (string filePath in ArchiveFileNamesGenerator(archivePath, dateFormat, app2Nm + fileExt).Take(numberFilesCreatedPerTargetArchive)) { File.WriteAllLines(filePath, new[] { "test archive ", "=====", filePath }); var time = now.AddDays(i); if (changeCreationAndWriteTime) { File.SetCreationTime(filePath, time); File.SetLastWriteTime(filePath, time); } i--; } // Create same app1 file as config defines. Will force archiving to happen on startup File.WriteAllLines(Path.Combine(tempDir, app1Nm + fileExt), new[] { "Write first app debug target. Startup will archive this file" }, Encoding.ASCII); var app1Config = XmlLoggingConfiguration.CreateFromXmlString(@"<nlog throwExceptions='true'> <targets> <target name='logfile' type='File' fileName='" + Path.Combine(tempDir, app1Nm + fileExt) + @"' archiveFileName='" + Path.Combine(archivePath, @"${date:format=" + dateFormat + "}-" + app1Nm + fileExt) + @"' archiveEvery='minute' archiveOldFileOnStartup='true' maxArchiveFiles='" + maxArchiveFilesConfig + @"' layout='${longdate} [${level}] [${callsite}] ${message}' concurrentWrites='true' keepFileOpen='false' /> </targets>; <rules> <logger name='*' minLevel='Trace' writeTo='logfile' /> </rules> </nlog>"); var app2Config = XmlLoggingConfiguration.CreateFromXmlString(@"<nlog throwExceptions='true'> <targets> <target name='logfile' type='File' fileName='" + Path.Combine(tempDir, app2Nm + fileExt) + @"' archiveFileName='" + Path.Combine(archivePath, @"${date:format=" + dateFormat + "}-" + app2Nm + fileExt) + @"' archiveEvery='minute' archiveOldFileOnStartup='true' maxArchiveFiles='" + maxArchiveFilesConfig + @"' layout='${longdate} [${level}] [${callsite}] ${message}' concurrentWrites='true' keepFileOpen='false' /> </targets>; <rules> <logger name='*' minLevel='Trace' writeTo='logfile' /> </rules> </nlog>"); LogManager.Configuration = app1Config; var logger = LogManager.GetCurrentClassLogger(); // Trigger archive to happen on startup logger.Debug("Test 1 - Write to the log file that already exists; trigger archive to happen because archiveOldFileOnStartup='true'"); // verify file counts. EXPECTED OUTCOME: // app1: Removed extra archives // app2: Has all extra archives var app1TargetFileCnt = archiveDir.GetFiles("*" + app1Nm + "*").Length; var app2FileTargetCnt = archiveDir.GetFiles("*" + app2Nm + "*").Length; Assert.Equal(numberFilesCreatedPerTargetArchive, app2FileTargetCnt); Assert.Equal(expectedArchiveFiles, app1TargetFileCnt); } finally { //cleanup LogManager.Configuration = null; archiveDir.Delete(true); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } /// <summary> /// Generate unlimited archivefiles names. Don't use toList on this ;) /// </summary> /// <param name="path"></param> /// <param name="dateFormat"></param> /// <param name="fileExt">fileext with .</param> /// <returns></returns> private static IEnumerable<string> ArchiveFileNamesGenerator(string path, string dateFormat, string fileExt) { //yyyyMMdd-HHmm int dateOffset = 1; var now = DateTime.Now; while (true) { dateOffset--; yield return Path.Combine(path, now.AddDays(dateOffset).ToString(dateFormat) + fileExt); } } [Fact] public void RelativeFileNaming_ShouldSuccess() { var relativeFileName = @"Logs\myapp.log"; var fullFilePath = Path.GetFullPath(relativeFileName); try { var fileTarget = new FileTarget { FileName = fullFilePath, LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", OpenFileCacheTimeout = 0 }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(fullFilePath, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } finally { if (File.Exists(fullFilePath)) File.Delete(fullFilePath); } } [Fact] public void RelativeFileNaming_DirectoryNavigation_ShouldSuccess() { var relativeFileName = @"..\..\Logs\myapp.log"; var fullFilePath = Path.GetFullPath(relativeFileName); try { var fileTarget = new FileTarget { FileName = fullFilePath, LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", OpenFileCacheTimeout = 0 }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(fullFilePath, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } finally { if (File.Exists(fullFilePath)) File.Delete(fullFilePath); } } [Fact] public void RelativeSequentialArchiveTest_MaxArchiveFiles_0() { string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logfile = Path.Combine(tempDir, "file.txt"); try { string archiveFolder = Path.Combine(tempDir, "archive"); var fileTarget = new FileTarget { FileName = logfile, ArchiveFileName = Path.Combine(archiveFolder, "{####}.txt"), ArchiveAboveSize = 100, ArchiveOldFileOnStartup = true, // Verify ArchiveOldFileOnStartup works together with ArchiveAboveSize LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Sequence, Layout = "${message}", MaxArchiveFiles = 0 }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); logfile = Path.GetFullPath(logfile); // we emit 5 * 25 *(3 x aaa + \n) bytes // so that we should get a full file + 4 archives Generate100BytesLog('a'); Generate100BytesLog('b'); Generate100BytesLog('c'); Generate100BytesLog('d'); Generate100BytesLog('e'); LogManager.Configuration = null; var times = 25; AssertFileContents(logfile, StringRepeat(times, "eee\n"), Encoding.UTF8); AssertFileContents( Path.Combine(archiveFolder, "0000.txt"), StringRepeat(times, "aaa\n"), Encoding.UTF8); AssertFileContents( Path.Combine(archiveFolder, "0001.txt"), StringRepeat(times, "bbb\n"), Encoding.UTF8); AssertFileContents( Path.Combine(archiveFolder, "0002.txt"), StringRepeat(times, "ccc\n"), Encoding.UTF8); AssertFileContents( Path.Combine(archiveFolder, "0003.txt"), StringRepeat(times, "ddd\n"), Encoding.UTF8); Assert.True(!File.Exists(Path.Combine(archiveFolder, "0004.txt"))); } finally { if (File.Exists(logfile)) File.Delete(logfile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void TestFilenameCleanup() { var invalidChars = Path.GetInvalidFileNameChars(); var invalidFileName = Path.DirectorySeparatorChar.ToString(); var expectedFileName = ""; for (int i = 0; i < invalidChars.Length; i++) { var invalidChar = invalidChars[i]; if (invalidChar == Path.DirectorySeparatorChar || invalidChar == Path.AltDirectorySeparatorChar) { //ignore, won't used in cleanup (but for find filename in path) continue; } invalidFileName += i + invalidChar.ToString(); //underscore is used for clean expectedFileName += i + "_"; } //under mono this the invalid chars is sometimes only 1 char (so min width 2) Assert.True(invalidFileName.Length >= 2); //CleanupFileName is default true; var fileTarget = new FileTarget(); fileTarget.FileName = invalidFileName; var filePathLayout = new NLog.Internal.FilePathLayout(invalidFileName, true, FilePathKind.Absolute); var path = filePathLayout.Render(LogEventInfo.CreateNullEvent()); Assert.Equal(expectedFileName, path); } [Theory] [InlineData(DayOfWeek.Sunday, "2017-03-02 15:27:34.651", "2017-03-05 15:27:34.651")] // On a Thursday, finding next Sunday [InlineData(DayOfWeek.Thursday, "2017-03-02 15:27:34.651", "2017-03-09 15:27:34.651")] // On a Thursday, finding next Thursday [InlineData(DayOfWeek.Monday, "2017-03-02 00:00:00.000", "2017-03-06 00:00:00.000")] // On Thursday at Midnight, finding next Monday public void TestCalculateNextWeekday(DayOfWeek day, string todayString, string expectedString) { DateTime today = DateTime.Parse(todayString); DateTime expected = DateTime.Parse(expectedString); DateTime actual = FileTarget.CalculateNextWeekday(today, day); Assert.Equal(expected, actual); } [Theory] [InlineData("UTF-16", true)] [InlineData("UTF-16BE", true)] [InlineData("UTF-32", true)] [InlineData("UTF-32BE", true)] #if !NET6_0_OR_GREATER [InlineData("UTF-7", false)] #endif [InlineData("UTF-8", false)] [InlineData("ASCII", false)] public void TestInitialBomValue(string encodingName, bool expected) { var fileTarget = new FileTarget(); // Act fileTarget.Encoding = Encoding.GetEncoding(encodingName); // Assert Assert.Equal(expected, fileTarget.WriteBom); } [Fact] public void BatchErrorHandlingTest() { using (new NoThrowNLogExceptions()) { var fileTarget = new FileTarget { FileName = "${logger}", Layout = "${message}", ArchiveAboveSize = 10, DiscardAll = true }; fileTarget.Initialize(null); // make sure that when file names get sorted, the asynchronous continuations are sorted with them as well var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "file99.txt", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "", "msg2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "", "msg3").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "", "msg4").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "file99.txt", "msg5").WithContinuation(exceptions.Add), }; fileTarget.WriteAsyncLogEvents(events); LogManager.Flush(); Assert.Equal(5, exceptions.Count); Assert.Null(exceptions[0]); Assert.Null(exceptions[1]); // Will be written together Assert.NotNull(exceptions[2]); Assert.NotNull(exceptions[3]); Assert.NotNull(exceptions[4]); } } [Fact] public void BatchBufferOverflowTest() { string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logfile = Path.Combine(tempDir, "file.txt"); try { // Arrange var fileTarget = new FileTarget { FileName = logfile, BufferSize = 5, LineEnding = LineEndingMode.LF, Layout = "${message}", Encoding = Encoding.UTF8, }; fileTarget.Initialize(null); var result = new List<int>(); var events = new List<NLog.Common.AsyncLogEventInfo>(); var times = 200; for (int i = 1; i <= times; ++i) { int counter = i; events.Add(new LogEventInfo(LogLevel.Info, "logger", counter.ToString()).WithContinuation(ex => result.Add(ex is null ? counter : -1))); } // Act fileTarget.WriteAsyncLogEvents(events); fileTarget.Close(); // Assert Assert.Equal(Enumerable.Range(1, times).ToList(), result); AssertFileContents(logfile, string.Join("\n", result.ToArray()) + "\n", Encoding.UTF8); } finally { if (File.Exists(logfile)) File.Delete(logfile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void HandleArchiveFileAlreadyExistsTest_noBom() { //NO bom var utf8nobom = new UTF8Encoding(false); HandleArchiveFileAlreadyExistsTest(utf8nobom, false); } [Fact] public void HandleArchiveFileAlreadyExistsTest_withBom() { // bom var utf8nobom = new UTF8Encoding(true); HandleArchiveFileAlreadyExistsTest(utf8nobom, true); } [Fact] public void HandleArchiveFileAlreadyExistsTest_ascii() { //NO bom var encoding = Encoding.ASCII; HandleArchiveFileAlreadyExistsTest(encoding, false); } private static void HandleArchiveFileAlreadyExistsTest(Encoding encoding, bool hasBom) { var tempDir = Path.Combine(Path.GetTempPath(), "HandleArchiveFileAlreadyExistsTest-" + Guid.NewGuid()); string logFile = Path.Combine(tempDir, "log.txt"); try { // set log file access times the same way as when this issue comes up. Directory.CreateDirectory(tempDir); File.WriteAllText(logFile, "some content" + Environment.NewLine, encoding); var oldTime = DateTime.Now.AddDays(-2); File.SetCreationTime(logFile, oldTime); File.SetLastWriteTime(logFile, oldTime); File.SetLastAccessTime(logFile, oldTime); //write to archive directly var archiveDateFormat = "yyyy-MM-dd"; var archiveFileNamePattern = Path.Combine(tempDir, "log-{#}.txt"); var archiveFileName = archiveFileNamePattern.Replace("{#}", oldTime.ToString(archiveDateFormat)); File.WriteAllText(archiveFileName, "message already in archive" + Environment.NewLine, encoding); LogManager.ThrowExceptions = true; // configure nlog var fileTarget = new FileTarget("file") { FileName = logFile, ArchiveEvery = FileArchivePeriod.Day, ArchiveFileName = archiveFileNamePattern, ArchiveNumbering = ArchiveNumberingMode.Date, ArchiveDateFormat = archiveDateFormat, Encoding = encoding, Layout = "${message}", WriteBom = hasBom, }; var config = new LoggingConfiguration(); config.AddTarget(fileTarget); config.AddRuleForAllLevels(fileTarget); LogManager.Configuration = config; var logger = LogManager.GetLogger("HandleArchiveFileAlreadyExistsTest"); // write, this should append. logger.Info("log to force archiving"); logger.Info("log to same file"); LogManager.Configuration = null; // Flush AssertFileContents(archiveFileName, "message already in archive" + Environment.NewLine + "some content" + Environment.NewLine, encoding, hasBom); AssertFileContents(logFile, "log to force archiving" + Environment.NewLine + "log to same file" + Environment.NewLine, encoding, hasBom); } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void DontCrashWhenDateAndSequenceDoesntMatchFiles() { var tempDir = Path.Combine(Path.GetTempPath(), "DontCrashWhenDateAndSequenceDoesntMatchFiles-" + Guid.NewGuid()); string logFile = Path.Combine(tempDir, "log.txt"); try { // set log file access times the same way as when this issue comes up. Directory.CreateDirectory(tempDir); File.WriteAllText(logFile, "some content" + Environment.NewLine); var oldTime = DateTime.Now.AddDays(-2); File.SetCreationTime(logFile, oldTime); File.SetLastWriteTime(logFile, oldTime); File.SetLastAccessTime(logFile, oldTime); //write to archive directly var archiveDateFormat = "yyyyMMdd"; var archiveFileNamePattern = Path.Combine(tempDir, "log-{#}.txt"); var archiveFileName = archiveFileNamePattern.Replace("{#}", oldTime.ToString(archiveDateFormat)); File.WriteAllText(archiveFileName, "some archive content"); LogManager.ThrowExceptions = true; // configure nlog var fileTarget = new FileTarget("file") { FileName = logFile, ArchiveEvery = FileArchivePeriod.Day, ArchiveFileName = "log-{#}.txt", ArchiveNumbering = ArchiveNumberingMode.DateAndSequence, ArchiveAboveSize = 50000, MaxArchiveFiles = 7 }; var config = new LoggingConfiguration(); config.AddRuleForAllLevels(fileTarget); LogManager.Configuration = config; // write var logger = LogManager.GetLogger("DontCrashWhenDateAndSequenceDoesntMatchFiles"); logger.Info("Log message"); LogManager.Configuration = null; Assert.True(File.Exists(logFile)); } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Theory] [InlineData(true, 100, true)] // archive, as size of file is 101 [InlineData(true, 101, false)] //equals is not above [InlineData(true, 102, false)] // don;t archive, we didn't reach the aboveSize [InlineData(false, 100, false)] [InlineData(null, 0, false)] [InlineData(null, 99, true)] [InlineData(null, 100, true)] [InlineData(null, 101, false)] public void ShouldArchiveOldFileOnStartupTest(bool? archiveOldFileOnStartup, long archiveOldFileOnStartupAboveSize, bool expected) { // Arrange var fileAppenderCacheMock = Substitute.For<NLog.Internal.FileAppenders.IFileAppenderCache>(); var filePath = "x:/somewhere/file.txt"; fileAppenderCacheMock.GetFileLength(filePath).Returns(101); var target = new FileTarget(fileAppenderCacheMock) { ArchiveOldFileOnStartupAboveSize = archiveOldFileOnStartupAboveSize }; if (archiveOldFileOnStartup.HasValue) { target.ArchiveOldFileOnStartup = archiveOldFileOnStartup.Value; } // Act var result = target.ShouldArchiveOldFileOnStartup(filePath); // Assert Assert.Equal(expected, result); } [Fact] public void ShouldNotArchiveWhenMeetingOldLogEventTimestamps() { var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempDir, "file.txt"); try { string archiveFolder = Path.Combine(tempDir, "archive"); var fileTarget = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(archiveFolder, "{####}.txt"), ArchiveEvery = FileArchivePeriod.Day, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Sequence, Layout = "${message}", }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(fileTarget)); var logger = LogManager.GetLogger(nameof(ShouldNotArchiveWhenMeetingOldLogEventTimestamps)); logger.Info("123"); logger.Info("456"); logger.Log(new LogEventInfo(LogLevel.Info, null, "789") { TimeStamp = NLog.Time.TimeSource.Current.Time.AddDays(-2) }); logger.Log(new LogEventInfo(LogLevel.Info, null, "123") { TimeStamp = NLog.Time.TimeSource.Current.Time.AddDays(-2) }); logger.Info("456"); logger.Log(new LogEventInfo(LogLevel.Info, null, "123") { TimeStamp = NLog.Time.TimeSource.Current.Time.AddDays(1) }); LogManager.Configuration = null; // Flush AssertFileContents(logFile, "123\n", Encoding.UTF8); AssertFileContents( Path.Combine(archiveFolder, "0000.txt"), "123\n456\n789\n123\n456\n", Encoding.UTF8); Assert.True(!File.Exists(Path.Combine(archiveFolder, "0001.txt"))); } finally { if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Collections.Generic; using System.Globalization; using System.Text; using NLog.Internal; using NLog.Layouts; /// <summary> /// Renders the nested states from <see cref="ScopeContext"/> like a callstack /// </summary> [LayoutRenderer("scopenested")] public sealed class ScopeContextNestedStatesLayoutRenderer : LayoutRenderer { /// <summary> /// Gets or sets the number of top stack frames to be rendered. /// </summary> /// <docgen category='Layout Options' order='100' /> public int TopFrames { get; set; } = -1; /// <summary> /// Gets or sets the number of bottom stack frames to be rendered. /// </summary> /// <docgen category='Layout Options' order='100' /> public int BottomFrames { get; set; } = -1; /// <summary> /// Gets or sets the separator to be used for concatenating nested logical context output. /// </summary> /// <docgen category='Layout Options' order='100' /> public string Separator { get => _separator?.OriginalText; set => _separator = new SimpleLayout(value ?? string.Empty); } private SimpleLayout _separator = new SimpleLayout(" "); /// <summary> /// Gets or sets how to format each nested state. Ex. like JSON = @ /// </summary> /// <docgen category='Layout Options' order='50' /> public string Format { get; set; } /// <summary> /// Gets or sets the culture used for rendering. /// </summary> /// <docgen category='Layout Options' order='100' /> public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (TopFrames == 1) { // Allows fast rendering of topframes=1 var topFrame = ScopeContext.PeekNestedState(); if (topFrame != null) builder.AppendFormattedValue(topFrame, Format, GetFormatProvider(logEvent, Culture), ValueFormatter); return; } var messages = ScopeContext.GetAllNestedStateList(); if (messages.Count == 0) return; int startPos = 0; int endPos = messages.Count; if (TopFrames != -1) { endPos = Math.Min(TopFrames, messages.Count); } else if (BottomFrames != -1) { startPos = messages.Count - Math.Min(BottomFrames, messages.Count); } AppendNestedStates(builder, messages, startPos, endPos, logEvent); } private void AppendNestedStates(StringBuilder builder, IList<object> messages, int startPos, int endPos, LogEventInfo logEvent) { bool formatAsJson = MessageTemplates.ValueFormatter.FormatAsJson.Equals(Format, StringComparison.Ordinal); var formatProvider = GetFormatProvider(logEvent, Culture); string separator = null; string itemSeparator = null; if (formatAsJson) { separator = _separator?.Render(logEvent) ?? string.Empty; builder.Append('['); builder.Append(separator); itemSeparator = "," + separator; } try { string currentSeparator = null; for (int i = endPos - 1; i >= startPos; --i) { builder.Append(currentSeparator); if (formatAsJson) AppendJsonFormattedValue(messages[i], formatProvider, builder, separator, itemSeparator); else if (messages[i] is IEnumerable<KeyValuePair<string, object>>) builder.Append(Convert.ToString(messages[i])); // Special support for Microsoft Extension Logging ILogger.BeginScope else builder.AppendFormattedValue(messages[i], Format, formatProvider, ValueFormatter); currentSeparator = itemSeparator ?? _separator?.Render(logEvent) ?? string.Empty; } } finally { if (formatAsJson) { builder.Append(separator); builder.Append(']'); } } } private void AppendJsonFormattedValue(object nestedState, IFormatProvider formatProvider, StringBuilder builder, string separator, string itemSeparator) { if (nestedState is IEnumerable<KeyValuePair<string, object>> propertyList && HasUniqueCollectionKeys(propertyList)) { // Special support for Microsoft Extension Logging ILogger.BeginScope where property-states are rendered as expando-objects builder.Append('{'); builder.Append(separator); string currentSeparator = string.Empty; using (var scopeEnumerator = new ScopeContextPropertyEnumerator<object>(propertyList)) { while (scopeEnumerator.MoveNext()) { var property = scopeEnumerator.Current; int orgLength = builder.Length; if (!AppendJsonProperty(property.Key, property.Value, builder, currentSeparator)) { builder.Length = orgLength; continue; } currentSeparator = itemSeparator; } } builder.Append(separator); builder.Append('}'); } else { builder.AppendFormattedValue(nestedState, Format, formatProvider, ValueFormatter); } } bool AppendJsonProperty(string propertyName, object propertyValue, StringBuilder builder, string itemSeparator) { if (string.IsNullOrEmpty(propertyName)) return false; builder.Append(itemSeparator); if (!ValueFormatter.FormatValue(propertyName, null, MessageTemplates.CaptureType.Serialize, null, builder)) { return false; } builder.Append(": "); if (!ValueFormatter.FormatValue(propertyValue, null, MessageTemplates.CaptureType.Serialize, null, builder)) { return false; } return true; } bool HasUniqueCollectionKeys(IEnumerable<KeyValuePair<string, object>> propertyList) { if (propertyList is IDictionary<string, object>) { return true; } #if !NET35 else if (propertyList is IReadOnlyDictionary<string, object>) { return true; } else if (propertyList is IReadOnlyCollection<KeyValuePair<string, object>> propertyCollection) { if (propertyCollection.Count <= 1) return true; else if (propertyCollection.Count > 10) return false; // Too many combinations } #endif return ScopeContextPropertyEnumerator<object>.HasUniqueCollectionKeys(propertyList, StringComparer.Ordinal); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 && !NETSTANDARD1_5 namespace NLog.Internal.NetworkSenders { using System; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; internal sealed class SslSocketProxy : ISocket, IDisposable { readonly AsyncCallback _sendCompleted; readonly SocketProxy _socketProxy; readonly string _host; readonly SslProtocols _sslProtocol; SslStream _sslStream; public SslSocketProxy(string host, SslProtocols sslProtocol, SocketProxy socketProxy) { _socketProxy = socketProxy; _host = host; _sslProtocol = sslProtocol; _sendCompleted = (ar) => SocketProxySendCompleted(ar); } public void Close() { if (_sslStream != null) _sslStream.Close(); else _socketProxy.Close(); } public bool ConnectAsync(SocketAsyncEventArgs args) { var proxyArgs = new TcpNetworkSender.MySocketAsyncEventArgs(); proxyArgs.RemoteEndPoint = args.RemoteEndPoint; proxyArgs.Completed += SocketProxyConnectCompleted; proxyArgs.UserToken = args; if (!_socketProxy.ConnectAsync(proxyArgs)) { SocketProxyConnectCompleted(this, proxyArgs); return false; } return true; } private void SocketProxySendCompleted(IAsyncResult asyncResult) { var proxyArgs = asyncResult.AsyncState as TcpNetworkSender.MySocketAsyncEventArgs; try { _sslStream.EndWrite(asyncResult); } catch (SocketException ex) { if (proxyArgs != null) proxyArgs.SocketError = ex.SocketErrorCode; } catch (Exception ex) { if (proxyArgs != null) { if (ex.InnerException is SocketException socketException) proxyArgs.SocketError = socketException.SocketErrorCode; else proxyArgs.SocketError = SocketError.OperationAborted; } } finally { proxyArgs?.RaiseCompleted(); } } private void SocketProxyConnectCompleted(object sender, SocketAsyncEventArgs e) { var proxyArgs = e.UserToken as TcpNetworkSender.MySocketAsyncEventArgs; if (e.SocketError != SocketError.Success) { if (proxyArgs != null) { proxyArgs.SocketError = e.SocketError; proxyArgs.RaiseCompleted(); } } else { try { _sslStream = new SslStream(new NetworkStream(_socketProxy.UnderlyingSocket), false, UserCertificateValidationCallback) { // Wait 20 secs before giving up on SSL-handshake ReadTimeout = 20000 }; AuthenticateAsClient(_sslStream, _host, _sslProtocol); } catch (SocketException ex) { if (proxyArgs != null) proxyArgs.SocketError = ex.SocketErrorCode; } catch (Exception ex) { if (proxyArgs != null) { proxyArgs.SocketError = GetSocketError(ex); } } finally { proxyArgs?.RaiseCompleted(); } } } private static SocketError GetSocketError(Exception ex) { SocketError socketError; if (ex.InnerException is SocketException socketException) { socketError = socketException.SocketErrorCode; } else { socketError = SocketError.ConnectionRefused; } return socketError; } private static void AuthenticateAsClient(SslStream sslStream, string targetHost, SslProtocols enabledSslProtocols) { if (enabledSslProtocols != SslProtocols.Default) sslStream.AuthenticateAsClient(targetHost, null, enabledSslProtocols, false); else sslStream.AuthenticateAsClient(targetHost); } private static bool UserCertificateValidationCallback(object sender, object certificate, object chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) return true; Common.InternalLogger.Debug("SSL certificate errors were encountered when establishing connection to the server: {0}, Certificate: {1}", sslPolicyErrors, certificate); return false; } public bool SendAsync(SocketAsyncEventArgs args) { _sslStream.BeginWrite(args.Buffer, args.Offset, args.Count, _sendCompleted, args); return true; } public bool SendToAsync(SocketAsyncEventArgs args) { return SendAsync(args); } public void Dispose() { if (_sslStream != null) _sslStream.Dispose(); else _socketProxy.Dispose(); } } } #endif <file_sep>using NLog; using NLog.Win32.Targets; class Example { static void Main(string[] args) { ColoredConsoleTarget target = new ColoredConsoleTarget(); target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; target.RowHighlightingRules.Add( new ConsoleRowHighlightingRule( "level >= LogLevel.Error and contains(message,'serious')", // condition ConsoleOutputColor.White, // foreground color ConsoleOutputColor.Red // background color ) ); target.RowHighlightingRules.Add( new ConsoleRowHighlightingRule( "starts-with(logger,'Example')", // condition ConsoleOutputColor.Yellow, // foreground color ConsoleOutputColor.DarkBlue) // background color ); NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace); // LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration("ColoredConsoleTargetRowHighlighting.nlog"); Logger logger = LogManager.GetLogger("Example"); logger.Trace("trace log message"); logger.Debug("debug log message"); logger.Info("info log message"); logger.Warn("warn log message"); logger.Error("very serious error log message"); logger.Fatal("fatal log message, rather serious"); Logger logger2 = LogManager.GetLogger("Another"); logger2.Trace("trace log message"); logger2.Debug("debug log message"); logger2.Info("info log message"); logger2.Warn("warn log message"); logger2.Error("very serious error log message"); logger2.Fatal("fatal log message"); } } <file_sep>using NLog; using NLog.Win32.Targets; class Example { static void Main(string[] args) { ColoredConsoleTarget target = new ColoredConsoleTarget(); target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace); Logger logger = LogManager.GetLogger("Example"); logger.Trace("trace log message"); logger.Debug("debug log message"); logger.Info("info log message"); logger.Warn("warn log message"); logger.Error("error log message"); logger.Fatal("fatal log message"); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NET35 && !NET40 namespace NLog.Targets { using System.IO; using System.IO.Compression; /// <summary> /// Builtin IFileCompressor implementation utilizing the .Net4.5 specific <see cref="ZipArchive"/> /// and is used as the default value for <see cref="FileTarget.FileCompressor"/> on .Net4.5. /// So log files created via <see cref="FileTarget"/> can be zipped when archived /// w/o 3rd party zip library when run on .Net4.5 or higher. /// </summary> internal class ZipArchiveFileCompressor : IArchiveFileCompressor { /// <summary> /// Implements <see cref="IFileCompressor.CompressFile(string, string)"/> using the .Net4.5 specific <see cref="ZipArchive"/> /// </summary> public void CompressFile(string fileName, string archiveFileName) { string entryName = Path.GetFileNameWithoutExtension(archiveFileName) + Path.GetExtension(fileName); CompressFile(fileName, archiveFileName, entryName); } public void CompressFile(string fileName, string archiveFileName, string entryName) { using (var originalFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var archiveStream = new FileStream(archiveFileName, FileMode.CreateNew)) using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create)) { var zipArchiveEntry = archive.CreateEntry(entryName); using (var destination = zipArchiveEntry.Open()) { originalFileStream.CopyTo(destination); } } } } } #endif <file_sep>// // Copyright (c) 2004-2016 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace MakeNLogXSD { using System; using System.Collections.Generic; class Program { public static int Main(string[] args) { try { var apiFiles = new List<string>(); string outputFile = "NLog.xsd"; string targetNamespace = "http://www.nlog-project.org/schemas/NLog.xsd"; for (int i = 0; i < args.Length; ++i) { string argName; if (args[i].StartsWith("/") || args[i].StartsWith("-")) { argName = args[i].Substring(1).ToLowerInvariant(); } else { argName = "?"; } switch (argName) { case "api": apiFiles.Add(args[++i]); break; case "out": outputFile = args[++i]; break; case "xmlns": targetNamespace = args[++i]; break; default: Usage(); return 1; } } if (apiFiles.Count == 0) { Console.WriteLine("API files not specified."); Usage(); return 1; } if (string.IsNullOrEmpty(outputFile)) { Console.WriteLine("Output file not specified."); Usage(); return 1; } var xsdFileGenerator = new XsdFileGenerator(); xsdFileGenerator.TargetNamespace = targetNamespace; foreach (string apiFile in apiFiles) { xsdFileGenerator.ProcessApiFile(apiFile); } xsdFileGenerator.SaveResult(outputFile); return 0; } catch (Exception ex) { Console.WriteLine("ERROR: {0}", ex); return 1; } } private static void Usage() { Console.WriteLine("MakeNLogXSD -api inputFile.api [-out outputFile] [-xmlns namespace]"); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Text; using System.Threading; using JetBrains.Annotations; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Internal.Fakeables; using NLog.Targets; /// <summary> /// Creates and manages instances of <see cref="NLog.Logger" /> objects. /// </summary> public class LogFactory : IDisposable { private static readonly TimeSpan DefaultFlushTimeout = TimeSpan.FromSeconds(15); [Obsolete("For unit testing only. Marked obsolete on NLog 5.0")] private static IAppDomain currentAppDomain; private static AppEnvironmentWrapper defaultAppEnvironment; /// <remarks> /// Internal for unit tests /// </remarks> internal readonly object _syncRoot = new object(); private readonly LoggerCache _loggerCache = new LoggerCache(); [NotNull] private ServiceRepositoryInternal _serviceRepository = new ServiceRepositoryInternal(); private IAppEnvironment _currentAppEnvironment; internal LoggingConfiguration _config; internal LogMessageFormatter ActiveMessageFormatter; internal LogMessageFormatter SingleTargetMessageFormatter; private LogLevel _globalThreshold = LogLevel.MinLevel; private bool _configLoaded; private int _supendLoggingCounter; /// <summary> /// Overwrite possible file paths (including filename) for possible NLog config files. /// When this property is <c>null</c>, the default file paths (<see cref="GetCandidateConfigFilePaths()"/> are used. /// </summary> [Obsolete("Replaced by LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] private List<string> _candidateConfigFilePaths; private readonly ILoggingConfigurationLoader _configLoader; /// <summary> /// Occurs when logging <see cref="Configuration" /> changes. /// </summary> public event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged; #if !NETSTANDARD1_3 /// <summary> /// Occurs when logging <see cref="Configuration" /> gets reloaded. /// </summary> [Obsolete("Replaced by ConfigurationChanged, but check args.ActivatedConfiguration != null. Marked obsolete on NLog 5.2")] public event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded; #endif private static event EventHandler<EventArgs> LoggerShutdown; #if !NETSTANDARD1_3 /// <summary> /// Initializes static members of the LogManager class. /// </summary> static LogFactory() { RegisterEvents(DefaultAppEnvironment); } #endif /// <summary> /// Initializes a new instance of the <see cref="LogFactory" /> class. /// </summary> public LogFactory() #pragma warning disable CS0618 // Type or member is obsolete #if !NETSTANDARD1_3 : this(new LoggingConfigurationWatchableFileLoader(DefaultAppEnvironment)) #else : this(new LoggingConfigurationFileLoader(DefaultAppEnvironment)) #endif #pragma warning restore CS0618 // Type or member is obsolete { _serviceRepository.TypeRegistered += ServiceRepository_TypeRegistered; RefreshMessageFormatter(); } /// <summary> /// Initializes a new instance of the <see cref="LogFactory" /> class. /// </summary> /// <param name="config">The config.</param> [Obsolete("Constructor with LoggingConfiguration as parameter should not be used. Instead provide LogFactory as parameter when constructing LoggingConfiguration. Marked obsolete in NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public LogFactory(LoggingConfiguration config) : this() { Configuration = config; } /// <summary> /// Initializes a new instance of the <see cref="LogFactory" /> class. /// </summary> /// <param name="configLoader">The config loader</param> /// <param name="appEnvironment">The custom AppEnvironmnet override</param> internal LogFactory(ILoggingConfigurationLoader configLoader, IAppEnvironment appEnvironment = null) { _configLoader = configLoader; _currentAppEnvironment = appEnvironment; #if !NETSTANDARD1_3 LoggerShutdown += OnStopLogging; #endif } /// <summary> /// Gets the current <see cref="IAppDomain"/>. /// </summary> [Obsolete("For unit testing only. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public static IAppDomain CurrentAppDomain { get => currentAppDomain ?? DefaultAppEnvironment.AppDomain; set { if (defaultAppEnvironment != null) UnregisterEvents(defaultAppEnvironment); currentAppDomain = value; if (value != null && defaultAppEnvironment != null) { defaultAppEnvironment.AppDomain = value; UnregisterEvents(defaultAppEnvironment); RegisterEvents(defaultAppEnvironment); } } } internal static IAppEnvironment DefaultAppEnvironment { get { #pragma warning disable CS0618 // Type or member is obsolete return defaultAppEnvironment ?? (defaultAppEnvironment = new AppEnvironmentWrapper(currentAppDomain ?? (currentAppDomain = #if !NETSTANDARD1_3 && !NETSTANDARD1_5 new AppDomainWrapper(AppDomain.CurrentDomain) #else new FakeAppDomain() #endif ))); #pragma warning restore CS0618 // Type or member is obsolete } } internal IAppEnvironment CurrentAppEnvironment { get => _currentAppEnvironment ?? DefaultAppEnvironment; set => _currentAppEnvironment = value; } /// <summary> /// Gets or sets a value indicating whether exceptions should be thrown. See also <see cref="ThrowConfigExceptions"/>. /// </summary> /// <value>A value of <c>true</c> if exception should be thrown; otherwise, <c>false</c>.</value> /// <remarks>By default exceptions are not thrown under any circumstances.</remarks> public bool ThrowExceptions { get; set; } /// <summary> /// Gets or sets a value indicating whether <see cref="NLogConfigurationException"/> should be thrown. /// /// If <c>null</c> then <see cref="ThrowExceptions"/> is used. /// </summary> /// <value>A value of <c>true</c> if exception should be thrown; otherwise, <c>false</c>.</value> /// <remarks> /// This option is for backwards-compatibility. /// By default exceptions are not thrown under any circumstances. /// </remarks> public bool? ThrowConfigExceptions { get; set; } /// <summary> /// Gets or sets a value indicating whether Variables should be kept on configuration reload. /// </summary> public bool KeepVariablesOnReload { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether to automatically call <see cref="LogFactory.Shutdown"/> /// on AppDomain.Unload or AppDomain.ProcessExit /// </summary> public bool AutoShutdown { get { return _autoShutdown; } set { if (value != _autoShutdown) { _autoShutdown = value; #if !NETSTANDARD1_3 LoggerShutdown -= OnStopLogging; if (value) LoggerShutdown += OnStopLogging; #endif } } } private bool _autoShutdown = true; /// <summary> /// Gets or sets the current logging configuration. /// </summary> /// <remarks> /// Setter will re-configure all <see cref="Logger"/>-objects, so no need to also call <see cref="ReconfigExistingLoggers()" /> /// </remarks> public LoggingConfiguration Configuration { get { if (_configLoaded) return _config; lock (_syncRoot) { if (_configLoaded || _isDisposing) return _config; var config = _configLoader.Load(this); if (config != null) { try { LogNLogAssemblyVersion(); _config = config; _configLoader.Activated(this, _config); _config.Dump(); ReconfigExistingLoggers(); InternalLogger.Info("Configuration initialized."); } finally { _configLoaded = true; } } return _config; } } set { lock (_syncRoot) { LoggingConfiguration oldConfig = _config; if (oldConfig != null) { InternalLogger.Info("Closing old configuration."); Flush(); oldConfig.Close(); } _config = value; if (_config is null) { _configLoaded = false; _configLoader.Activated(this, _config); } else { try { if (oldConfig is null) LogNLogAssemblyVersion(); _configLoader.Activated(this, _config); _config.Dump(); ReconfigExistingLoggers(); InternalLogger.Info("Configuration initialized."); } finally { _configLoaded = true; } } OnConfigurationChanged(new LoggingConfigurationChangedEventArgs(value, oldConfig)); } } } /// <summary> /// Repository of interfaces used by NLog to allow override for dependency injection /// </summary> [NotNull] public ServiceRepository ServiceRepository { get => _serviceRepository; internal set { _serviceRepository.TypeRegistered -= ServiceRepository_TypeRegistered; _serviceRepository = (value as ServiceRepositoryInternal) ?? new ServiceRepositoryInternal(true); _serviceRepository.TypeRegistered += ServiceRepository_TypeRegistered; } } private void ServiceRepository_TypeRegistered(object sender, ServiceRepositoryUpdateEventArgs e) { _config?.CheckForMissingServiceTypes(e.ServiceType); if (e.ServiceType == typeof(ILogMessageFormatter)) { RefreshMessageFormatter(); } } private void RefreshMessageFormatter() { var messageFormatter = _serviceRepository.GetService<ILogMessageFormatter>(); ActiveMessageFormatter = messageFormatter.FormatMessage; if (messageFormatter is LogMessageTemplateFormatter templateFormatter) { SingleTargetMessageFormatter = new LogMessageTemplateFormatter(_serviceRepository, templateFormatter.MessageTemplateParser == true, true).FormatMessage; } else { SingleTargetMessageFormatter = null; } } /// <summary> /// Gets or sets the global log level threshold. Log events below this threshold are not logged. /// </summary> public LogLevel GlobalThreshold { get => _globalThreshold; set { lock (_syncRoot) { if (_globalThreshold != value) { InternalLogger.Info("LogFactory GlobalThreshold changing to LogLevel: {0}", value); } _globalThreshold = value ?? LogLevel.MinLevel; ReconfigExistingLoggers(); } } } /// <summary> /// Gets or sets the default culture info to use as <see cref="LogEventInfo.FormatProvider"/>. /// </summary> /// <value> /// Specific culture info or null to use <see cref="CultureInfo.CurrentCulture"/> /// </value> [CanBeNull] public CultureInfo DefaultCultureInfo { get => _config is null ? _defaultCultureInfo : _config.DefaultCultureInfo; set { if (_config != null && (ReferenceEquals(_config.DefaultCultureInfo, _defaultCultureInfo) || _config.DefaultCultureInfo is null)) _config.DefaultCultureInfo = value; _defaultCultureInfo = value; } } internal CultureInfo _defaultCultureInfo; internal static void LogNLogAssemblyVersion() { if (!InternalLogger.IsInfoEnabled) return; try { InternalLogger.LogAssemblyVersion(typeof(LogFactory).GetAssembly()); } catch (SecurityException ex) { InternalLogger.Debug(ex, "Not running in full trust"); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting /// unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Begins configuration of the LogFactory options using fluent interface /// </summary> public ISetupBuilder Setup() { return new SetupBuilder(this); } /// <summary> /// Begins configuration of the LogFactory options using fluent interface /// </summary> public LogFactory Setup(Action<ISetupBuilder> setupBuilder) { Guard.ThrowIfNull(setupBuilder); setupBuilder(new SetupBuilder(this)); return this; } /// <summary> /// Creates a logger that discards all log messages. /// </summary> /// <returns>Null logger instance.</returns> public Logger CreateNullLogger() { return new NullLogger(this); } /// <summary> /// Gets the logger with the full name of the current class, so namespace and class name. /// </summary> /// <returns>The logger.</returns> /// <remarks>This method introduces performance hit, because of StackTrace capture. /// Make sure you are not calling this method in a loop.</remarks> [MethodImpl(MethodImplOptions.NoInlining)] public Logger GetCurrentClassLogger() { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 var className = StackTraceUsageUtils.GetClassFullName(new StackFrame(1, false)); #else var className = StackTraceUsageUtils.GetClassFullName(); #endif return GetLogger(className); } /// <summary> /// Gets the logger with the full name of the current class, so namespace and class name. /// Use <typeparamref name="T"/> to create instance of a custom <see cref="Logger"/>. /// If you haven't defined your own <see cref="Logger"/> class, then use the overload without the type parameter. /// </summary> /// <returns>The logger with type <typeparamref name="T"/>.</returns> /// <typeparam name="T">Type of the logger</typeparam> /// <remarks>This method introduces performance hit, because of StackTrace capture. /// Make sure you are not calling this method in a loop.</remarks> [MethodImpl(MethodImplOptions.NoInlining)] public T GetCurrentClassLogger<T>() where T : Logger, new() { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 var className = StackTraceUsageUtils.GetClassFullName(new StackFrame(1, false)); #else var className = StackTraceUsageUtils.GetClassFullName(); #endif return GetLogger<T>(className); } /// <summary> /// Gets a custom logger with the full name of the current class, so namespace and class name. /// Use <paramref name="loggerType"/> to create instance of a custom <see cref="Logger"/>. /// If you haven't defined your own <see cref="Logger"/> class, then use the overload without the loggerType. /// </summary> /// <param name="loggerType">The type of the logger to create. The type must inherit from <see cref="Logger"/></param> /// <returns>The logger of type <paramref name="loggerType"/>.</returns> /// <remarks>This method introduces performance hit, because of StackTrace capture. /// Make sure you are not calling this method in a loop.</remarks> [MethodImpl(MethodImplOptions.NoInlining)] [Obsolete("Replaced by GetCurrentClassLogger<T>(). Marked obsolete on NLog 5.2")] public Logger GetCurrentClassLogger([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type loggerType) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 var className = StackTraceUsageUtils.GetClassFullName(new StackFrame(1, false)); #else var className = StackTraceUsageUtils.GetClassFullName(); #endif return GetLogger(className, loggerType ?? typeof(Logger)); } /// <summary> /// Gets the specified named logger. /// </summary> /// <param name="name">Name of the logger.</param> /// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument /// are not guaranteed to return the same logger reference.</returns> public Logger GetLogger(string name) { return GetLoggerThreadSafe(name, Logger.DefaultLoggerType, (t) => new Logger()); } /// <summary> /// Gets the specified named logger. /// Use <typeparamref name="T"/> to create instance of a custom <see cref="Logger"/>. /// If you haven't defined your own <see cref="Logger"/> class, then use the overload without the type parameter. /// </summary> /// <param name="name">Name of the logger.</param> /// <typeparam name="T">Type of the logger</typeparam> /// <returns>The logger reference with type <typeparamref name="T"/>. Multiple calls to <c>GetLogger</c> with the same argument /// are not guaranteed to return the same logger reference.</returns> public T GetLogger<T>(string name) where T : Logger, new() { return (T)GetLoggerThreadSafe(name, typeof(T), (t) => new T()); } /// <summary> /// Gets the specified named logger. /// Use <paramref name="loggerType"/> to create instance of a custom <see cref="Logger"/>. /// If you haven't defined your own <see cref="Logger"/> class, then use the overload without the loggerType. /// </summary> /// <param name="name">Name of the logger.</param> /// <param name="loggerType">The type of the logger to create. The type must inherit from <see cref="Logger" />.</param> /// <returns>The logger of type <paramref name="loggerType"/>. Multiple calls to <c>GetLogger</c> with the /// same argument aren't guaranteed to return the same logger reference.</returns> [Obsolete("Replaced by GetLogger<T>(). Marked obsolete on NLog 5.2")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2067")] public Logger GetLogger(string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type loggerType) { return GetLoggerThreadSafe(name, loggerType ?? typeof(Logger), (t) => Logger.DefaultLoggerType.IsAssignableFrom(t) ? Activator.CreateInstance(t, true) as Logger : null); } private bool RefreshExistingLoggers() { bool purgeObsoleteLoggers; List<Logger> loggers; lock (_syncRoot) { _config?.InitializeAll(); loggers = _loggerCache.GetLoggers(); purgeObsoleteLoggers = loggers.Count != _loggerCache.Count; } foreach (var logger in loggers) { logger.SetConfiguration(BuildLoggerConfiguration(logger.Name, _config)); } return purgeObsoleteLoggers; } /// <summary> /// Loops through all loggers previously returned by GetLogger and recalculates their /// target and filter list. Useful after modifying the configuration programmatically /// to ensure that all loggers have been properly configured. /// </summary> public void ReconfigExistingLoggers() { RefreshExistingLoggers(); } /// <summary> /// Loops through all loggers previously returned by GetLogger and recalculates their /// target and filter list. Useful after modifying the configuration programmatically /// to ensure that all loggers have been properly configured. /// </summary> /// <param name="purgeObsoleteLoggers">Purge garbage collected logger-items from the cache</param> public void ReconfigExistingLoggers(bool purgeObsoleteLoggers) { purgeObsoleteLoggers = RefreshExistingLoggers() && purgeObsoleteLoggers; if (purgeObsoleteLoggers) { lock (_syncRoot) _loggerCache.PurgeObsoleteLoggers(); } } /// <summary> /// Flush any pending log messages (in case of asynchronous targets) with the default timeout of 15 seconds. /// </summary> public void Flush() { Flush(DefaultFlushTimeout); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="timeout">Maximum time to allow for the flush. Any messages after that time /// will be discarded.</param> public void Flush(TimeSpan timeout) { FlushInternal(timeout, null); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages /// after that time will be discarded.</param> public void Flush(int timeoutMilliseconds) { Flush(TimeSpan.FromMilliseconds(timeoutMilliseconds)); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> public void Flush(AsyncContinuation asyncContinuation) { Flush(asyncContinuation, TimeSpan.MaxValue); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages /// after that time will be discarded.</param> public void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds) { Flush(asyncContinuation, TimeSpan.FromMilliseconds(timeoutMilliseconds)); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout) { FlushInternal(timeout, asyncContinuation ?? (ex => { })); } private void FlushInternal(TimeSpan timeout, AsyncContinuation asyncContinuation) { try { InternalLogger.Debug("LogFactory Flush with timeout={0} secs", timeout.TotalSeconds); LoggingConfiguration config; lock (_syncRoot) { config = _config; // Flush should not attempt to auto-load Configuration } if (config != null) { if (asyncContinuation != null) { FlushAllTargetsAsync(config, asyncContinuation, timeout); } else { if (FlushAllTargetsSync(config, timeout, ThrowExceptions)) return; } } else { asyncContinuation?.Invoke(null); } } catch (Exception ex) { if (ThrowExceptions) { throw; } InternalLogger.Error(ex, "LogFactory failed to flush targets."); asyncContinuation?.Invoke(ex); } } /// <summary> /// Flushes any pending log messages on all appenders. /// </summary> /// <param name="loggingConfiguration">Config containing Targets to Flush</param> /// <param name="asyncContinuation">Flush completed notification (success / timeout)</param> /// <param name="asyncTimeout">Optional timeout that guarantees that completed notification is called.</param> /// <returns></returns> private static AsyncContinuation FlushAllTargetsAsync(LoggingConfiguration loggingConfiguration, AsyncContinuation asyncContinuation, TimeSpan? asyncTimeout) { var pendingTargets = loggingConfiguration.GetAllTargetsToFlush(); AsynchronousAction<Target> flushAction = (target, cont) => { target.Flush(ex => { if (ex != null) InternalLogger.Warn(ex, "Flush failed for target {0}(Name={1})", target.GetType(), target.Name); lock (pendingTargets) { pendingTargets.Remove(target); } cont(ex); }); }; AsyncContinuation flushContinuation = (ex) => { lock (pendingTargets) { foreach (var pendingTarget in pendingTargets) InternalLogger.Debug("Flush timeout for target {0}(Name={1})", pendingTarget.GetType(), pendingTarget.Name); pendingTargets.Clear(); } if (ex != null) InternalLogger.Warn(ex, "Flush completed with errors"); else InternalLogger.Debug("Flush completed"); asyncContinuation(ex); }; if (asyncTimeout.HasValue) { flushContinuation = AsyncHelpers.WithTimeout(flushContinuation, asyncTimeout.Value); } else { flushContinuation = AsyncHelpers.PreventMultipleCalls(flushContinuation); } InternalLogger.Trace("Flushing all {0} targets...", pendingTargets.Count); AsyncHelpers.ForEachItemInParallel(pendingTargets, flushContinuation, flushAction); return flushContinuation; } private static bool FlushAllTargetsSync(LoggingConfiguration oldConfig, TimeSpan timeout, bool throwExceptions) { Exception lastException = null; try { ManualResetEvent flushCompletedEvent = new ManualResetEvent(false); var flushContinuation = FlushAllTargetsAsync(oldConfig, (ex) => { if (ex != null) lastException = ex; flushCompletedEvent.Set(); }, null); bool flushCompleted = flushCompletedEvent.WaitOne(timeout); if (!flushCompleted) flushContinuation(new TimeoutException($"Timeout when flushing all targets, after waiting {timeout.TotalSeconds} seconds.")); } catch (Exception ex) { #if DEBUG if (ex.MustBeRethrownImmediately()) throw; // Throwing exceptions here might crash the entire application (.NET 2.0 behavior) #endif InternalLogger.Error(ex, "LogFactory failed to flush targets."); if (throwExceptions) throw new NLogRuntimeException("Asynchronous exception has occurred.", ex); return false; } if (lastException != null) { if (throwExceptions) throw new NLogRuntimeException("Asynchronous exception has occurred.", lastException); else return false; } return true; } /// <summary> /// Suspends the logging, and returns object for using-scope so scope-exit calls <see cref="ResumeLogging"/> /// </summary> /// <remarks> /// Logging is suspended when the number of <see cref="SuspendLogging"/> calls are greater /// than the number of <see cref="ResumeLogging"/> calls. /// </remarks> /// <returns>An object that implements IDisposable whose Dispose() method re-enables logging. /// To be used with C# <c>using ()</c> statement.</returns> public IDisposable SuspendLogging() { lock (_syncRoot) { _supendLoggingCounter++; if (_supendLoggingCounter == 1) { ReconfigExistingLoggers(); } } return new LogEnabler(this); } /// <summary> /// Resumes logging if having called <see cref="SuspendLogging"/>. /// </summary> /// <remarks> /// Logging is suspended when the number of <see cref="SuspendLogging"/> calls are greater /// than the number of <see cref="ResumeLogging"/> calls. /// </remarks> public void ResumeLogging() { lock (_syncRoot) { _supendLoggingCounter--; if (_supendLoggingCounter == 0) { ReconfigExistingLoggers(); } } } /// <summary> /// Returns <see langword="true" /> if logging is currently enabled. /// </summary> /// <remarks> /// Logging is suspended when the number of <see cref="SuspendLogging"/> calls are greater /// than the number of <see cref="ResumeLogging"/> calls. /// </remarks> /// <returns>A value of <see langword="true" /> if logging is currently enabled, /// <see langword="false"/> otherwise.</returns> public bool IsLoggingEnabled() { return _supendLoggingCounter <= 0; } /// <summary> /// Raises the event when the configuration is reloaded. /// </summary> /// <param name="e">Event arguments.</param> protected virtual void OnConfigurationChanged(LoggingConfigurationChangedEventArgs e) { ConfigurationChanged?.Invoke(this, e); } #if !NETSTANDARD1_3 /// <summary> /// Raises the event when the configuration is reloaded. /// </summary> /// <param name="e">Event arguments</param> [Obsolete("Replaced by ConfigurationChanged, but check args.ActivatedConfiguration != null. Marked obsolete on NLog 5.2")] protected virtual void OnConfigurationReloaded(LoggingConfigurationReloadedEventArgs e) { ConfigurationReloaded?.Invoke(this, e); } [Obsolete("Replaced by ConfigurationChanged, but check args.ActivatedConfiguration != null. Marked obsolete on NLog 5.2")] internal void NotifyConfigurationReloaded(LoggingConfigurationReloadedEventArgs eventArgs) { OnConfigurationReloaded(eventArgs); } #endif internal TargetWithFilterChain[] BuildLoggerConfiguration(string loggerName, LoggingConfiguration configuration) { var targetsByLevel = TargetWithFilterChain.BuildLoggerConfiguration(loggerName, configuration, IsLoggingEnabled() ? GlobalThreshold : LogLevel.Off); if (InternalLogger.IsDebugEnabled && !DumpTargetConfigurationForLogger(loggerName, targetsByLevel)) { InternalLogger.Debug("Targets not configured for Logger: {0}", loggerName); } return targetsByLevel; } private static bool DumpTargetConfigurationForLogger(string loggerName, TargetWithFilterChain[] targetsByLevel) { if (ReferenceEquals(targetsByLevel, TargetWithFilterChain.NoTargetsByLevel)) return false; StringBuilder sb = null; for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i) { if (sb != null) { sb.Length = 0; sb.AppendFormat(CultureInfo.InvariantCulture, "Logger {0} [{1}] =>", loggerName, LogLevel.FromOrdinal(i)); } for (TargetWithFilterChain afc = targetsByLevel[i]; afc != null; afc = afc.NextInChain) { if (sb is null) { InternalLogger.Debug("Targets configured when LogLevel >= {0} for Logger: {1}", LogLevel.FromOrdinal(i), loggerName); sb = new StringBuilder(); sb.AppendFormat(CultureInfo.InvariantCulture, "Logger {0} [{1}] =>", loggerName, LogLevel.FromOrdinal(i)); } sb.AppendFormat(CultureInfo.InvariantCulture, " {0}", afc.Target.Name); if (afc.FilterChain.Count > 0) { sb.AppendFormat(CultureInfo.InvariantCulture, " ({0} filters)", afc.FilterChain.Count); } } if (sb != null) InternalLogger.Debug(sb.ToString()); } return sb != null; } /// <summary> /// Currently this <see cref="LogFactory"/> is disposing? /// </summary> private bool _isDisposing; private void Close(TimeSpan flushTimeout) { if (_isDisposing) { return; } _isDisposing = true; _serviceRepository.TypeRegistered -= ServiceRepository_TypeRegistered; #if !NETSTANDARD1_3 LoggerShutdown -= OnStopLogging; ConfigurationReloaded = null; // Release event listeners #endif if (Monitor.TryEnter(_syncRoot, 500)) { try { _configLoader.Dispose(); var oldConfig = _config; if (_configLoaded && oldConfig != null) { CloseOldConfig(flushTimeout, oldConfig); } } finally { Monitor.Exit(_syncRoot); } } ConfigurationChanged = null; // Release event listeners } private void CloseOldConfig(TimeSpan flushTimeout, LoggingConfiguration oldConfig) { try { bool attemptClose = true; if (flushTimeout > TimeSpan.Zero) { attemptClose = FlushAllTargetsSync(oldConfig, flushTimeout, false); } // Disable all loggers, so things become quiet _config = null; ReconfigExistingLoggers(); if (!attemptClose) { InternalLogger.Warn("Target flush timeout. One or more targets did not complete flush operation, skipping target close."); } else { // Flush completed within timeout, lets try and close down oldConfig.Close(); OnConfigurationChanged(new LoggingConfigurationChangedEventArgs(null, oldConfig)); } } catch (Exception ex) { InternalLogger.Error(ex, "LogFactory failed to close NLog LoggingConfiguration."); } } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>True</c> to release both managed and unmanaged resources; /// <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { Close(DefaultFlushTimeout); } } /// <summary> /// Dispose all targets, and shutdown logging. /// </summary> public void Shutdown() { InternalLogger.Info("Shutdown() called. Logger closing..."); if (!_isDisposing && _configLoaded) { lock (_syncRoot) { if (_isDisposing || !_configLoaded) return; Configuration = null; _configLoaded = true; // Locked disabled state ReconfigExistingLoggers(); // Disable all loggers, so things become quiet } } InternalLogger.Info("Logger has been closed down."); } /// <summary> /// Get file paths (including filename) for the possible NLog config files. /// </summary> /// <returns>The file paths to the possible config file</returns> [Obsolete("Replaced by LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] public IEnumerable<string> GetCandidateConfigFilePaths() { if (_candidateConfigFilePaths != null) { return _candidateConfigFilePaths.AsReadOnly(); } return _configLoader.GetDefaultCandidateConfigFilePaths(); } /// <summary> /// Get file paths (including filename) for the possible NLog config files. /// </summary> /// <returns>The file paths to the possible config file</returns> [Obsolete("Replaced by chaining LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] internal IEnumerable<string> GetCandidateConfigFilePaths(string filename) { if (_candidateConfigFilePaths != null) return GetCandidateConfigFilePaths(); return _configLoader.GetDefaultCandidateConfigFilePaths(string.IsNullOrEmpty(filename) ? null : filename); } /// <summary> /// Overwrite the candidates paths (including filename) for the possible NLog config files. /// </summary> /// <param name="filePaths">The file paths to the possible config file</param> [Obsolete("Replaced by chaining LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] public void SetCandidateConfigFilePaths(IEnumerable<string> filePaths) { _candidateConfigFilePaths = new List<string>(); if (filePaths != null) { _candidateConfigFilePaths.AddRange(filePaths); } } /// <summary> /// Clear the candidate file paths and return to the defaults. /// </summary> [Obsolete("Replaced by chaining LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] public void ResetCandidateConfigFilePath() { _candidateConfigFilePaths = null; } private Logger GetLoggerThreadSafe(string name, Type loggerType, Func<Type, Logger> loggerCreator) { if (name is null) throw new ArgumentNullException(nameof(name), "Name of logger cannot be null"); LoggerCacheKey cacheKey = new LoggerCacheKey(name, loggerType); lock (_syncRoot) { Logger existingLogger = _loggerCache.Retrieve(cacheKey); if (existingLogger != null) { // Logger is still in cache and referenced. return existingLogger; } Logger newLogger = CreateNewLogger(loggerType, loggerCreator); if (newLogger is null) { cacheKey = new LoggerCacheKey(cacheKey.Name, typeof(Logger)); newLogger = new Logger(); } var config = _config ?? (_loggerCache.Count == 0 ? Configuration : null); // Only force load NLog-config with first logger newLogger.Initialize(name, BuildLoggerConfiguration(name, config), this); if (config is null && _loggerCache.Count == 0) { InternalLogger.Info("NLog Configuration has not been loaded."); } _loggerCache.InsertOrUpdate(cacheKey, newLogger); return newLogger; } } internal Logger CreateNewLogger(Type loggerType, Func<Type, Logger> loggerCreator) { try { Logger newLogger = loggerCreator(loggerType); if (newLogger is null) { if (Logger.DefaultLoggerType.IsAssignableFrom(loggerType)) { throw new NLogRuntimeException($"GetLogger / GetCurrentClassLogger with type '{loggerType}' could not create instance of NLog Logger"); } else if (ThrowExceptions) { throw new NLogRuntimeException($"GetLogger / GetCurrentClassLogger with type '{loggerType}' does not inherit from NLog Logger"); } } else { return newLogger; } } catch (Exception ex) { InternalLogger.Error(ex, "GetLogger / GetCurrentClassLogger. Cannot create instance of type '{0}'. It should have an default constructor.", loggerType); if (ex.MustBeRethrown()) { throw; } } return new Logger(); } /// <summary> /// Loads logging configuration from file (Currently only XML configuration files supported) /// </summary> /// <param name="configFile">Configuration file to be read</param> /// <returns>LogFactory instance for fluent interface</returns> [Obsolete("Replaced by LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] public LogFactory LoadConfiguration(string configFile) { // TODO Remove explicit File-loading logic from LogFactory (Should handle environment without files) return LoadConfiguration(configFile, optional: false); } internal LogFactory LoadConfiguration(string configFile, bool optional) { var actualConfigFile = string.IsNullOrEmpty(configFile) ? "NLog.config" : configFile; if (optional && string.Equals(actualConfigFile.Trim(), "NLog.config", StringComparison.OrdinalIgnoreCase) && _config != null) { return this; // Skip optional loading of default config, when config is already loaded } var config = _configLoader.Load(this, configFile); if (config is null) { if (!optional) { var message = CreateFileNotFoundMessage(configFile); throw new System.IO.FileNotFoundException(message, actualConfigFile); } else { return this; } } Configuration = config; return this; } private string CreateFileNotFoundMessage(string configFile) { var messageBuilder = new StringBuilder("Failed to load NLog LoggingConfiguration."); try { // hashset to remove duplicates var triedPaths = new HashSet<string>(_configLoader.GetDefaultCandidateConfigFilePaths(configFile)); messageBuilder.AppendLine(" Searched the following locations:"); foreach (var path in triedPaths) { messageBuilder.Append("- "); messageBuilder.AppendLine(path); } } catch (Exception e) { InternalLogger.Debug("Failed to GetDefaultCandidateConfigFilePaths in CreateFileNotFoundMessage: {0}", e); } var message = messageBuilder.ToString(); return message; } /// <summary> /// Logger cache key. /// </summary> private struct LoggerCacheKey : IEquatable<LoggerCacheKey> { public readonly string Name; public readonly Type ConcreteType; public LoggerCacheKey(string name, Type concreteType) { Name = name; ConcreteType = concreteType; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> public override int GetHashCode() { return ConcreteType.GetHashCode() ^ Name.GetHashCode(); } /// <summary> /// Determines if two objects are equal in value. /// </summary> /// <param name="obj">Other object to compare to.</param> /// <returns>True if objects are equal, false otherwise.</returns> public override bool Equals(object obj) { return obj is LoggerCacheKey key && Equals(key); } /// <summary> /// Determines if two objects of the same type are equal in value. /// </summary> /// <param name="other">Other object to compare to.</param> /// <returns>True if objects are equal, false otherwise.</returns> public bool Equals(LoggerCacheKey other) { return (ConcreteType == other.ConcreteType) && string.Equals(other.Name, Name, StringComparison.Ordinal); } } /// <summary> /// Logger cache. /// </summary> private sealed class LoggerCache { // The values of WeakReferences are of type Logger i.e. Directory<LoggerCacheKey, Logger>. private readonly Dictionary<LoggerCacheKey, WeakReference> _loggerCache = new Dictionary<LoggerCacheKey, WeakReference>(); public int Count => _loggerCache.Count; /// <summary> /// Inserts or updates. /// </summary> /// <param name="cacheKey"></param> /// <param name="logger"></param> public void InsertOrUpdate(LoggerCacheKey cacheKey, Logger logger) { _loggerCache[cacheKey] = new WeakReference(logger); } public Logger Retrieve(LoggerCacheKey cacheKey) { if (_loggerCache.TryGetValue(cacheKey, out var loggerReference)) { // logger in the cache and still referenced return loggerReference.Target as Logger; } return null; } public List<Logger> GetLoggers() { List<Logger> values = new List<Logger>(_loggerCache.Count); foreach (var item in _loggerCache) { if (item.Value.Target is Logger logger) { values.Add(logger); } } return values; } public void Reset() { _loggerCache.Clear(); } /// <summary> /// Loops through all cached loggers and removes dangling loggers that have been garbage collected. /// </summary> public void PurgeObsoleteLoggers() { foreach (var key in _loggerCache.Keys.ToList()) { var logger = Retrieve(key); if (logger != null) continue; _loggerCache.Remove(key); } } } /// <remarks> /// Internal for unit tests /// </remarks> internal int ResetLoggerCache() { var keysCount = _loggerCache.Count; _loggerCache.Reset(); return keysCount; } /// <summary> /// Enables logging in <see cref="IDisposable.Dispose"/> implementation. /// </summary> private sealed class LogEnabler : IDisposable { private readonly LogFactory _factory; /// <summary> /// Initializes a new instance of the <see cref="LogEnabler" /> class. /// </summary> /// <param name="factory">The factory.</param> public LogEnabler(LogFactory factory) { _factory = factory; } /// <summary> /// Enables logging. /// </summary> void IDisposable.Dispose() { _factory.ResumeLogging(); } } private static void RegisterEvents(IAppEnvironment appEnvironment) { if (appEnvironment is null) return; try { appEnvironment.ProcessExit += OnLoggerShutdown; } catch (Exception exception) { InternalLogger.Warn(exception, "Error setting up termination events."); if (exception.MustBeRethrown()) { throw; } } } private static void UnregisterEvents(IAppEnvironment appEnvironment) { if (appEnvironment is null) return; appEnvironment.ProcessExit -= OnLoggerShutdown; } private static void OnLoggerShutdown(object sender, EventArgs args) { try { LoggerShutdown?.Invoke(sender, args); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; InternalLogger.Error(ex, "LogFactory failed to shutdown properly."); } finally { LoggerShutdown = null; if (defaultAppEnvironment != null) { defaultAppEnvironment.ProcessExit -= OnLoggerShutdown; // Unregister from AppDomain } } } private void OnStopLogging(object sender, EventArgs args) { try { //stop timer on domain unload, otherwise: //Exception: System.AppDomainUnloadedException //Message: Attempted to access an unloaded AppDomain. InternalLogger.Info("AppDomain Shutting down. LogFactory closing..."); // Domain-Unload has to complete in about 2 secs on Windows-platform, before being terminated. // Other platforms like Linux will fail when trying to spin up new threads at domain unload. var flushTimeout = #if !NETSTANDARD1_3 PlatformDetector.IsWin32 ? TimeSpan.FromMilliseconds(1500) : #endif TimeSpan.Zero; Close(flushTimeout); InternalLogger.Info("LogFactory has been closed."); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; InternalLogger.Error(ex, "LogFactory failed to close properly."); } } } }<file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; namespace ASPNetBufferingWrapper { public partial class NormalPage : System.Web.UI.Page { private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); protected void Page_Load(object sender, EventArgs e) { // This page simulates correct flow, no warnings are emitted // This causes the postfiltering wrapper to emit only the Info messages logger.Info("info1"); logger.Debug("some debug message"); logger.Debug("some other debug message"); logger.Debug("yet another other debug message"); logger.Info("info2"); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using Config; using Layouts; /// <summary> /// Represents target that supports string formatting using layouts. /// </summary> public abstract class TargetWithLayoutHeaderAndFooter : TargetWithLayout { /// <summary> /// Initializes a new instance of the <see cref="TargetWithLayoutHeaderAndFooter" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> protected TargetWithLayoutHeaderAndFooter() { } /// <summary> /// Gets or sets the text to be rendered. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> /// <docgen category='Layout Options' order='1' /> [RequiredParameter] public override Layout Layout { get => LHF.Layout; set { if (value is LayoutWithHeaderAndFooter) { base.Layout = value; } else if (LHF is null) { LHF = new LayoutWithHeaderAndFooter() { Layout = value }; } else { LHF.Layout = value; } } } /// <summary> /// Gets or sets the footer. /// </summary> /// <docgen category='Layout Options' order='3' /> public Layout Footer { get => LHF.Footer; set => LHF.Footer = value; } /// <summary> /// Gets or sets the header. /// </summary> /// <docgen category='Layout Options' order='2' /> public Layout Header { get => LHF.Header; set => LHF.Header = value; } /// <summary> /// Gets or sets the layout with header and footer. /// </summary> /// <value>The layout with header and footer.</value> private LayoutWithHeaderAndFooter LHF { get => (LayoutWithHeaderAndFooter)base.Layout; set => base.Layout = value; } } } <file_sep><html> <head> <title>NLog Examples</title> <style type="text/css"> body { font-family: Tahoma; font-size: 10pt; } </style> </head> <body> <p> This directory contains examples of extending functionality of loggers. This is needed to pass extra per-call context information to the logging engine. For example, you can pass log event ID that will be written to the Event Log. </p> <p> There are 2 methods of extending loggers: </p> <ul> <li><b>wrapping loggers</b> - the code that wraps Logger is located in the <a href="LoggerWrapper/">LoggerWrapper</a> directory.</li> <li><b>inheriting from loggers</b> - the code that extends the Logger class by inheriting from it can be found in the <a href="InheritFromLogger/">InheritFromLogger</a> directory.</li> </ul> <p> Both methods construct a <code>LogEventInfo</code> object and pass it to the Log() method of the logger. It is important to also pass the declaring type of the method that is invoked by user code, otherwise the <a href="http://www.nlog-project.org/lr.callsite.html">${callsite}</a> and <a href="http://www.nlog-project.org/lr.stacktrace.html">${stacktrace}</a> layout renderers won't work properly. </p> <p> The examples also demonstrate is the technique of passing additional per-log context information. This is done by adding items to the <code>LogEvent.Context</code> dictionary. This context data can be retrieved and used in layouts with the <code>${event-context}</code> layout renderer. </p> <p> The examples are compatible with <a href="http://www.microsoft.com/vstudio">Visual Studio 2005</a> and can be built with <a href="http://msdn2.microsoft.com/en-us/library/wea2sca5.aspx">MSBuild</a>. </p> </body> </html> <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Text; using NLog.Config; using NLog.Internal; /// <summary> /// Globally-unique identifier (GUID). /// </summary> [LayoutRenderer("guid")] [ThreadAgnostic] public class GuidLayoutRenderer : LayoutRenderer, IRawValue, IStringValueRenderer { /// <summary> /// Gets or sets the GUID format as accepted by Guid.ToString() method. /// </summary> /// <docgen category='Layout Options' order='10' /> public string Format { get; set; } = "N"; /// <summary> /// Generate the Guid from the NLog LogEvent (Will be the same for all targets) /// </summary> /// <docgen category='Layout Options' order='100' /> public bool GeneratedFromLogEvent { get; set; } /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(GetStringValue(logEvent)); } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = GetValue(logEvent); return true; } string IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) => GetStringValue(logEvent); private string GetStringValue(LogEventInfo logEvent) { return GetValue(logEvent).ToString(Format); } private Guid GetValue(LogEventInfo logEvent) { Guid guid; if (GeneratedFromLogEvent) { int hashCode = logEvent.GetHashCode(); short b = (short)((hashCode >> 16) & 0XFFFF); short c = (short)(hashCode & 0XFFFF); long zeroDateTicks = LogEventInfo.ZeroDate.Ticks; byte d = (byte)((zeroDateTicks >> 56) & 0xFF); byte e = (byte)((zeroDateTicks >> 48) & 0xFF); byte f = (byte)((zeroDateTicks >> 40) & 0xFF); byte g = (byte)((zeroDateTicks >> 32) & 0xFF); byte h = (byte)((zeroDateTicks >> 24) & 0xFF); byte i = (byte)((zeroDateTicks >> 16) & 0xFF); byte j = (byte)((zeroDateTicks >> 8) & 0xFF); byte k = (byte)(zeroDateTicks & 0XFF); guid = new Guid(logEvent.SequenceID, b, c, d, e, f, g, h, i, j, k); } else { guid = Guid.NewGuid(); } return guid; } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !MONO && !NETSTANDARD namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.Diagnostics.Eventing.Reader; using System.Linq; using System.Diagnostics; using NLog.Config; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using Xunit; public class EventLogTargetTests : NLogTestBase { private const int MaxMessageLength = EventLogTarget.EventLogMaxMessageLength; [Fact] public void EventLogSource_AppDomainFriendlyName() { var eventLogTarget = new EventLogTarget(); var eventLogSource = eventLogTarget.Source?.Render(LogEventInfo.CreateNullEvent()); Assert.Equal(AppDomain.CurrentDomain.FriendlyName, eventLogSource); } [Fact] public void MaxMessageLengthShouldBe16384_WhenNotSpecifyAnyOption() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog ThrowExceptions='true'> <targets> <target type='EventLog' name='eventLog1' layout='${message}' /> </targets> <rules> <logger name='*' writeTo='eventLog1'> </logger> </rules> </nlog>"); var eventLog1 = c.FindTargetByName<EventLogTarget>("eventLog1"); Assert.Equal(MaxMessageLength, eventLog1.MaxMessageLength); } [Fact] public void MaxMessageLengthShouldBeAsSpecifiedOption() { const int expectedMaxMessageLength = 1000; LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString($@" <nlog ThrowExceptions='true'> <targets> <target type='EventLog' name='eventLog1' layout='${{message}}' maxmessagelength='{ expectedMaxMessageLength }' /> </targets> <rules> <logger name='*' writeTo='eventLog1'> </logger> </rules> </nlog>"); var eventLog1 = c.FindTargetByName<EventLogTarget>("eventLog1"); Assert.Equal(expectedMaxMessageLength, eventLog1.MaxMessageLength); } [Theory] [InlineData(0)] [InlineData(-1)] public void ConfigurationShouldThrowException_WhenMaxMessageLengthIsNegativeOrZero(int maxMessageLength) { string configrationText = $@" <nlog ThrowExceptions='true'> <targets> <target type='EventLog' name='eventLog1' layout='${{message}}' maxmessagelength='{ maxMessageLength }' /> </targets> <rules> <logger name='*' writeTo='eventLog1'> </logger> </rules> </nlog>"; NLogConfigurationException ex = Assert.Throws<NLogConfigurationException>(() => XmlLoggingConfiguration.CreateFromXmlString(configrationText)); Assert.Equal("MaxMessageLength cannot be zero or negative.", ex.InnerException.InnerException.Message); } [Theory] [InlineData(0)] // Is multiple of 64, but less than the min value of 64 [InlineData(65)] // Isn't multiple of 64 [InlineData(4194304)] // Is multiple of 64, but bigger than the max value of 4194240 public void Configuration_ShouldThrowException_WhenMaxKilobytesIsInvalid(long? maxKilobytes) { string configrationText = $@" <nlog ThrowExceptions='true'> <targets> <target type='EventLog' name='eventLog1' layout='${{message}}' maxKilobytes='{maxKilobytes}' /> </targets> <rules> <logger name='*' writeTo='eventLog1' /> </rules> </nlog>"; NLogConfigurationException ex = Assert.Throws<NLogConfigurationException>(() => XmlLoggingConfiguration.CreateFromXmlString(configrationText)); Assert.Equal("MaxKilobytes must be a multiple of 64, and between 64 and 4194240", ex.InnerException.InnerException.Message); } [Theory] [InlineData(0)] // Is multiple of 64, but less than the min value of 64 [InlineData(65)] // Isn't multiple of 64 [InlineData(4194304)] // Is multiple of 64, but bigger than the max value of 4194240 public void MaxKilobytes_ShouldThrowException_WhenMaxKilobytesIsInvalid(long? maxKilobytes) { ArgumentException ex = Assert.Throws<ArgumentException>(() => { var target = new EventLogTarget(); target.MaxKilobytes = maxKilobytes; }); Assert.Equal("MaxKilobytes must be a multiple of 64, and between 64 and 4194240", ex.Message); } [Theory] // 'null' case is omitted, as it isn't a valid value for Int64 XML property. [InlineData(64)] // Min value [InlineData(4194240)] // Max value [InlineData(16384)] // Acceptable value public void ConfigurationMaxKilobytes_ShouldBeAsSpecified_WhenMaxKilobytesIsValid(long? maxKilobytes) { var expectedMaxKilobytes = maxKilobytes; string configrationText = $@" <nlog ThrowExceptions='true'> <targets> <target type='EventLog' name='eventLog1' layout='${{message}}' maxKilobytes='{maxKilobytes}' /> </targets> <rules> <logger name='*' writeTo='eventLog1' /> </rules> </nlog>"; LoggingConfiguration configuration = XmlLoggingConfiguration.CreateFromXmlString(configrationText); var eventLog1 = configuration.FindTargetByName<EventLogTarget>("eventLog1"); Assert.Equal(expectedMaxKilobytes, eventLog1.MaxKilobytes); } [Theory] [InlineData(null)] // A possible value, that should not change anything [InlineData(64)] // Min value [InlineData(4194240)] // Max value [InlineData(16384)] // Acceptable value public void MaxKilobytes_ShouldBeAsSpecified_WhenValueIsValid(long? maxKilobytes) { var expectedMaxKilobytes = maxKilobytes; var target = new EventLogTarget(); target.MaxKilobytes = maxKilobytes; Assert.Equal(expectedMaxKilobytes, target.MaxKilobytes); } [Theory] [InlineData(32768, 16384, 32768)] // Should set MaxKilobytes when value is set and valid [InlineData(16384, 32768, 32768)] // Should not change MaxKilobytes when initial MaximumKilobytes is bigger [InlineData(null, EventLogMock.EventLogDefaultMaxKilobytes, EventLogMock.EventLogDefaultMaxKilobytes)] // Should not change MaxKilobytes when the value is null public void ShouldSetMaxKilobytes_WhenNeeded(long? newValue, long initialValue, long expectedValue) { string targetLog = "application"; // The Log to write to is intentionally lower case!! var eventLogMock = new EventLogMock( deleteEventSourceFunction: (source, machineName) => { }, sourceExistsFunction: (source, machineName) => false, logNameFromSourceNameFunction: (source, machineName) => targetLog, createEventSourceFunction: (sourceData) => { }) { MaximumKilobytes = initialValue }; var target = new EventLogTarget(eventLogMock, null) { Log = targetLog, Source = "NLog.UnitTests" + Guid.NewGuid().ToString("N"), // set the source explicitly to prevent random AppDomain name being used as the source name Layout = new SimpleLayout("${message}"), // Be able to check message length and content, the Layout is intentionally only ${message}. OnOverflow = EventLogTargetOverflowAction.Truncate, MaxMessageLength = MaxMessageLength, MaxKilobytes = newValue, }; eventLogMock.AssociateNewEventLog(target.Log, target.MachineName, target.GetFixedSource()); target.Install(new InstallationContext()); Assert.Equal(expectedValue, eventLogMock.MaximumKilobytes); } [Theory] [InlineData(0)] [InlineData(-1)] public void ShouldThrowException_WhenMaxMessageLengthSetNegativeOrZero(int maxMessageLength) { ArgumentException ex = Assert.Throws<ArgumentException>(() => { var target = new EventLogTarget(); target.MaxMessageLength = maxMessageLength; }); Assert.Equal("MaxMessageLength cannot be zero or negative.", ex.Message); } [Theory] [InlineData(0, EventLogEntryType.Information, "AtInformationLevel_WhenNLogLevelIsTrace", null)] [InlineData(1, EventLogEntryType.Information, "AtInformationLevel_WhenNLogLevelIsDebug", null)] [InlineData(2, EventLogEntryType.Information, "AtInformationLevel_WhenNLogLevelIsInfo", null)] [InlineData(3, EventLogEntryType.Warning, "AtWarningLevel_WhenNLogLevelIsWarn", null)] [InlineData(4, EventLogEntryType.Error, "AtErrorLevel_WhenNLogLevelIsError", null)] [InlineData(5, EventLogEntryType.Error, "AtErrorLevel_WhenNLogLevelIsFatal", null)] [InlineData(3, EventLogEntryType.SuccessAudit, "AtSuccessAuditLevel_WhenEntryTypeLayoutSpecifiedAsSuccessAudit", "SuccessAudit")] [InlineData(3, EventLogEntryType.SuccessAudit, "AtSuccessAuditLevel_WhenEntryTypeLayoutSpecifiedAsSuccessAudit_Uppercase", "SUCCESSAUDIT")] [InlineData(1, EventLogEntryType.FailureAudit, "AtFailureAuditLevel_WhenEntryTypeLayoutSpecifiedAsFailureAudit_Space", "FailureAudit ")] [InlineData(1, EventLogEntryType.Error, "AtErrorLevel_WhenEntryTypeLayoutSpecifiedAsErrorLowerCase", "error")] [InlineData(3, EventLogEntryType.Warning, "AtSpecifiedNLogLevel_WhenWrongEntryTypeLayoutSupplied", "fallback to auto determined")] public void TruncatedMessagesShouldBeWrittenAtCorrenpondingNLogLevel(int logLevelOrdinal, EventLogEntryType expectedEventLogEntryType, string expectedMessage, string layoutString) { LogLevel logLevel = LogLevel.FromOrdinal(logLevelOrdinal); Layout entryTypeLayout = layoutString != null ? new SimpleLayout(layoutString) : null; var eventRecords = WriteWithMock(logLevel, expectedEventLogEntryType, expectedMessage, entryTypeLayout).ToList(); Assert.Single(eventRecords); AssertWrittenMessage(eventRecords, expectedMessage); } [Theory] [InlineData(0, EventLogEntryType.Information, null)] // AtInformationLevel_WhenNLogLevelIsTrace [InlineData(1, EventLogEntryType.Information, null)] // AtInformationLevel_WhenNLogLevelIsDebug [InlineData(2, EventLogEntryType.Information, null)] // AtInformationLevel_WhenNLogLevelIsInfo [InlineData(3, EventLogEntryType.Warning, null)] // AtWarningLevel_WhenNLogLevelIsWarn [InlineData(4, EventLogEntryType.Error, null)] // AtErrorLevel_WhenNLogLevelIsError [InlineData(5, EventLogEntryType.Error, null)] // AtErrorLevel_WhenNLogLevelIsFatal [InlineData(1, EventLogEntryType.SuccessAudit, "SuccessAudit")] // AtSuccessAuditLevel_WhenEntryTypeLayoutSpecifiedAsSuccessAudit [InlineData(1, EventLogEntryType.FailureAudit, "FailureAudit")] // AtFailureLevel_WhenEntryTypeLayoutSpecifiedAsFailureAudit [InlineData(1, EventLogEntryType.Error, "error")] // AtErrorLevel_WhenEntryTypeLayoutSpecifiedAsError [InlineData(2, EventLogEntryType.Information, "wrong entry type level")] // AtSpecifiedNLogLevel_WhenWrongEntryTypeLayoutSupplied public void SplitMessagesShouldBeWrittenAtCorrenpondingNLogLevel(int logLevelOrdinal, EventLogEntryType expectedEventLogEntryType, string layoutString) { LogLevel logLevel = LogLevel.FromOrdinal(logLevelOrdinal); Layout entryTypeLayout = layoutString != null ? new SimpleLayout(layoutString) : null; const int expectedEntryCount = 2; string messagePart1 = string.Join("", Enumerable.Repeat("l", MaxMessageLength)); string messagePart2 = "this part must be split"; string testMessage = messagePart1 + messagePart2; var entries = WriteWithMock(logLevel, expectedEventLogEntryType, testMessage, entryTypeLayout, EventLogTargetOverflowAction.Split).ToList(); Assert.Equal(expectedEntryCount, entries.Count); } [Fact] public void WriteEventLogEntryLargerThanMaxMessageLengthWithOverflowTruncate_TruncatesTheMessage() { string expectedMessage = string.Join("", Enumerable.Repeat("t", MaxMessageLength)); string expectedToTruncateMessage = " this part will be truncated"; string testMessage = expectedMessage + expectedToTruncateMessage; var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, testMessage).ToList(); Assert.Single(entries); AssertWrittenMessage(entries, expectedMessage); } [Fact] public void WriteEventLogEntryEqualToMaxMessageLengthWithOverflowTruncate_TheMessageIsNotTruncated() { string expectedMessage = string.Join("", Enumerable.Repeat("t", MaxMessageLength)); var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, expectedMessage).ToList(); Assert.Single(entries); AssertWrittenMessage(entries, expectedMessage); } [Fact] public void WriteEventLogEntryLargerThanMaxMessageLengthWithOverflowSplitEntries_TheMessageShouldBeSplit() { const int expectedEntryCount = 5; string messagePart1 = string.Join("", Enumerable.Repeat("a", MaxMessageLength)); string messagePart2 = string.Join("", Enumerable.Repeat("b", MaxMessageLength)); string messagePart3 = string.Join("", Enumerable.Repeat("c", MaxMessageLength)); string messagePart4 = string.Join("", Enumerable.Repeat("d", MaxMessageLength)); string messagePart5 = "this part must be split too"; string testMessage = messagePart1 + messagePart2 + messagePart3 + messagePart4 + messagePart5; var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, testMessage, null, EventLogTargetOverflowAction.Split).ToList(); Assert.Equal(expectedEntryCount, entries.Count); AssertWrittenMessage(entries, messagePart1); AssertWrittenMessage(entries, messagePart2); AssertWrittenMessage(entries, messagePart3); AssertWrittenMessage(entries, messagePart4); AssertWrittenMessage(entries, messagePart5); } [Fact] public void WriteEventLogEntryEqualToMaxMessageLengthWithOverflowSplitEntries_TheMessageShouldBeSplitInTwoChunks() { const int expectedEntryCount = 2; string messagePart1 = string.Join("", Enumerable.Repeat("a", MaxMessageLength)); string messagePart2 = string.Join("", Enumerable.Repeat("b", MaxMessageLength)); string testMessage = messagePart1 + messagePart2; var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, testMessage, null, EventLogTargetOverflowAction.Split).ToList(); Assert.Equal(expectedEntryCount, entries.Count); AssertWrittenMessage(entries, messagePart1); AssertWrittenMessage(entries, messagePart2); } [Fact] public void WriteEventLogEntryEqualToMaxMessageLengthWithOverflowSplitEntries_TheMessageIsNotSplit() { string expectedMessage = string.Join("", Enumerable.Repeat("a", MaxMessageLength)); var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, expectedMessage, null, EventLogTargetOverflowAction.Split).ToList(); Assert.Single(entries); AssertWrittenMessage(entries, expectedMessage); } [Fact] public void WriteEventLogEntryEqualToMaxMessageLengthWithOverflowDiscard_TheMessageIsWritten() { string expectedMessage = string.Join("", Enumerable.Repeat("a", MaxMessageLength)); var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, expectedMessage, null, EventLogTargetOverflowAction.Discard).ToList(); Assert.Single(entries); AssertWrittenMessage(entries, expectedMessage); } [Fact] public void WriteEventLogEntryLargerThanMaxMessageLengthWithOverflowDiscard_TheMessageIsNotWritten() { string messagePart1 = string.Join("", Enumerable.Repeat("a", MaxMessageLength)); string messagePart2 = "b"; string testMessage = messagePart1 + messagePart2; bool wasWritten = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, testMessage, null, EventLogTargetOverflowAction.Discard).Any(); Assert.False(wasWritten); } [Fact] public void WriteEventLogEntry_WithoutSource_WillBeDiscarded() { // Arrange var eventLogMock = new EventLogMock( deleteEventSourceFunction: (source, machineName) => { }, sourceExistsFunction: (source, machineName) => true, logNameFromSourceNameFunction: (source, machineName) => string.Empty, createEventSourceFunction: (sourceData) => { }); var target = new EventLogTarget(eventLogMock, null); target.Source = "${event-properties:item=DynamicSource}"; var logFactory = new LogFactory(); var logConfig = new LoggingConfiguration(logFactory); logConfig.AddRuleForAllLevels(target); logFactory.Configuration = logConfig; // Act var logger = logFactory.GetLogger("EventLogCorrectLog"); logger.Info("Hello"); // Assert Assert.Empty(eventLogMock.WrittenEntries); } [Fact] public void WriteEventLogEntry_WillRecreate_WhenWrongLogName() { // Arrange string sourceName = "NLog.UnitTests" + Guid.NewGuid().ToString("N"); string deletedSourceName = string.Empty; string createdLogName = string.Empty; var eventLogMock = new EventLogMock( deleteEventSourceFunction: (source, machineName) => deletedSourceName = source, sourceExistsFunction: (source, machineName) => true, logNameFromSourceNameFunction: (source, machineName) => "FaultyLog", createEventSourceFunction: (sourceData) => createdLogName = sourceData.LogName); var target = new EventLogTarget(eventLogMock, null); target.Log = "CorrectLog"; target.Source = sourceName; target.Layout = "${message}"; var logFactory = new LogFactory(); var logConfig = new LoggingConfiguration(logFactory); logConfig.AddRuleForAllLevels(target); logFactory.Configuration = logConfig; // Act var logger = logFactory.GetLogger("EventLogCorrectLog"); logger.Info("Hello"); // Assert Assert.Equal(sourceName, deletedSourceName); Assert.Equal(target.Log, createdLogName); Assert.Single(eventLogMock.WrittenEntries); Assert.Equal(target.Log, eventLogMock.WrittenEntries[0].Log); Assert.Equal(sourceName, eventLogMock.WrittenEntries[0].Source); Assert.Equal("Hello", eventLogMock.WrittenEntries[0].Message); } [Fact] public void WriteEventLogEntry_WillComplain_WhenWrongLogName() { // Arrange string sourceName = "NLog.UnitTests" + Guid.NewGuid().ToString("N"); string deletedSourceName = string.Empty; string createdLogName = string.Empty; var eventLogMock = new EventLogMock( deleteEventSourceFunction: (source, machineName) => deletedSourceName = source, sourceExistsFunction: (source, machineName) => true, logNameFromSourceNameFunction: (source, machineName) => "FaultyLog", createEventSourceFunction: (sourceData) => createdLogName = sourceData.LogName); var target = new EventLogTarget(eventLogMock, null); target.Log = "CorrectLog"; target.Source = "${event-properties:item=DynamicSource}"; target.Layout = "${message}"; var logFactory = new LogFactory(); var logConfig = new LoggingConfiguration(logFactory); logConfig.AddRuleForAllLevels(target); logFactory.Configuration = logConfig; // Act var logger = logFactory.GetLogger("EventLogCorrectLog"); logger.Info("Hello {DynamicSource:l}", sourceName); // Assert Assert.Equal(string.Empty, deletedSourceName); Assert.Equal(string.Empty, createdLogName); Assert.Equal(target.Log, eventLogMock.WrittenEntries[0].Log); Assert.Equal(sourceName, eventLogMock.WrittenEntries[0].Source); Assert.Equal($"Hello {sourceName}", eventLogMock.WrittenEntries[0].Message); } [Fact] public void WriteEventLogEntryWithDynamicSource() { const int maxMessageLength = 10; string expectedMessage = string.Join("", Enumerable.Repeat("a", maxMessageLength)); var target = CreateEventLogTarget("NLog.UnitTests" + Guid.NewGuid().ToString("N"), EventLogTargetOverflowAction.Split, maxMessageLength); target.Layout = new SimpleLayout("${message}"); target.Source = new SimpleLayout("${event-properties:item=DynamicSource}"); LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(target)); var logger = LogManager.GetLogger("WriteEventLogEntry"); var sourceName = "NLog.UnitTests" + Guid.NewGuid().ToString("N"); var logEvent = CreateLogEventWithDynamicSource(expectedMessage, LogLevel.Trace, "DynamicSource", sourceName); logger.Log(logEvent); var eventLog = new EventLog(target.Log); var entries = GetEventRecords(eventLog.Log).ToList(); entries = entries.Where(a => a.ProviderName == sourceName).ToList(); Assert.Single(entries); AssertWrittenMessage(entries, expectedMessage); sourceName = "NLog.UnitTests" + Guid.NewGuid().ToString("N"); expectedMessage = string.Join("", Enumerable.Repeat("b", maxMessageLength)); logEvent = CreateLogEventWithDynamicSource(expectedMessage, LogLevel.Trace, "DynamicSource", sourceName); logger.Log(logEvent); entries = GetEventRecords(eventLog.Log).ToList(); entries = entries.Where(a => a.ProviderName == sourceName).ToList(); Assert.Single(entries); AssertWrittenMessage(entries, expectedMessage); } [Fact] public void LogEntryWithStaticEventIdAndCategoryInTargetLayout() { var rnd = new Random(); int eventId = rnd.Next(1, short.MaxValue); int category = rnd.Next(1, short.MaxValue); var target = CreateEventLogTarget("NLog.UnitTests" + Guid.NewGuid().ToString("N"), EventLogTargetOverflowAction.Truncate, 5000); target.EventId = eventId; target.Category = (short)category; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(target)); var logger = LogManager.GetLogger("WriteEventLogEntry"); logger.Log(LogLevel.Error, "Simple Test Message"); var eventLog = new EventLog(target.Log); var entries = GetEventRecords(eventLog.Log).ToList(); var expectedProviderName = target.GetFixedSource(); var filtered = entries.Where(entry => entry.ProviderName == expectedProviderName && HasEntryType(entry, EventLogEntryType.Error) ); Assert.Single(filtered); var record = filtered.First(); Assert.Equal(eventId, record.Id); Assert.Equal(category, record.Task); } [Fact] public void LogEntryWithDynamicEventIdAndCategory() { var rnd = new Random(); int eventId = rnd.Next(1, short.MaxValue); int category = rnd.Next(1, short.MaxValue); var target = CreateEventLogTarget("NLog.UnitTests" + Guid.NewGuid().ToString("N"), EventLogTargetOverflowAction.Truncate, 5000); target.EventId = "${event-properties:EventId}"; target.Category = "${event-properties:Category}"; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(target)); var logger = LogManager.GetLogger("WriteEventLogEntry"); LogEventInfo theEvent = new LogEventInfo(LogLevel.Error, "TestLoggerName", "Simple Message"); theEvent.Properties["EventId"] = eventId; theEvent.Properties["Category"] = category; logger.Log(theEvent); var eventLog = new EventLog(target.Log); var entries = GetEventRecords(eventLog.Log).ToList(); var expectedProviderName = target.GetFixedSource(); var filtered = entries.Where(entry => entry.ProviderName == expectedProviderName && HasEntryType(entry, EventLogEntryType.Error) ); Assert.Single(filtered); var record = filtered.First(); Assert.Equal(eventId, record.Id); Assert.Equal(category, record.Task); } private static IEnumerable<EventLogMock.EventRecord> WriteWithMock(LogLevel logLevel, EventLogEntryType expectedEventLogEntryType, string logMessage, Layout entryType = null, EventLogTargetOverflowAction overflowAction = EventLogTargetOverflowAction.Truncate, int maxMessageLength = MaxMessageLength) { var sourceName = "NLog.UnitTests" + Guid.NewGuid().ToString("N"); var eventLogMock = new EventLogMock( deleteEventSourceFunction: (source, machineName) => { }, sourceExistsFunction: (source, machineName) => false, logNameFromSourceNameFunction: (source, machineName) => string.Empty, createEventSourceFunction: (sourceData) => { }); var target = new EventLogTarget(eventLogMock, null); InitializeEventLogTarget(target, sourceName, overflowAction, maxMessageLength, entryType); LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(target)); var logger = LogManager.GetLogger("WriteEventLogEntry"); logger.Log(logLevel, logMessage); var entries = eventLogMock.WrittenEntries; var expectedSource = target.GetFixedSource(); var filteredEntries = entries.Where(entry => entry.Source == expectedSource && entry.EntryType == expectedEventLogEntryType ); if (overflowAction == EventLogTargetOverflowAction.Discard && logMessage.Length > maxMessageLength) { Assert.False(filteredEntries.Any(), $"No message is expected. But {filteredEntries.Count()} message(s) found entry of type '{expectedEventLogEntryType}' from source '{expectedSource}'."); } else { Assert.True(filteredEntries.Any(), $"Failed to find entry of type '{expectedEventLogEntryType}' from source '{expectedSource}'"); } return filteredEntries; } private void AssertWrittenMessage(IEnumerable<EventRecord> eventLogs, string expectedMessage) { var messages = eventLogs.Where(entry => entry.Properties.Any(prop => Convert.ToString(prop.Value) == expectedMessage)); Assert.True(messages.Any(), $"Event records has not the expected message: '{expectedMessage}'"); } private void AssertWrittenMessage(IEnumerable<EventLogMock.EventRecord> eventLogs, string expectedMessage) { var messages = eventLogs.Where(entry => entry.Message == expectedMessage); Assert.True(messages.Any(), $"Event records has not the expected message: '{expectedMessage}'"); } private static EventLogTarget CreateEventLogTarget(string sourceName, EventLogTargetOverflowAction overflowAction, int maxMessageLength, Layout entryType = null) { return InitializeEventLogTarget(new EventLogTarget(), sourceName, overflowAction, maxMessageLength, entryType); } private static EventLogTarget InitializeEventLogTarget(EventLogTarget target, string sourceName, EventLogTargetOverflowAction overflowAction, int maxMessageLength, Layout entryType) { target.Name = "eventlog"; target.Log = "application"; // The Log to write to is intentionally lower case!! target.Source = sourceName; // set the source explicitly to prevent random AppDomain name being used as the source name target.Layout = new SimpleLayout("${message}"); //Be able to check message length and content, the Layout is intentionally only ${message}. target.OnOverflow = overflowAction; target.MaxMessageLength = maxMessageLength; if (entryType != null) { using (new NoThrowNLogExceptions()) target.EntryType = new Layout<EventLogEntryType>(entryType); } return target; } private LogEventInfo CreateLogEventWithDynamicSource(string message, LogLevel level, string propertyKey, string proertyValue) { var logEvent = new LogEventInfo(); logEvent.Message = message; logEvent.Level = level; logEvent.Properties[propertyKey] = proertyValue; return logEvent; } private static IEnumerable<EventRecord> GetEventRecords(string logName) { var query = new EventLogQuery(logName, PathType.LogName) { ReverseDirection = true }; using (var reader = new EventLogReader(query)) for (var eventInstance = reader.ReadEvent(); eventInstance != null; eventInstance = reader.ReadEvent()) yield return eventInstance; } private static bool HasEntryType(EventRecord eventRecord, EventLogEntryType entryType) { var keywords = (StandardEventKeywords)(eventRecord.Keywords ?? 0); var level = (StandardEventLevel)(eventRecord.Level ?? 0); bool isClassicEvent = keywords.HasFlag(StandardEventKeywords.EventLogClassic); switch (entryType) { case EventLogEntryType.Error: return isClassicEvent && level == StandardEventLevel.Error; case EventLogEntryType.Warning: return isClassicEvent && level == StandardEventLevel.Warning; case EventLogEntryType.Information: return isClassicEvent && level == StandardEventLevel.Informational; case EventLogEntryType.SuccessAudit: return keywords.HasFlag(StandardEventKeywords.AuditSuccess); case EventLogEntryType.FailureAudit: return keywords.HasFlag(StandardEventKeywords.AuditFailure); } return false; } private class EventLogMock : EventLogTarget.IEventLogWrapper { public const int EventLogDefaultMaxKilobytes = 512; public EventLogMock( Action<string, string> deleteEventSourceFunction, Func<string, string, bool> sourceExistsFunction, Func<string, string, string> logNameFromSourceNameFunction, Action<EventSourceCreationData> createEventSourceFunction) { DeleteEventSourceFunction = Guard.ThrowIfNull(deleteEventSourceFunction); SourceExistsFunction = Guard.ThrowIfNull(sourceExistsFunction); LogNameFromSourceNameFunction = Guard.ThrowIfNull(logNameFromSourceNameFunction); CreateEventSourceFunction = Guard.ThrowIfNull(createEventSourceFunction); } private Action<string, string> DeleteEventSourceFunction { get; } private Func<string, string, bool> SourceExistsFunction { get; } private Func<string, string, string> LogNameFromSourceNameFunction { get; } private Action<EventSourceCreationData> CreateEventSourceFunction { get; } public class EventRecord { public string Message { get; set; } public EventLogEntryType EntryType { get; set; } public string Log { get; set; } public string Source { get; set; } public string MachineName { get; set; } public int EventId { get; set; } public short Category { get; set; } } internal List<EventRecord> WrittenEntries { get; } = new List<EventRecord>(); /// <inheritdoc/> public string Source { get; set; } /// <inheritdoc/> public string Log { get; set; } /// <inheritdoc/> public string MachineName { get; set; } /// <inheritdoc/> public long MaximumKilobytes { get; set; } = EventLogDefaultMaxKilobytes; /// <inheritdoc/> public void WriteEntry(string message, EventLogEntryType entryType, int eventId, short category) { if (!IsEventLogAssociated) throw new InvalidOperationException("Missing initialization using AssociateNewEventLog"); WrittenEntries.Add(new EventRecord() { Message = message, EntryType = entryType, EventId = eventId, Category = category, Source = Source, Log = Log, MachineName = MachineName, }); } /// <inheritdoc/> public bool IsEventLogAssociated { get; private set; } /// <inheritdoc/> public void AssociateNewEventLog(string logName, string machineName, string source) { Log = logName; MachineName = machineName; Source = source; if (!IsEventLogAssociated) { IsEventLogAssociated = true; } } /// <inheritdoc/> public void DeleteEventSource(string source, string machineName) => DeleteEventSourceFunction(source, machineName); /// <inheritdoc/> public bool SourceExists(string source, string machineName) => SourceExistsFunction(source, machineName); /// <inheritdoc/> public string LogNameFromSourceName(string source, string machineName) => LogNameFromSourceNameFunction(source, machineName); /// <inheritdoc/> public void CreateEventSource(EventSourceCreationData sourceData) => CreateEventSourceFunction(sourceData); } } } #endif<file_sep>using System; using NLog; using NLog.Targets; using System.Diagnostics; public class Example { public static void LogMethod(string level, string message) { Console.WriteLine("l: {0} m: {1}", level, message); } static void Main(string[] args) { MethodCallTarget target = new MethodCallTarget(); target.ClassName = typeof(Example).AssemblyQualifiedName; target.MethodName = "LogMethod"; target.Parameters.Add(new MethodCallParameter("${level}")); target.Parameters.Add(new MethodCallParameter("${message}")); NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); logger.Error("error message"); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using System; using System.Collections.Generic; using NLog.Common; /// <summary> /// Asynchronous request queue. /// </summary> internal class AsyncRequestQueue : AsyncRequestQueueBase { private readonly Queue<AsyncLogEventInfo> _logEventInfoQueue = new Queue<AsyncLogEventInfo>(1000); /// <summary> /// Initializes a new instance of the AsyncRequestQueue class. /// </summary> /// <param name="requestLimit">Request limit.</param> /// <param name="overflowAction">The overflow action.</param> public AsyncRequestQueue(int requestLimit, AsyncTargetWrapperOverflowAction overflowAction) { RequestLimit = requestLimit; OnOverflow = overflowAction; } /// <summary> /// Gets the number of requests currently in the queue. /// </summary> public int RequestCount { get { lock (_logEventInfoQueue) { return _logEventInfoQueue.Count; } } } public override bool IsEmpty => RequestCount == 0; /// <summary> /// Enqueues another item. If the queue is overflown the appropriate /// action is taken as specified by <see cref="AsyncRequestQueueBase.OnOverflow"/>. /// </summary> /// <param name="logEventInfo">The log event info.</param> /// <returns>Queue was empty before enqueue</returns> public override bool Enqueue(AsyncLogEventInfo logEventInfo) { lock (_logEventInfoQueue) { if (_logEventInfoQueue.Count >= RequestLimit) { switch (OnOverflow) { case AsyncTargetWrapperOverflowAction.Discard: InternalLogger.Debug("AsyncQueue - Discarding single item, because queue is full"); var lostItem = _logEventInfoQueue.Dequeue(); OnLogEventDropped(lostItem.LogEvent); break; case AsyncTargetWrapperOverflowAction.Grow: InternalLogger.Debug("AsyncQueue - Growing the size of queue, because queue is full"); OnLogEventQueueGrows(RequestCount + 1); RequestLimit *= 2; break; case AsyncTargetWrapperOverflowAction.Block: while (_logEventInfoQueue.Count >= RequestLimit) { InternalLogger.Debug("AsyncQueue - Blocking until ready, because queue is full"); System.Threading.Monitor.Wait(_logEventInfoQueue); InternalLogger.Trace("AsyncQueue - Entered critical section."); } InternalLogger.Trace("AsyncQueue - Limit ok."); break; } } _logEventInfoQueue.Enqueue(logEventInfo); return _logEventInfoQueue.Count == 1; } } /// <summary> /// Dequeues a maximum of <c>count</c> items from the queue /// and adds returns the list containing them. /// </summary> /// <param name="count">Maximum number of items to be dequeued</param> /// <returns>The array of log events.</returns> public override AsyncLogEventInfo[] DequeueBatch(int count) { AsyncLogEventInfo[] resultEvents; lock (_logEventInfoQueue) { if (_logEventInfoQueue.Count < count) count = _logEventInfoQueue.Count; if (count == 0) return Internal.ArrayHelper.Empty<AsyncLogEventInfo>(); resultEvents = new AsyncLogEventInfo[count]; for (int i = 0; i < count; ++i) { resultEvents[i] = _logEventInfoQueue.Dequeue(); } if (OnOverflow == AsyncTargetWrapperOverflowAction.Block) { System.Threading.Monitor.PulseAll(_logEventInfoQueue); } } return resultEvents; } /// <summary> /// Dequeues into a preallocated array, instead of allocating a new one /// </summary> /// <param name="count">Maximum number of items to be dequeued</param> /// <param name="result">Preallocated list</param> public override void DequeueBatch(int count, IList<AsyncLogEventInfo> result) { lock (_logEventInfoQueue) { if (_logEventInfoQueue.Count < count) count = _logEventInfoQueue.Count; for (int i = 0; i < count; ++i) result.Add(_logEventInfoQueue.Dequeue()); if (OnOverflow == AsyncTargetWrapperOverflowAction.Block) { System.Threading.Monitor.PulseAll(_logEventInfoQueue); } } } /// <summary> /// Clears the queue. /// </summary> public override void Clear() { lock (_logEventInfoQueue) { _logEventInfoQueue.Clear(); if (OnOverflow == AsyncTargetWrapperOverflowAction.Block) { // Try to eject any threads, that are blocked in the RequestQueue System.Threading.Monitor.PulseAll(_logEventInfoQueue); } } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.Text; using System.Threading; using NLog.Common; using NLog.Internal; using NLog.Internal.NetworkSenders; using NLog.Layouts; using NLog.Targets.Wrappers; /// <summary> /// Sends log messages over the network. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/Network-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/Network-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/Network/NLog.config" /> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/Network/Simple/Example.cs" /> /// <p> /// To print the results, use any application that's able to receive messages over /// TCP or UDP. <a href="http://m.nu/program/util/netcat/netcat.html">NetCat</a> is /// a simple but very powerful command-line tool that can be used for that. This image /// demonstrates the NetCat tool receiving log messages from Network target. /// </p> /// <img src="examples/targets/Screenshots/Network/Output.gif" /> /// <p> /// There are two specialized versions of the Network target: <a href="T_NLog_Targets_ChainsawTarget.htm">Chainsaw</a> /// and <a href="T_NLog_Targets_NLogViewerTarget.htm">NLogViewer</a> which write to instances of Chainsaw log4j viewer /// or NLogViewer application respectively. /// </p> /// </example> [Target("Network")] public class NetworkTarget : TargetWithLayout { private readonly Dictionary<string, LinkedListNode<NetworkSender>> _currentSenderCache = new Dictionary<string, LinkedListNode<NetworkSender>>(StringComparer.Ordinal); private readonly LinkedList<NetworkSender> _openNetworkSenders = new LinkedList<NetworkSender>(); private readonly ReusableBufferCreator _reusableEncodingBuffer = new ReusableBufferCreator(32 * 1024); /// <summary> /// Initializes a new instance of the <see cref="NetworkTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> public NetworkTarget() { SenderFactory = NetworkSenderFactory.Default; } /// <summary> /// Initializes a new instance of the <see cref="NetworkTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> /// <param name="name">Name of the target.</param> public NetworkTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets the network address. /// </summary> /// <remarks> /// The network address can be: /// <ul> /// <li>tcp://host:port - TCP (auto select IPv4/IPv6)</li> /// <li>tcp4://host:port - force TCP/IPv4</li> /// <li>tcp6://host:port - force TCP/IPv6</li> /// <li>udp://host:port - UDP (auto select IPv4/IPv6)</li> /// <li>udp4://host:port - force UDP/IPv4</li> /// <li>udp6://host:port - force UDP/IPv6</li> /// <li>http://host:port/pageName - HTTP using POST verb</li> /// <li>https://host:port/pageName - HTTPS using POST verb</li> /// </ul> /// For SOAP-based webservice support over HTTP use WebService target. /// </remarks> /// <docgen category='Connection Options' order='10' /> public Layout Address { get; set; } /// <summary> /// Gets or sets a value indicating whether to keep connection open whenever possible. /// </summary> /// <docgen category='Connection Options' order='10' /> public bool KeepConnection { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether to append newline at the end of log message. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool NewLine { get; set; } /// <summary> /// Gets or sets the end of line value if a newline is appended at the end of log message <see cref="NewLine"/>. /// </summary> /// <docgen category='Payload Options' order='10' /> public LineEndingMode LineEnding { get => _lineEnding; set { _lineEnding = value; NewLine = value != null; } } private LineEndingMode _lineEnding = LineEndingMode.CRLF; /// <summary> /// Gets or sets the maximum message size in bytes. On limit breach then <see cref="OnOverflow"/> action is activated. /// </summary> /// <docgen category='Payload Options' order='10' /> public int MaxMessageSize { get; set; } = 65000; /// <summary> /// Gets or sets the maximum simultaneous connections. Requires <see cref="KeepConnection"/> = false /// </summary> /// <remarks> /// When having reached the maximum limit, then <see cref="OnConnectionOverflow"/> action will apply. /// </remarks> /// <docgen category="Connection Options" order="10"/> public int MaxConnections { get; set; } = 100; /// <summary> /// Gets or sets the action that should be taken, when more connections than <see cref="MaxConnections"/>. /// </summary> /// <docgen category='Connection Options' order='10' /> public NetworkTargetConnectionsOverflowAction OnConnectionOverflow { get; set; } = NetworkTargetConnectionsOverflowAction.Discard; /// <summary> /// Gets or sets the maximum queue size for a single connection. Requires <see cref="KeepConnection"/> = true /// </summary> /// <remarks> /// When having reached the maximum limit, then <see cref="OnQueueOverflow"/> action will apply. /// </remarks> /// <docgen category='Connection Options' order='10' /> public int MaxQueueSize { get; set; } = 10000; /// <summary> /// Gets or sets the action that should be taken, when more pending messages than <see cref="MaxQueueSize"/>. /// </summary> /// <docgen category='Connection Options' order='10' /> public NetworkTargetQueueOverflowAction OnQueueOverflow { get; set; } = NetworkTargetQueueOverflowAction.Discard; /// <summary> /// Occurs when LogEvent has been dropped. /// </summary> /// <remarks> /// - When internal queue is full and <see cref="OnQueueOverflow"/> set to <see cref="NetworkTargetOverflowAction.Discard"/><br/> /// - When connection-list is full and <see cref="OnConnectionOverflow"/> set to <see cref="NetworkTargetConnectionsOverflowAction.Discard"/><br/> /// - When message is too big and <see cref="OnOverflow"/> set to <see cref="NetworkTargetOverflowAction.Discard"/><br/> /// </remarks> public event EventHandler<NetworkLogEventDroppedEventArgs> LogEventDropped; /// <summary> /// Gets or sets the size of the connection cache (number of connections which are kept alive). Requires <see cref="KeepConnection"/> = true /// </summary> /// <docgen category="Connection Options" order="10"/> public int ConnectionCacheSize { get; set; } = 5; /// <summary> /// Gets or sets the action that should be taken if the message is larger than <see cref="MaxMessageSize" /> /// </summary> /// <remarks> /// For TCP sockets then <see cref="NetworkTargetOverflowAction.Split"/> means no-limit, as TCP sockets /// performs splitting automatically. /// /// For UDP Network sender then <see cref="NetworkTargetOverflowAction.Split"/> means splitting the message /// into smaller chunks. This can be useful on networks using DontFragment, which drops network packages /// larger than MTU-size (1472 bytes). /// </remarks> /// <docgen category='Connection Options' order='10' /> public NetworkTargetOverflowAction OnOverflow { get; set; } = NetworkTargetOverflowAction.Split; /// <summary> /// Gets or sets the encoding to be used. /// </summary> /// <docgen category='Payload Options' order='10' /> public Encoding Encoding { get; set; } = Encoding.UTF8; /// <summary> /// Gets or sets the SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. /// </summary> /// <docgen category='Connection Options' order='10' /> public System.Security.Authentication.SslProtocols SslProtocols { get; set; } = System.Security.Authentication.SslProtocols.None; /// <summary> /// The number of seconds a connection will remain idle before the first keep-alive probe is sent /// </summary> /// <docgen category='Connection Options' order='10' /> public int KeepAliveTimeSeconds { get; set; } /// <summary> /// Type of compression for protocol payload. Useful for UDP where datagram max-size is 8192 bytes. /// </summary> public NetworkTargetCompressionType Compress { get; set; } /// <summary> /// Skip compression when protocol payload is below limit to reduce overhead in cpu-usage and additional headers /// </summary> public int CompressMinBytes { get; set; } internal INetworkSenderFactory SenderFactory { get; set; } /// <summary> /// Flush any pending log messages asynchronously (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { int remainingCount; void Continuation(Exception ex) { // ignore exception if (Interlocked.Decrement(ref remainingCount) == 0) { asyncContinuation(null); } } lock (_openNetworkSenders) { remainingCount = _openNetworkSenders.Count; if (remainingCount == 0) { // nothing to flush asyncContinuation(null); } else { // otherwise call FlushAsync() on all senders // and invoke continuation at the very end foreach (var openSender in _openNetworkSenders) { openSender.FlushAsync(Continuation); } } } } /// <inheritdoc/> protected override void CloseTarget() { base.CloseTarget(); lock (_currentSenderCache) { lock (_openNetworkSenders) { foreach (var openSender in _openNetworkSenders) { openSender.Close(ex => { }); } _openNetworkSenders.Clear(); } _currentSenderCache.Clear(); } } /// <summary> /// Sends the /// rendered logging event over the network optionally concatenating it with a newline character. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(AsyncLogEventInfo logEvent) { string address = RenderLogEvent(Address, logEvent.LogEvent); InternalLogger.Trace("{0}: Sending to address: '{1}'", this, address); byte[] bytes = GetBytesToWrite(logEvent.LogEvent); if (KeepConnection) { WriteBytesToCachedNetworkSender(address, bytes, logEvent); } else { WriteBytesToNewNetworkSender(address, bytes, logEvent); } } private void WriteBytesToCachedNetworkSender(string address, byte[] bytes, AsyncLogEventInfo logEvent) { LinkedListNode<NetworkSender> senderNode; try { senderNode = GetCachedNetworkSender(address); } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed to create sender to address: '{1}'", this, address); OnLogEventDropped(this, NetworkLogEventDroppedEventArgs.NetworkErrorDetected); throw; } WriteBytesToNetworkSender( senderNode.Value, bytes, ex => { if (ex != null) { InternalLogger.Error(ex, "{0}: Error when sending.", this); OnLogEventDropped(this, NetworkLogEventDroppedEventArgs.NetworkErrorDetected); ReleaseCachedConnection(senderNode); } logEvent.Continuation(ex); }); } private void WriteBytesToNewNetworkSender(string address, byte[] bytes, AsyncLogEventInfo logEvent) { NetworkSender sender; LinkedListNode<NetworkSender> linkedListNode; lock (_openNetworkSenders) { //handle too many connections var tooManyConnections = _openNetworkSenders.Count >= MaxConnections; if (tooManyConnections && MaxConnections > 0) { switch (OnConnectionOverflow) { case NetworkTargetConnectionsOverflowAction.Discard: InternalLogger.Debug("{0}: Discarding message, because too many open connections.", this); OnLogEventDropped(this, NetworkLogEventDroppedEventArgs.MaxConnectionsOverflow); logEvent.Continuation(null); return; case NetworkTargetConnectionsOverflowAction.Grow: MaxConnections = MaxConnections * 2; InternalLogger.Debug("{0}: Growing max connections limit, because many open connections.", this); break; case NetworkTargetConnectionsOverflowAction.Block: while (_openNetworkSenders.Count >= MaxConnections) { InternalLogger.Debug("{0}: Blocking until ready, because too many open connections.", this); Monitor.Wait(_openNetworkSenders); InternalLogger.Trace("{0}: Entered critical section.", this); } InternalLogger.Trace("{0}: Limit ok.", this); break; } } try { sender = CreateNetworkSender(address); } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed to create sender to address: '{1}'", this, address); OnLogEventDropped(this, NetworkLogEventDroppedEventArgs.NetworkErrorDetected); throw; } linkedListNode = _openNetworkSenders.AddLast(sender); } WriteBytesToNetworkSender( sender, bytes, ex => { lock (_openNetworkSenders) { TryRemove(_openNetworkSenders, linkedListNode); if (OnConnectionOverflow == NetworkTargetConnectionsOverflowAction.Block) { Monitor.PulseAll(_openNetworkSenders); } } if (ex != null) { InternalLogger.Error(ex, "{0}: Error when sending.", this); OnLogEventDropped(this, NetworkLogEventDroppedEventArgs.NetworkErrorDetected); } sender.Close(ex2 => { }); logEvent.Continuation(ex); }); } private void OnLogEventDropped(object sender, NetworkLogEventDroppedEventArgs logEventDroppedEventArgs) { LogEventDropped?.Invoke(this, logEventDroppedEventArgs); } /// <summary> /// Try to remove. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="node"></param> /// <returns>removed something?</returns> private static bool TryRemove<T>(LinkedList<T> list, LinkedListNode<T> node) { if (node is null || list != node.List) { return false; } list.Remove(node); return true; } /// <summary> /// Gets the bytes to be written. /// </summary> /// <param name="logEvent">Log event.</param> /// <returns>Byte array.</returns> protected virtual byte[] GetBytesToWrite(LogEventInfo logEvent) { var payload = RenderBytesToWrite(logEvent); if (Compress != NetworkTargetCompressionType.None) { payload = CompressBytesToWrite(payload); } return payload; } private byte[] RenderBytesToWrite(LogEventInfo logEvent) { using (var localBuffer = _reusableEncodingBuffer.Allocate()) { if (!NewLine && logEvent.TryGetCachedLayoutValue(Layout, out var text)) { return GetBytesFromString(localBuffer.Result, text?.ToString() ?? string.Empty); } else { using (var localBuilder = ReusableLayoutBuilder.Allocate()) { Layout.Render(logEvent, localBuilder.Result); if (NewLine) { localBuilder.Result.Append(LineEnding.NewLineCharacters); } return GetBytesFromStringBuilder(localBuffer.Result, localBuilder.Result); } } } } private byte[] GetBytesFromStringBuilder(char[] charBuffer, StringBuilder stringBuilder) { InternalLogger.Trace("{0}: Sending {1} chars", this, stringBuilder.Length); if (stringBuilder.Length <= charBuffer.Length) { stringBuilder.CopyTo(0, charBuffer, 0, stringBuilder.Length); return Encoding.GetBytes(charBuffer, 0, stringBuilder.Length); } return Encoding.GetBytes(stringBuilder.ToString()); } private byte[] GetBytesFromString(char[] charBuffer, string layoutMessage) { InternalLogger.Trace("{0}: Sending {1}", this, layoutMessage); if (layoutMessage.Length <= charBuffer.Length) { layoutMessage.CopyTo(0, charBuffer, 0, layoutMessage.Length); return Encoding.GetBytes(charBuffer, 0, layoutMessage.Length); } return Encoding.GetBytes(layoutMessage); } private byte[] CompressBytesToWrite(byte[] payload) { if (payload.Length > CompressMinBytes) { using (var outputStream = new System.IO.MemoryStream(Math.Max(payload.Length / 10, 256))) { #if !NET35 using (var gzipStream = new System.IO.Compression.GZipStream(outputStream, Compress == NetworkTargetCompressionType.GZip ? System.IO.Compression.CompressionLevel.Optimal : System.IO.Compression.CompressionLevel.Fastest, true)) #else using (var gzipStream = new System.IO.Compression.GZipStream(outputStream, System.IO.Compression.CompressionMode.Compress, true)) #endif { gzipStream.Write(payload, 0, payload.Length); } payload = outputStream.ToArray(); } } return payload; } private LinkedListNode<NetworkSender> GetCachedNetworkSender(string address) { lock (_currentSenderCache) { // already have address if (_currentSenderCache.TryGetValue(address, out var senderNode)) { senderNode.Value.CheckSocket(); return senderNode; } if (_currentSenderCache.Count >= ConnectionCacheSize) { // make room in the cache by closing the least recently used connection int minAccessTime = int.MaxValue; LinkedListNode<NetworkSender> leastRecentlyUsed = null; foreach (var pair in _currentSenderCache) { var networkSender = pair.Value.Value; if (networkSender.LastSendTime < minAccessTime) { minAccessTime = networkSender.LastSendTime; leastRecentlyUsed = pair.Value; } } if (leastRecentlyUsed != null) { ReleaseCachedConnection(leastRecentlyUsed); } } NetworkSender sender = CreateNetworkSender(address); lock (_openNetworkSenders) { senderNode = _openNetworkSenders.AddLast(sender); } _currentSenderCache.Add(address, senderNode); return senderNode; } } private NetworkSender CreateNetworkSender(string address) { var sender = SenderFactory.Create(address, MaxQueueSize, OnQueueOverflow, MaxMessageSize, SslProtocols, TimeSpan.FromSeconds(KeepAliveTimeSeconds)); sender.Initialize(); if (KeepConnection || LogEventDropped != null) { sender.LogEventDropped += OnLogEventDropped; } return sender; } private void ReleaseCachedConnection(LinkedListNode<NetworkSender> senderNode) { lock (_currentSenderCache) { var networkSender = senderNode.Value; lock (_openNetworkSenders) { if (TryRemove(_openNetworkSenders, senderNode)) { // only remove it once networkSender.Close(ex => { }); } } // make sure the current sender for this address is the one we want to remove if (_currentSenderCache.TryGetValue(networkSender.Address, out var sender2) && ReferenceEquals(senderNode, sender2)) { _currentSenderCache.Remove(networkSender.Address); } } } private void WriteBytesToNetworkSender(NetworkSender sender, byte[] buffer, AsyncContinuation continuation) { int messageSize = buffer.Length; if (messageSize > MaxMessageSize) { if (OnOverflow == NetworkTargetOverflowAction.Discard) { InternalLogger.Debug("{0}: Discarded LogEvent because MessageSize={1} is above MaxMessageSize={2}", this, messageSize, MaxMessageSize); OnLogEventDropped(this, NetworkLogEventDroppedEventArgs.MaxMessageSizeOverflow); continuation(null); return; } if (OnOverflow == NetworkTargetOverflowAction.Error) { InternalLogger.Debug("{0}: Discarded LogEvent because MessageSize={1} is above MaxMessageSize={2}", this, messageSize, MaxMessageSize); OnLogEventDropped(this, NetworkLogEventDroppedEventArgs.MaxMessageSizeOverflow); continuation(new InvalidOperationException($"NetworkTarget: Discarded LogEvent because MessageSize={messageSize} is above MaxMessageSize={MaxMessageSize}")); return; } } InternalLogger.Trace("{0}: Sending LogEvent MessageSize={1}", this, messageSize); if (messageSize <= 0) { continuation(null); return; } sender.Send(buffer, 0, messageSize, continuation); } } }<file_sep>using NLog; using NLog.Targets; using NLog.Targets.Wrappers; using System.Threading; class Example { static void Main(string[] args) { FileTarget target = new FileTarget(); target.Layout = "${longdate} ${logger} ${message}"; target.FileName = "${basedir}/logs/logfile.${level}.txt"; // where to store the archive files target.ArchiveFileName = "${basedir}/archives/${level}/log.{#####}.txt"; target.ArchiveEvery = FileTarget.ArchiveEveryMode.Minute; target.ArchiveNumbering = FileTarget.ArchiveNumberingMode.Rolling; target.MaxArchiveFiles = 3; target.ArchiveAboveSize = 10000; // this speeds up things when no other processes are writing to the file target.ConcurrentWrites = true; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); // generate a large number of messages, sleeping 1/10 of second between writes // to observe time-based archiving which occurs every minute // the volume is high enough to cause ArchiveAboveSize to be triggered // so that log files larger than 10000 bytes are archived as well // in this version, a single File target keeps track of 3 sets of log and // archive files, one for each level // you get: // logs/logfile.Debug.txt // logs/logfile.Error.txt // logs/logfile.Fatal.txt // // and your archives go to: // // archives/Debug/log.00000.txt // archives/Debug/log.00001.txt // archives/Debug/log.00002.txt // archives/Debug/log.00003.txt // archives/Error/log.00000.txt // archives/Error/log.00001.txt // archives/Error/log.00002.txt // archives/Error/log.00003.txt // archives/Fatal/log.00000.txt // archives/Fatal/log.00001.txt // archives/Fatal/log.00002.txt // archives/Fatal/log.00003.txt for (int i = 0; i < 2500; ++i) { logger.Debug("log message {i}", i); logger.Error("log message {i}", i); logger.Fatal("log message {i}", i); Thread.Sleep(100); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 && !NETSTANDARD1_5 namespace NLog.Internal { using System.Net.Mail; /// <summary> /// Supports mocking of SMTP Client code. /// </summary> /// <remarks> /// Disabled Error CS0618 'SmtpClient' is obsolete: 'SmtpClient and its network of types are poorly designed, /// we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead' /// </remarks> #pragma warning disable 618 internal sealed class MySmtpClient : SmtpClient, ISmtpClient #pragma warning restore 618 { #if NET35 || MONO /// <summary> /// Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, and releases all resources used by the current instance of the <see cref="T:System.Net.Mail.SmtpClient"/> class. /// </summary> #pragma warning disable 108 public void Dispose() #pragma warning restore 108 { // dispose was added in .NET Framework 4.0, previous frameworks don't need it but adding it here to make the // user experience the same across all } #endif } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using NLog.Common; using NLog.Filters; using NLog.Internal; using NLog.LayoutRenderers; using NLog.Layouts; using NLog.Targets; using NLog.Time; /// <summary> /// Provides registration information for named items (targets, layouts, layout renderers, etc.) managed by NLog. /// /// Everything of an assembly could be loaded by <see cref="RegisterItemsFromAssembly(System.Reflection.Assembly)"/> /// </summary> public class ConfigurationItemFactory { private static ConfigurationItemFactory _defaultInstance; internal static readonly object SyncRoot = new object(); private readonly ServiceRepository _serviceRepository; #pragma warning disable CS0618 // Type or member is obsolete internal IAssemblyExtensionLoader AssemblyLoader { get; } = new AssemblyExtensionLoader(); #pragma warning restore CS0618 // Type or member is obsolete private readonly IFactory[] _allFactories; private readonly Factory<Target, TargetAttribute> _targets; private readonly Factory<Filter, FilterAttribute> _filters; private readonly LayoutRendererFactory _layoutRenderers; private readonly Factory<Layout, LayoutAttribute> _layouts; private readonly MethodFactory _conditionMethods; private readonly Factory<LayoutRenderer, AmbientPropertyAttribute> _ambientProperties; private readonly Factory<TimeSource, TimeSourceAttribute> _timeSources; private readonly Dictionary<Type, ItemFactory> _itemFactories = new Dictionary<Type, ItemFactory>(256); private struct ItemFactory { public readonly Func<Dictionary<string, PropertyInfo>> ItemProperties; public readonly Func<object> ItemCreator; public ItemFactory(Func<Dictionary<string, PropertyInfo>> itemProperties, Func<object> itemCreator) { ItemProperties = itemProperties; ItemCreator = itemCreator; } } /// <summary> /// Called before the assembly will be loaded. /// </summary> [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] public static event EventHandler<AssemblyLoadingEventArgs> AssemblyLoading; /// <summary> /// Initializes a new instance of the <see cref="ConfigurationItemFactory"/> class. /// </summary> public ConfigurationItemFactory() : this(LogManager.LogFactory.ServiceRepository, null) { } /// <summary> /// Initializes a new instance of the <see cref="ConfigurationItemFactory"/> class. /// </summary> /// <param name="assemblies">The assemblies to scan for named items.</param> [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] public ConfigurationItemFactory(params Assembly[] assemblies) : this(LogManager.LogFactory.ServiceRepository, null) { foreach (var asm in assemblies) { RegisterItemsFromAssembly(asm); } } internal ConfigurationItemFactory(ServiceRepository serviceRepository, ConfigurationItemFactory globalDefaultFactory) { _serviceRepository = Guard.ThrowIfNull(serviceRepository); _targets = new Factory<Target, TargetAttribute>(this, globalDefaultFactory?._targets); _filters = new Factory<Filter, FilterAttribute>(this, globalDefaultFactory?._filters); _layoutRenderers = new LayoutRendererFactory(this, globalDefaultFactory?._layoutRenderers); _layouts = new Factory<Layout, LayoutAttribute>(this, globalDefaultFactory?._layouts); _conditionMethods = new MethodFactory(globalDefaultFactory?._conditionMethods); _ambientProperties = new Factory<LayoutRenderer, AmbientPropertyAttribute>(this, globalDefaultFactory?._ambientProperties); _timeSources = new Factory<TimeSource, TimeSourceAttribute>(this, globalDefaultFactory?._timeSources); _allFactories = new IFactory[] { _targets, _filters, _layoutRenderers, _layouts, _conditionMethods, _ambientProperties, _timeSources, }; } /// <summary> /// Gets or sets default singleton instance of <see cref="ConfigurationItemFactory"/>. /// </summary> /// <remarks> /// This property implements lazy instantiation so that the <see cref="ConfigurationItemFactory"/> is not built before /// the internal logger is configured. /// </remarks> public static ConfigurationItemFactory Default { get => _defaultInstance ?? (_defaultInstance = BuildDefaultFactory()); set => _defaultInstance = value; } /// <summary> /// Gets the <see cref="Target"/> factory. /// </summary> public IFactory<Target> TargetFactory => _targets; /// <summary> /// Gets the <see cref="Layout"/> factory. /// </summary> public IFactory<Layout> LayoutFactory => _layouts; /// <summary> /// Gets the <see cref="LayoutRenderer"/> factory. /// </summary> public IFactory<LayoutRenderer> LayoutRendererFactory => _layoutRenderers; /// <summary> /// Gets the ambient property factory. /// </summary> public IFactory<LayoutRenderer> AmbientRendererFactory => _ambientProperties; /// <summary> /// Gets the <see cref="Filter"/> factory. /// </summary> public IFactory<Filter> FilterFactory => _filters; /// <summary> /// Gets the <see cref="TimeSource"/> factory. /// </summary> public IFactory<TimeSource> TimeSourceFactory => _timeSources; internal MethodFactory ConditionMethodFactory => _conditionMethods; internal Factory<Target, TargetAttribute> GetTargetFactory() => _targets; internal Factory<Layout, LayoutAttribute> GetLayoutFactory() => _layouts; internal LayoutRendererFactory GetLayoutRendererFactory() => _layoutRenderers; internal ICollection<Type> ItemTypes { get { lock (SyncRoot) return new List<Type>(_itemFactories.Keys); } } /// <summary> /// Gets or sets the creator delegate used to instantiate configuration objects. /// </summary> /// <remarks> /// By overriding this property, one can enable dependency injection or interception for created objects. /// </remarks> [Obsolete("Instead use NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public ConfigurationItemCreator CreateInstance { get; set; } = FactoryHelper.CreateInstance; /// <summary> /// Gets the <see cref="Target"/> factory. /// </summary> /// <value>The target factory.</value> [Obsolete("Instead use LogManager.Setup().SetupExtensions(ext => ext.RegisterTarget<T>()). Marked obsolete with NLog v5.2")] public INamedItemFactory<Target, Type> Targets => _targets; /// <summary> /// Gets the <see cref="Layout"/> factory. /// </summary> /// <value>The layout factory.</value> [Obsolete("Instead use LogManager.Setup().SetupExtensions(ext => ext.RegisterLayout<T>()). Marked obsolete with NLog v5.2")] public INamedItemFactory<Layout, Type> Layouts => _layouts; /// <summary> /// Gets the <see cref="LayoutRenderer"/> factory. /// </summary> /// <value>The layout renderer factory.</value> [Obsolete("Instead use LogManager.Setup().SetupExtensions(ext => ext.RegisterLayoutRenderer<T>()). Marked obsolete with NLog v5.2")] public INamedItemFactory<LayoutRenderer, Type> LayoutRenderers => _layoutRenderers; /// <summary> /// Gets the ambient property factory. /// </summary> /// <value>The ambient property factory.</value> [Obsolete("Instead use NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public INamedItemFactory<LayoutRenderer, Type> AmbientProperties => _ambientProperties; /// <summary> /// Gets the <see cref="Filter"/> factory. /// </summary> /// <value>The filter factory.</value> [Obsolete("Instead use NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public INamedItemFactory<Filter, Type> Filters => _filters; /// <summary> /// Gets the time source factory. /// </summary> /// <value>The time source factory.</value> [Obsolete("Instead use NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public INamedItemFactory<TimeSource, Type> TimeSources => _timeSources; /// <summary> /// Gets the condition method factory. /// </summary> /// <value>The condition method factory.</value> [Obsolete("Instead use NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public INamedItemFactory<MethodInfo, MethodInfo> ConditionMethods => _conditionMethods; /// <summary> /// Gets or sets the JSON serializer to use with <see cref="JsonLayout"/> /// </summary> [Obsolete("Instead use NLog.LogManager.Setup().SetupSerialization(s => s.RegisterJsonConverter()) or ResolveService<IJsonConverter>(). Marked obsolete on NLog 5.0")] public IJsonConverter JsonConverter { get => _serviceRepository.GetService<IJsonConverter>(); set => _serviceRepository.RegisterJsonConverter(value); } /// <summary> /// Gets or sets the string serializer to use with <see cref="LogEventInfo.MessageTemplateParameters"/> /// </summary> [Obsolete("Instead use NLog.LogManager.Setup().SetupSerialization(s => s.RegisterValueFormatter()) or ResolveService<IValueFormatter>(). Marked obsolete on NLog 5.0")] public IValueFormatter ValueFormatter { get => _serviceRepository.GetService<IValueFormatter>(); set => _serviceRepository.RegisterValueFormatter(value); } /// <summary> /// Gets or sets the parameter converter to use with <see cref="TargetWithContext"/> or <see cref="Layout{T}"/> /// </summary> [Obsolete("Instead use LogFactory.ServiceRepository.RegisterService(). Marked obsolete on NLog 5.0")] public IPropertyTypeConverter PropertyTypeConverter { get => _serviceRepository.GetService<IPropertyTypeConverter>(); set => _serviceRepository.RegisterPropertyTypeConverter(value); } /// <summary> /// Perform message template parsing and formatting of LogEvent messages (True = Always, False = Never, Null = Auto Detect) /// </summary> /// <remarks> /// - Null (Auto Detect) : NLog-parser checks <see cref="LogEventInfo.Message"/> for positional parameters, and will then fallback to string.Format-rendering. /// - True: Always performs the parsing of <see cref="LogEventInfo.Message"/> and rendering of <see cref="LogEventInfo.FormattedMessage"/> using the NLog-parser (Allows custom formatting with <see cref="ValueFormatter"/>) /// - False: Always performs parsing and rendering using string.Format (Fastest if not using structured logging) /// </remarks> public bool? ParseMessageTemplates { get => _serviceRepository.ResolveMessageTemplateParser(); set => _serviceRepository.RegisterMessageTemplateParser(value); } /// <summary> /// Registers named items from the assembly. /// </summary> /// <param name="assembly">The assembly.</param> [Obsolete("Instead use NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public void RegisterItemsFromAssembly(Assembly assembly) { RegisterItemsFromAssembly(assembly, string.Empty); } /// <summary> /// Registers named items from the assembly. /// </summary> /// <param name="assembly">The assembly.</param> /// <param name="itemNamePrefix">Item name prefix.</param> [Obsolete("Instead use NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public void RegisterItemsFromAssembly(Assembly assembly, string itemNamePrefix) { if (AssemblyLoading != null) { var args = new AssemblyLoadingEventArgs(assembly); AssemblyLoading.Invoke(null, args); if (args.Cancel) { InternalLogger.Info("Loading assembly '{0}' is canceled", assembly.FullName); return; } } InternalLogger.Debug("ScanAssembly('{0}')", assembly.FullName); var typesToScan = AssemblyHelpers.SafeGetTypes(assembly); if (typesToScan?.Length > 0) { string assemblyName = string.Empty; if (ReferenceEquals(assembly, typeof(LogFactory).GetAssembly())) { typesToScan = typesToScan.Where(t => t.IsPublic() && t.IsClass()).ToArray(); } else { assemblyName = new AssemblyName(assembly.FullName).Name; PreloadAssembly(typesToScan); } lock (SyncRoot) { foreach (IFactory f in _allFactories) { f.ScanTypes(typesToScan, assemblyName, itemNamePrefix); } } } } /// <summary> /// Call Preload for NLogPackageLoader /// </summary> /// <remarks> /// Every package could implement a class "NLogPackageLoader" (namespace not important) with the public static method "Preload" (no arguments) /// This method will be called just before registering all items in the assembly. /// </remarks> /// <param name="typesToScan"></param> [Obsolete("Instead use NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2072")] public void PreloadAssembly(Type[] typesToScan) { var types = typesToScan.Where(t => t.Name.Equals("NLogPackageLoader", StringComparison.OrdinalIgnoreCase)); foreach (var type in types) { CallPreload(type); } } /// <summary> /// Call the Preload method for <paramref name="type"/>. The Preload method must be static. /// </summary> /// <param name="type"></param> [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] private void CallPreload([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) { if (type is null) { return; } InternalLogger.Debug("Found for preload'{0}'", type.FullName); var preloadMethod = type.GetMethod("Preload"); if (preloadMethod != null) { if (preloadMethod.IsStatic) { InternalLogger.Debug("NLogPackageLoader contains Preload method"); //only static, so first param null try { var parameters = CreatePreloadParameters(preloadMethod, this); preloadMethod.Invoke(null, parameters); InternalLogger.Debug("Preload successfully invoked for '{0}'", type.FullName); } catch (Exception e) { InternalLogger.Warn(e, "Invoking Preload for '{0}' failed", type.FullName); } } else { InternalLogger.Debug("NLogPackageLoader contains a preload method, but isn't static"); } } else { InternalLogger.Debug("{0} doesn't contain Preload method", type.FullName); } } [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] private static object[] CreatePreloadParameters(MethodInfo preloadMethod, ConfigurationItemFactory configurationItemFactory) { var firstParam = preloadMethod.GetParameters().FirstOrDefault(); object[] parameters = null; if (firstParam?.ParameterType == typeof(ConfigurationItemFactory)) { parameters = new object[] { configurationItemFactory }; } return parameters; } /// <summary> /// Clears the contents of all factories. /// </summary> public void Clear() { lock (SyncRoot) { foreach (IFactory f in _allFactories) { f.Clear(); } } } /// <summary> /// Registers the type. /// </summary> /// <param name="type">The type to register.</param> /// <param name="itemNamePrefix">The item name prefix.</param> [Obsolete("Instead use NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public void RegisterType([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicMethods)] Type type, string itemNamePrefix) { lock (SyncRoot) { foreach (IFactory f in _allFactories) { f.RegisterType(type, itemNamePrefix); } } } internal void RegisterType<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicMethods)] TType>() where TType : class, new() { lock (SyncRoot) { RegisterTypeProperties<TType>(() => new TType()); foreach (IFactory f in _allFactories) { f.RegisterType(typeof(TType), string.Empty); } } } internal void RegisterTypeProperties<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] TType>(Func<object> itemCreator) { lock (SyncRoot) { if (!_itemFactories.ContainsKey(typeof(TType))) { Dictionary<string, PropertyInfo> properties = null; var itemProperties = new Func<Dictionary<string, PropertyInfo>>(() => properties ?? (properties = typeof(TType).GetProperties(BindingFlags.Public | BindingFlags.Instance).ToDictionary(p => p.Name, StringComparer.OrdinalIgnoreCase))); var itemFactory = new ItemFactory(itemProperties, itemCreator); _itemFactories[typeof(TType)] = itemFactory; } } } internal void RegisterTypeProperties([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type itemType, Func<object> itemCreator) { lock (SyncRoot) { if (!_itemFactories.ContainsKey(itemType)) { Dictionary<string, PropertyInfo> properties = null; var itemProperties = new Func<Dictionary<string, PropertyInfo>>(() => properties ?? (properties = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance).ToDictionary(p => p.Name, StringComparer.OrdinalIgnoreCase))); var itemFactory = new ItemFactory(itemProperties, itemCreator); _itemFactories[itemType] = itemFactory; } } } internal Dictionary<string, PropertyInfo> TryGetTypeProperties(Type itemType) { lock (SyncRoot) { if (_itemFactories.TryGetValue(itemType, out var itemFactory)) { return itemFactory.ItemProperties.Invoke(); } } if (itemType.IsAbstract()) return new Dictionary<string, PropertyInfo>(); if (itemType.IsGenericType() && itemType.GetGenericTypeDefinition() == typeof(Layout<>)) return new Dictionary<string, PropertyInfo>(); #pragma warning disable CS0618 // Type or member is obsolete return ResolveTypePropertiesLegacy(itemType); #pragma warning restore CS0618 // Type or member is obsolete } [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2067")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2070")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2072")] [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] private Dictionary<string, PropertyInfo> ResolveTypePropertiesLegacy(Type itemType) { InternalLogger.Debug("Object reflection needed to configure instance of type: {0}", itemType); Dictionary<string, PropertyInfo> properties = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance).ToDictionary(p => p.Name, StringComparer.OrdinalIgnoreCase); lock (SyncRoot) { _itemFactories[itemType] = new ItemFactory(() => properties, () => Activator.CreateInstance(itemType)); } return properties; } internal bool TryCreateInstance(Type itemType, out object instance) { Func<object> itemCreator = null; lock (SyncRoot) { if (_itemFactories.TryGetValue(itemType, out var itemFactory)) itemCreator = itemFactory.ItemCreator; } if (itemCreator is null) { #pragma warning disable CS0618 // Type or member is obsolete instance = ResolveCreateInstanceLegacy(itemType); #pragma warning restore CS0618 // Type or member is obsolete } else { instance = itemCreator.Invoke(); } return !(instance is null); } [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2067")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2070")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2072")] [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] private object ResolveCreateInstanceLegacy(Type itemType) { InternalLogger.Debug("Object reflection needed to create instance of type: {0}", itemType); Dictionary<string, PropertyInfo> properties = null; var itemProperties = new Func<Dictionary<string, PropertyInfo>>(() => properties ?? (properties = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance).ToDictionary(p => p.Name, StringComparer.OrdinalIgnoreCase))); var itemFactory = new ItemFactory(itemProperties, () => Activator.CreateInstance(itemType)); lock (SyncRoot) { _itemFactories[itemType] = itemFactory; } return itemFactory.ItemCreator.Invoke(); } /// <summary> /// Builds the default configuration item factory. /// </summary> /// <returns>Default factory.</returns> private static ConfigurationItemFactory BuildDefaultFactory() { var factory = new ConfigurationItemFactory(LogManager.LogFactory.ServiceRepository, null); lock (SyncRoot) { AssemblyExtensionTypes.RegisterTypes(factory); #pragma warning disable CS0618 // Type or member is obsolete factory.RegisterExternalItems(); #pragma warning restore CS0618 // Type or member is obsolete } return factory; } /// <summary> /// Registers items in using late-bound types, so that we don't need a reference to the dll. /// </summary> [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] private void RegisterExternalItems() { #if !NET35 && !NET40 _layouts.RegisterNamedType("microsoftconsolejsonlayout", "NLog.Extensions.Logging.MicrosoftConsoleJsonLayout, NLog.Extensions.Logging"); _layoutRenderers.RegisterNamedType("configsetting", "NLog.Extensions.Logging.ConfigSettingLayoutRenderer, NLog.Extensions.Logging"); _layoutRenderers.RegisterNamedType("microsoftconsolelayout", "NLog.Extensions.Logging.MicrosoftConsoleLayoutRenderer, NLog.Extensions.Logging"); #endif _layoutRenderers.RegisterNamedType("performancecounter", "NLog.LayoutRenderers.PerformanceCounterLayoutRenderer, NLog.PerformanceCounter"); _layoutRenderers.RegisterNamedType("registry", "NLog.LayoutRenderers.RegistryLayoutRenderer, NLog.WindowsRegistry"); _layoutRenderers.RegisterNamedType("windows-identity", "NLog.LayoutRenderers.WindowsIdentityLayoutRenderer, NLog.WindowsIdentity"); _layoutRenderers.RegisterNamedType("rtblink", "NLog.Windows.Forms.RichTextBoxLinkLayoutRenderer, NLog.Windows.Forms"); _layoutRenderers.RegisterNamedType("activity", "NLog.LayoutRenderers.ActivityTraceLayoutRenderer, NLog.DiagnosticSource"); _targets.RegisterNamedType("diagnosticlistener", "NLog.Targets.DiagnosticListenerTarget, NLog.DiagnosticSource"); _targets.RegisterNamedType("database", "NLog.Targets.DatabaseTarget, NLog.Database"); #if NETSTANDARD _targets.RegisterNamedType("eventlog", "NLog.Targets.EventLogTarget, NLog.WindowsEventLog"); #endif _targets.RegisterNamedType("impersonatingwrapper", "NLog.Targets.Wrappers.ImpersonatingTargetWrapper, NLog.WindowsIdentity"); _targets.RegisterNamedType("logreceiverservice", "NLog.Targets.LogReceiverWebServiceTarget, NLog.Wcf"); _targets.RegisterNamedType("outputdebugstring", "NLog.Targets.OutputDebugStringTarget, NLog.OutputDebugString"); _targets.RegisterNamedType("performancecounter", "NLog.Targets.PerformanceCounterTarget, NLog.PerformanceCounter"); _targets.RegisterNamedType("richtextbox", "NLog.Windows.Forms.RichTextBoxTarget, NLog.Windows.Forms"); _targets.RegisterNamedType("messagebox", "NLog.Windows.Forms.MessageBoxTarget, NLog.Windows.Forms"); _targets.RegisterNamedType("formcontrol", "NLog.Windows.Forms.FormControlTarget, NLog.Windows.Forms"); _targets.RegisterNamedType("toolstripitem", "NLog.Windows.Forms.ToolStripItemTarget, NLog.Windows.Forms"); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Filters { using NLog.Config; /// <summary> /// An abstract filter class. Provides a way to eliminate log messages /// based on properties other than logger name and log level. /// </summary> [NLogConfigurationItem] public abstract class Filter { /// <summary> /// Initializes a new instance of the <see cref="Filter" /> class. /// </summary> protected Filter() { Action = FilterResult.Neutral; } /// <summary> /// Gets or sets the action to be taken when filter matches. /// </summary> /// <docgen category='Filtering Options' order='10' /> public FilterResult Action { get; set; } /// <summary> /// Gets the result of evaluating filter against given log event. /// </summary> /// <param name="logEvent">The log event.</param> /// <returns>Filter result.</returns> internal FilterResult GetFilterResult(LogEventInfo logEvent) { return Check(logEvent); } /// <summary> /// Checks whether log event should be logged or not. /// </summary> /// <param name="logEvent">Log event.</param> /// <returns> /// <see cref="FilterResult.Ignore"/> - if the log event should be ignored<br/> /// <see cref="FilterResult.Neutral"/> - if the filter doesn't want to decide<br/> /// <see cref="FilterResult.Log"/> - if the log event should be logged<br/> /// .</returns> protected abstract FilterResult Check(LogEventInfo logEvent); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Text; using System.Xml; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Internal.Fakeables; using NLog.Layouts; using NLog.Targets; /// <summary> /// XML event description compatible with log4j, Chainsaw and NLogViewer. /// </summary> [LayoutRenderer("log4jxmlevent")] [MutableUnsafe] public class Log4JXmlEventLayoutRenderer : LayoutRenderer, IUsesStackTrace, IIncludeContext { private static readonly DateTime log4jDateBase = new DateTime(1970, 1, 1); private static readonly string dummyNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid(); private static readonly string dummyNamespaceRemover = " xmlns:log4j=\"" + dummyNamespace + "\""; private static readonly string dummyNLogNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid(); private static readonly string dummyNLogNamespaceRemover = " xmlns:nlog=\"" + dummyNLogNamespace + "\""; private readonly ScopeContextNestedStatesLayoutRenderer _scopeNestedLayoutRenderer = new ScopeContextNestedStatesLayoutRenderer(); /// <summary> /// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class. /// </summary> public Log4JXmlEventLayoutRenderer() : this(LogFactory.DefaultAppEnvironment) { } /// <summary> /// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class. /// </summary> internal Log4JXmlEventLayoutRenderer(IAppEnvironment appEnvironment) { #if NETSTANDARD1_3 AppInfo = "NetCore Application"; #else AppInfo = string.Format( CultureInfo.InvariantCulture, "{0}({1})", appEnvironment.AppDomainFriendlyName, appEnvironment.CurrentProcessId); #endif Parameters = new List<NLogViewerParameterInfo>(); try { _machineName = XmlHelper.XmlConvertToStringSafe(EnvironmentHelper.GetMachineName()); if (string.IsNullOrEmpty(_machineName)) { InternalLogger.Info("MachineName is not available."); } } catch (Exception exception) { InternalLogger.Error(exception, "Error getting machine name."); if (exception.MustBeRethrown()) { throw; } _machineName = string.Empty; } } /// <inheritdoc/> protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); _xmlWriterSettings = new XmlWriterSettings { Indent = IndentXml, ConformanceLevel = ConformanceLevel.Fragment, #if !NET35 NamespaceHandling = NamespaceHandling.OmitDuplicates, #endif IndentChars = " ", }; } /// <summary> /// Gets or sets a value indicating whether to include NLog-specific extensions to log4j schema. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeNLogData { get; set; } /// <summary> /// Gets or sets a value indicating whether the XML should use spaces for indentation. /// </summary> /// <docgen category='Layout Options' order='50' /> public bool IndentXml { get; set; } /// <summary> /// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain. /// </summary> /// <docgen category='Layout Options' order='10' /> public Layout AppInfo { get; set; } /// <summary> /// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeCallSite { get; set; } /// <summary> /// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeSourceInfo { get; set; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary. /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] public bool IncludeMdc { get => _includeMdc ?? false; set => _includeMdc = value; } private bool? _includeMdc; /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsLogicalContext"/> dictionary. /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] public bool IncludeMdlc { get => _includeMdlc ?? false; set => _includeMdlc = value; } private bool? _includeMdlc; /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsLogicalContext"/> stack. /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeNdc. Marked obsolete on NLog 5.0")] public bool IncludeNdlc { get => _includeNdlc ?? false; set => _includeNdlc = value; } private bool? _includeNdlc; /// <summary> /// Gets or sets whether to include log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeNdc { get => _includeNdc ?? false; set => _includeNdc = value; } private bool? _includeNdc; /// <summary> /// Gets or sets whether to include the contents of the <see cref="ScopeContext"/> properties-dictionary. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeScopeProperties { get => _includeScopeProperties ?? (_includeMdlc == true || _includeMdc == true); set => _includeScopeProperties = value; } private bool? _includeScopeProperties; /// <summary> /// Gets or sets whether to include log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeScopeNested { get => _includeScopeNested ?? (_includeNdlc == true || _includeNdc == true); set => _includeScopeNested = value; } private bool? _includeScopeNested; /// <summary> /// Gets or sets the stack separator for log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Layout Options' order='10' /> public string ScopeNestedSeparator { get => _scopeNestedLayoutRenderer.Separator; set => _scopeNestedLayoutRenderer.Separator = value; } /// <summary> /// Gets or sets the stack separator for log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by NdcItemSeparator. Marked obsolete on NLog 5.0")] public string NdlcItemSeparator { get => ScopeNestedSeparator; set => ScopeNestedSeparator = value; } /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeEventProperties. Marked obsolete on NLog 5.0")] public bool IncludeAllProperties { get => IncludeEventProperties; set => IncludeEventProperties = value; } /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeEventProperties { get; set; } = true; /// <summary> /// Gets or sets the stack separator for log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Layout Options' order='10' /> public string NdcItemSeparator { get => ScopeNestedSeparator; set => ScopeNestedSeparator = value; } /// <summary> /// Gets or sets the log4j:event logger-xml-attribute (Default ${logger}) /// </summary> /// <docgen category='Layout Options' order='50' /> public Layout LoggerName { get; set; } /// <summary> /// Gets or sets whether the log4j:throwable xml-element should be written as CDATA /// </summary> /// <docgen category='Layout Options' order='50' /> public bool WriteThrowableCData { get; set; } private readonly string _machineName; private XmlWriterSettings _xmlWriterSettings; /// <inheritdoc/> StackTraceUsage IUsesStackTrace.StackTraceUsage => (IncludeCallSite || IncludeSourceInfo) ? (StackTraceUsageUtils.GetStackTraceUsage(IncludeSourceInfo, 0, true) | StackTraceUsage.WithCallSiteClassName) : StackTraceUsage.None; internal IList<NLogViewerParameterInfo> Parameters { get; set; } /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { StringBuilder sb = new StringBuilder(); using (XmlWriter xtw = XmlWriter.Create(sb, _xmlWriterSettings)) { xtw.WriteStartElement("log4j", "event", dummyNamespace); bool includeNLogCallsite = (IncludeCallSite || IncludeSourceInfo) && logEvent.CallSiteInformation != null; if (includeNLogCallsite && IncludeNLogData) { xtw.WriteAttributeString("xmlns", "nlog", null, dummyNLogNamespace); } xtw.WriteAttributeSafeString("logger", LoggerName != null ? LoggerName.Render(logEvent) : logEvent.LoggerName); xtw.WriteAttributeString("level", logEvent.Level.Name.ToUpperInvariant()); xtw.WriteAttributeString("timestamp", Convert.ToString((long)(logEvent.TimeStamp.ToUniversalTime() - log4jDateBase).TotalMilliseconds, CultureInfo.InvariantCulture)); xtw.WriteAttributeString("thread", AsyncHelpers.GetManagedThreadId().ToString(CultureInfo.InvariantCulture)); xtw.WriteElementSafeString("log4j", "message", dummyNamespace, logEvent.FormattedMessage); if (logEvent.Exception != null) { if (WriteThrowableCData) { // CDATA correctly preserves newlines and indention, but not all viewers support this xtw.WriteStartElement("log4j", "throwable", dummyNamespace); xtw.WriteSafeCData(logEvent.Exception.ToString()); xtw.WriteEndElement(); } else { xtw.WriteElementSafeString("log4j", "throwable", dummyNamespace, logEvent.Exception.ToString()); } } AppendScopeContextNestedStates(xtw, logEvent); if (includeNLogCallsite) { AppendCallSite(logEvent, xtw); } xtw.WriteStartElement("log4j", "properties", dummyNamespace); AppendScopeContextProperties(xtw); if (IncludeEventProperties) { AppendDataProperties("log4j", dummyNamespace, xtw, logEvent); } AppendParameters(logEvent, xtw); var appInfo = XmlHelper.XmlConvertToStringSafe(AppInfo?.Render(logEvent) ?? string.Empty); AppendDataProperty(xtw, "log4japp", appInfo, dummyNamespace); AppendDataProperty(xtw, "log4jmachinename", _machineName, dummyNamespace); xtw.WriteEndElement(); // properties xtw.WriteEndElement(); // event xtw.Flush(); // get rid of 'nlog' and 'log4j' namespace declarations sb.Replace(dummyNamespaceRemover, string.Empty); if (includeNLogCallsite && IncludeNLogData) { sb.Replace(dummyNLogNamespaceRemover, string.Empty); } sb.CopyTo(builder); // StringBuilder.Replace is not good when reusing the StringBuilder } } private void AppendScopeContextProperties(XmlWriter xtw) { if (IncludeScopeProperties) { using (var scopeEnumerator = ScopeContext.GetAllPropertiesEnumerator()) { while (scopeEnumerator.MoveNext()) { var scopeProperty = scopeEnumerator.Current; string propertyKey = XmlHelper.XmlConvertToStringSafe(scopeProperty.Key); if (string.IsNullOrEmpty(propertyKey)) continue; string propertyValue = XmlHelper.XmlConvertToStringSafe(scopeProperty.Value); if (propertyValue is null) continue; AppendDataProperty(xtw, propertyKey, propertyValue, dummyNamespace); } } } } private void AppendScopeContextNestedStates(XmlWriter xtw, LogEventInfo logEvent) { if (IncludeScopeNested) { var nestedStates = _scopeNestedLayoutRenderer.Render(logEvent); //NDLC and NDC should be in the same element xtw.WriteElementSafeString("log4j", "NDC", dummyNamespace, nestedStates); } } private void AppendParameters(LogEventInfo logEvent, XmlWriter xtw) { for (int i = 0; i < Parameters?.Count; ++i) { var parameter = Parameters[i]; string parameterName = parameter?.Name; // property-setter has ensured safe xml-string if (string.IsNullOrEmpty(parameterName)) continue; var parameterValue = XmlHelper.XmlConvertToStringSafe(parameter.Layout?.Render(logEvent) ?? string.Empty); if (!parameter.IncludeEmptyValue && string.IsNullOrEmpty(parameterValue)) continue; AppendDataProperty(xtw, parameterName, parameterValue, dummyNamespace); } } private void AppendCallSite(LogEventInfo logEvent, XmlWriter xtw) { MethodBase methodBase = logEvent.CallSiteInformation.GetCallerStackFrameMethod(0); string callerClassName = logEvent.CallSiteInformation.GetCallerClassName(methodBase, true, true, true); string callerMethodName = logEvent.CallSiteInformation.GetCallerMethodName(methodBase, true, true, true); xtw.WriteStartElement("log4j", "locationInfo", dummyNamespace); if (!string.IsNullOrEmpty(callerClassName)) { xtw.WriteAttributeSafeString("class", callerClassName); } xtw.WriteAttributeSafeString("method", callerMethodName); if (IncludeSourceInfo) { xtw.WriteAttributeSafeString("file", logEvent.CallSiteInformation.GetCallerFilePath(0)); xtw.WriteAttributeString("line", logEvent.CallSiteInformation.GetCallerLineNumber(0).ToString(CultureInfo.InvariantCulture)); } xtw.WriteEndElement(); if (IncludeNLogData) { xtw.WriteElementSafeString("nlog", "eventSequenceNumber", dummyNLogNamespace, logEvent.SequenceID.ToString(CultureInfo.InvariantCulture)); xtw.WriteStartElement("nlog", "locationInfo", dummyNLogNamespace); var type = methodBase?.DeclaringType; if (type != null) { xtw.WriteAttributeSafeString("assembly", type.GetAssembly().FullName); } xtw.WriteEndElement(); xtw.WriteStartElement("nlog", "properties", dummyNLogNamespace); AppendDataProperties("nlog", dummyNLogNamespace, xtw, logEvent); xtw.WriteEndElement(); } } private void AppendDataProperties(string prefix, string propertiesNamespace, XmlWriter xtw, LogEventInfo logEvent) { if (logEvent.HasProperties) { foreach (var contextProperty in logEvent.Properties) { string propertyKey = XmlHelper.XmlConvertToStringSafe(contextProperty.Key); if (string.IsNullOrEmpty(propertyKey)) continue; string propertyValue = XmlHelper.XmlConvertToStringSafe(contextProperty.Value); if (propertyValue is null) continue; AppendDataProperty(xtw, propertyKey, propertyValue, propertiesNamespace, prefix); } } } private static void AppendDataProperty(XmlWriter xtw, string propertyKey, string propertyValue, string propertiesNamespace, string prefix = "log4j") { xtw.WriteStartElement(prefix, "data", propertiesNamespace); xtw.WriteAttributeString("name", propertyKey); xtw.WriteAttributeString("value", propertyValue); xtw.WriteEndElement(); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Text; using System.Collections.Generic; using NLog.Config; using NLog.Internal; using System.Globalization; /// <summary> /// Log event context data. /// </summary> [LayoutRenderer("all-event-properties")] [ThreadAgnostic] [MutableUnsafe] public class AllEventPropertiesLayoutRenderer : LayoutRenderer { private string _format; private string _beforeKey; private string _afterKey; private string _afterValue; /// <summary> /// Initializes a new instance of the <see cref="AllEventPropertiesLayoutRenderer"/> class. /// </summary> public AllEventPropertiesLayoutRenderer() { Separator = ", "; Format = "[key]=[value]"; Exclude = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Gets or sets string that will be used to separate key/value pairs. /// </summary> /// <docgen category='Layout Options' order='10' /> public string Separator { get; set; } /// <summary> /// Get or set if empty values should be included. /// /// A value is empty when null or in case of a string, null or empty string. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeEmptyValues { get; set; } /// <summary> /// Gets or sets whether to include the contents of the <see cref="ScopeContext"/> properties-dictionary. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeScopeProperties { get; set; } /// <summary> /// Gets or sets the keys to exclude from the output. If omitted, none are excluded. /// </summary> /// <docgen category='Layout Options' order='10' /> #if !NET35 public ISet<string> Exclude { get; set; } #else public HashSet<string> Exclude { get; set; } #endif /// <summary> /// Enables capture of ScopeContext-properties from active thread context /// </summary> [NLogConfigurationIgnoreProperty] public LayoutRenderer FixScopeContext => IncludeScopeProperties ? _fixScopeContext : null; private static readonly LayoutRenderer _fixScopeContext = new ScopeContextPropertyLayoutRenderer() { Item = string.Empty }; /// <summary> /// Gets or sets how key/value pairs will be formatted. /// </summary> /// <docgen category='Layout Options' order='10' /> public string Format { get => _format; set { if (string.IsNullOrEmpty(value) || value.IndexOf("[key]", StringComparison.Ordinal) < 0) throw new ArgumentException("Invalid format: [key] placeholder is missing."); if (value.IndexOf("[value]", StringComparison.Ordinal) < 0) throw new ArgumentException("Invalid format: [value] placeholder is missing."); _format = value; var formatSplit = _format.Split(new[] { "[key]", "[value]" }, StringSplitOptions.None); if (formatSplit.Length == 3) { _beforeKey = formatSplit[0]; _afterKey = formatSplit[1]; _afterValue = formatSplit[2]; } else { _beforeKey = null; _afterKey = null; _afterValue = null; } } } /// <summary> /// Gets or sets the culture used for rendering. /// </summary> /// <docgen category='Layout Options' order='100' /> public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (!logEvent.HasProperties && !IncludeScopeProperties) return; var formatProvider = GetFormatProvider(logEvent, Culture); bool checkForExclude = Exclude?.Count > 0; bool nonStandardFormat = _beforeKey is null || _afterKey is null || _afterValue is null; bool includeSeparator = false; if (logEvent.HasProperties) { IEnumerable<MessageTemplates.MessageTemplateParameter> propertiesList = logEvent.CreateOrUpdatePropertiesInternal(true); foreach (var property in propertiesList) { if (AppendProperty(builder, property.Name, property.Value, property.Format, formatProvider, includeSeparator, checkForExclude, nonStandardFormat)) { includeSeparator = true; } } } if (IncludeScopeProperties) { using (var scopeEnumerator = ScopeContext.GetAllPropertiesEnumerator()) { while (scopeEnumerator.MoveNext()) { var property = scopeEnumerator.Current; if (AppendProperty(builder, property.Key, property.Value, null, formatProvider, includeSeparator, checkForExclude, nonStandardFormat)) { includeSeparator = true; } } } } } private bool AppendProperty(StringBuilder builder, object propertyKey, object propertyValue, string propertyFormat, IFormatProvider formatProvider, bool includeSeparator, bool checkForExclude, bool nonStandardFormat) { if (!IncludeEmptyValues && IsEmptyPropertyValue(propertyValue)) return false; if (checkForExclude && Exclude.Contains(propertyKey as string ?? string.Empty)) return false; if (includeSeparator) { builder.Append(Separator); } if (nonStandardFormat) { var key = Convert.ToString(propertyKey, formatProvider); var value = Convert.ToString(propertyValue, formatProvider); var pair = Format.Replace("[key]", key) .Replace("[value]", value); builder.Append(pair); } else { builder.Append(_beforeKey); builder.AppendFormattedValue(propertyKey, null, formatProvider, ValueFormatter); builder.Append(_afterKey); builder.AppendFormattedValue(propertyValue, propertyFormat, formatProvider, ValueFormatter); builder.Append(_afterValue); } return true; } private static bool IsEmptyPropertyValue(object value) { if (value is string s) { return string.IsNullOrEmpty(s); } return value is null; } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Text; using NLog.Common; using NLog.Conditions; using NLog.Config; using NLog.Layouts; using NLog.Targets; /// <summary> /// Reflection helpers for accessing properties. /// </summary> internal static class PropertyHelper { private static readonly Dictionary<Type, Dictionary<string, PropertyInfo>> _parameterInfoCache = new Dictionary<Type, Dictionary<string, PropertyInfo>>(); private static readonly Dictionary<Type, Func<string, ConfigurationItemFactory, object>> _propertyConversionMapper = BuildPropertyConversionMapper(); #pragma warning disable S1144 // Unused private types or members should be removed. BUT they help CoreRT to provide config through reflection private static readonly RequiredParameterAttribute _requiredParameterAttribute = new RequiredParameterAttribute(); private static readonly ArrayParameterAttribute _arrayParameterAttribute = new ArrayParameterAttribute(null, string.Empty); private static readonly DefaultParameterAttribute _defaultParameterAttribute = new DefaultParameterAttribute(); private static readonly NLogConfigurationIgnorePropertyAttribute _ignorePropertyAttribute = new NLogConfigurationIgnorePropertyAttribute(); private static readonly NLogConfigurationItemAttribute _configPropertyAttribute = new NLogConfigurationItemAttribute(); private static readonly FlagsAttribute _flagsAttribute = new FlagsAttribute(); #pragma warning restore S1144 // Unused private types or members should be removed private static Dictionary<Type, Func<string, ConfigurationItemFactory, object>> BuildPropertyConversionMapper() { return new Dictionary<Type, Func<string, ConfigurationItemFactory, object>>() { { typeof(Layout), TryParseLayoutValue }, { typeof(SimpleLayout), TryParseLayoutValue }, { typeof(ConditionExpression), TryParseConditionValue }, { typeof(Encoding), TryParseEncodingValue }, { typeof(string), (stringvalue, factory) => stringvalue }, { typeof(int), (stringvalue, factory) => Convert.ChangeType(stringvalue.Trim(), TypeCode.Int32, CultureInfo.InvariantCulture) }, { typeof(bool), (stringvalue, factory) => Convert.ChangeType(stringvalue.Trim(), TypeCode.Boolean, CultureInfo.InvariantCulture) }, { typeof(CultureInfo), (stringvalue, factory) => TryParseCultureInfo(stringvalue) }, { typeof(Type), (stringvalue, factory) => PropertyTypeConverter.ConvertToType(stringvalue.Trim(), true) }, { typeof(LineEndingMode), (stringvalue, factory) => LineEndingMode.FromString(stringvalue.Trim()) }, { typeof(Uri), (stringvalue, factory) => new Uri(stringvalue.Trim()) } }; } internal static void SetPropertyFromString(object targetObject, PropertyInfo propInfo, string stringValue, ConfigurationItemFactory configurationItemFactory) { object propertyValue = null; try { var propertyType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType; if (ReferenceEquals(propertyType, propInfo.PropertyType) || !StringHelpers.IsNullOrWhiteSpace(stringValue)) { if (!TryNLogSpecificConversion(propertyType, stringValue, configurationItemFactory, out propertyValue)) { if (propInfo.IsDefined(_arrayParameterAttribute.GetType(), false)) { throw new NotSupportedException($"'{targetObject?.GetType()?.Name}' cannot assign property '{propInfo.Name}', because property of type array and not scalar value: '{stringValue}'."); } if (!(TryGetEnumValue(propertyType, stringValue, out propertyValue) || TryImplicitConversion(propertyType, stringValue, out propertyValue) || TryFlatListConversion(targetObject, propInfo, stringValue, configurationItemFactory, out propertyValue) || TryTypeConverterConversion(propertyType, stringValue, out propertyValue))) propertyValue = Convert.ChangeType(stringValue, propertyType, CultureInfo.InvariantCulture); } } } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } throw new NLogConfigurationException($"'{targetObject?.GetType()?.Name}' cannot assign property '{propInfo.Name}'='{stringValue}'. Error: {ex.Message}", ex); } SetPropertyValueForObject(targetObject, propertyValue, propInfo); } internal static void SetPropertyValueForObject(object targetObject, object value, PropertyInfo propInfo) { try { propInfo.SetValue(targetObject, value, null); } catch (TargetInvocationException ex) { throw new NLogConfigurationException($"'{targetObject?.GetType()?.Name}' cannot assign property '{propInfo.Name}'", ex.InnerException ?? ex); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } throw new NLogConfigurationException($"'{targetObject?.GetType()?.Name}' cannot assign property '{propInfo.Name}'. Error={ex.Message}", ex); } } /// <summary> /// Get property info /// </summary> /// <param name="configFactory">Configuration Reflection Helper</param> /// <param name="obj">object which could have property <paramref name="propertyName"/></param> /// <param name="propertyName">property name on <paramref name="obj"/></param> /// <param name="result">result when success.</param> /// <returns>success.</returns> internal static bool TryGetPropertyInfo(ConfigurationItemFactory configFactory, object obj, string propertyName, out PropertyInfo result) { var configProperties = TryLookupConfigItemProperties(configFactory, obj.GetType()); if (configProperties is null) { if (!string.IsNullOrEmpty(propertyName)) { #pragma warning disable CS0618 // Type or member is obsolete return TryGetPropertyInfo(obj, propertyName, out result); #pragma warning restore CS0618 // Type or member is obsolete } result = null; return false; } return configProperties.TryGetValue(propertyName, out result); } [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2075")] [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] private static bool TryGetPropertyInfo(object obj, string propertyName, out PropertyInfo result) { InternalLogger.Debug("Object reflection needed to configure instance of type: {0} (Lookup property={1})", obj.GetType(), propertyName); PropertyInfo propInfo = obj.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase); if (propInfo != null) { result = propInfo; return true; } result = null; return false; } internal static Type GetArrayItemType(PropertyInfo propInfo) { var arrayParameterAttribute = propInfo.GetFirstCustomAttribute<ArrayParameterAttribute>(); return arrayParameterAttribute?.ItemType; } internal static bool IsConfigurationItemType(ConfigurationItemFactory configFactory, Type type) { if (type is null || IsSimplePropertyType(type)) return false; if (typeof(LayoutRenderers.LayoutRenderer).IsAssignableFrom(type)) return true; if (typeof(Layout).IsAssignableFrom(type)) return true; if (typeof(Target).IsAssignableFrom(type)) return true; if (typeof(IEnumerable).IsAssignableFrom(type)) return true; return TryLookupConfigItemProperties(configFactory, type) != null; } internal static Dictionary<string, PropertyInfo> GetAllConfigItemProperties(ConfigurationItemFactory configFactory, Type type) { // NLog will ignore all properties marked with NLogConfigurationIgnorePropertyAttribute return TryLookupConfigItemProperties(configFactory, type) ?? new Dictionary<string, PropertyInfo>(); } private static Dictionary<string, PropertyInfo> TryLookupConfigItemProperties(ConfigurationItemFactory configFactory, Type type) { lock (_parameterInfoCache) { // NLog will ignore all properties marked with NLogConfigurationIgnorePropertyAttribute if (!_parameterInfoCache.TryGetValue(type, out var cache)) { if (TryCreatePropertyInfoDictionary(configFactory, type, out cache)) { _parameterInfoCache[type] = cache; } else { _parameterInfoCache[type] = null; // Not config item type } } return cache; } } internal static void CheckRequiredParameters(ConfigurationItemFactory configFactory, object o) { foreach (var configProp in GetAllConfigItemProperties(configFactory, o.GetType())) { var propInfo = configProp.Value; var propertyType = propInfo.PropertyType; if (propertyType != null && (propertyType.IsClass() || Nullable.GetUnderlyingType(propertyType) != null)) { if (propInfo.IsDefined(_requiredParameterAttribute.GetType(), false)) { object value = propInfo.GetValue(o, null); if (value is null) { throw new NLogConfigurationException( $"Required parameter '{propInfo.Name}' on '{o}' was not specified."); } } } } } internal static bool IsSimplePropertyType(Type type) { #if !NETSTANDARD1_3 if (Type.GetTypeCode(type) != TypeCode.Object) #else if (type.IsPrimitive() || type == typeof(string)) #endif return true; if (type == typeof(CultureInfo)) return true; if (type == typeof(Type)) return true; if (type == typeof(Encoding)) return true; if (type == typeof(LogLevel)) return true; return false; } [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2070")] private static bool TryImplicitConversion(Type resultType, string value, out object result) { try { if (IsSimplePropertyType(resultType)) { result = null; return false; } MethodInfo operatorImplicitMethod = resultType.GetMethod("op_Implicit", BindingFlags.Public | BindingFlags.Static, null, new Type[] { value.GetType() }, null); if (operatorImplicitMethod is null || !resultType.IsAssignableFrom(operatorImplicitMethod.ReturnType)) { result = null; return false; } result = operatorImplicitMethod.Invoke(null, new object[] { value }); return true; } catch (Exception ex) { InternalLogger.Warn(ex, "Implicit Conversion Failed of {0} to {1}", value, resultType); } result = null; return false; } private static bool TryNLogSpecificConversion(Type propertyType, string value, ConfigurationItemFactory configurationItemFactory, out object newValue) { if (_propertyConversionMapper.TryGetValue(propertyType, out var objectConverter)) { newValue = objectConverter.Invoke(value, configurationItemFactory); return true; } if (propertyType.IsGenericType() && propertyType.GetGenericTypeDefinition() == typeof(Layout<>)) { var simpleLayout = new SimpleLayout(value, configurationItemFactory); var concreteType = typeof(Layout<>).MakeGenericType(propertyType.GetGenericArguments()); newValue = Activator.CreateInstance(concreteType, BindingFlags.Instance | BindingFlags.Public, null, new object[] { simpleLayout }, null); return true; } newValue = null; return false; } private static bool TryGetEnumValue(Type resultType, string value, out object result) { if (!resultType.IsEnum()) { result = null; return false; } if (!StringHelpers.IsNullOrWhiteSpace(value)) { // Note: .NET Standard 2.1 added a public Enum.TryParse(Type) try { result = (Enum)Enum.Parse(resultType, value, true); return true; } catch (ArgumentException ex) { throw new ArgumentException($"Failed parsing Enum {resultType.Name} from value: {value}", ex); } } else { result = null; return false; } } private static object TryParseCultureInfo(string stringValue) { stringValue = stringValue?.Trim(); if (string.IsNullOrEmpty(stringValue)) return CultureInfo.InvariantCulture; else return new CultureInfo(stringValue); } private static object TryParseEncodingValue(string stringValue, ConfigurationItemFactory configurationItemFactory) { _ = configurationItemFactory; // Discard unreferenced parameter stringValue = stringValue.Trim(); if (string.Equals(stringValue, nameof(Encoding.UTF8), StringComparison.OrdinalIgnoreCase)) stringValue = Encoding.UTF8.WebName; // Support utf8 without hyphen (And not just Utf-8) return Encoding.GetEncoding(stringValue); } private static object TryParseLayoutValue(string stringValue, ConfigurationItemFactory configurationItemFactory) { return new SimpleLayout(stringValue, configurationItemFactory); } private static object TryParseConditionValue(string stringValue, ConfigurationItemFactory configurationItemFactory) { try { return ConditionParser.ParseExpression(stringValue, configurationItemFactory); } catch (ConditionParseException ex) { throw new NLogConfigurationException($"Cannot parse ConditionExpression '{stringValue}'. Error: {ex.Message}", ex); } } /// <summary> /// Try parse of string to (Generic) list, comma separated. /// </summary> /// <remarks> /// If there is a comma in the value, then (single) quote the value. For single quotes, use the backslash as escape /// </remarks> private static bool TryFlatListConversion(object obj, PropertyInfo propInfo, string valueRaw, ConfigurationItemFactory configurationItemFactory, out object newValue) { if (propInfo.PropertyType.IsGenericType() && TryCreateCollectionObject(obj, propInfo, valueRaw, out var newList, out var collectionAddMethod, out var propertyType)) { var values = valueRaw.SplitQuoted(',', '\'', '\\'); foreach (var value in values) { if (!(TryGetEnumValue(propertyType, value, out newValue) || TryNLogSpecificConversion(propertyType, value, configurationItemFactory, out newValue) || TryImplicitConversion(propertyType, value, out newValue) || TryTypeConverterConversion(propertyType, value, out newValue))) { newValue = Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture); } collectionAddMethod.Invoke(newList, new object[] { newValue }); } newValue = newList; return true; } newValue = null; return false; } private static bool TryCreateCollectionObject(object obj, PropertyInfo propInfo, string valueRaw, out object collectionObject, out MethodInfo collectionAddMethod, out Type collectionItemType) { var collectionType = propInfo.PropertyType; var typeDefinition = collectionType.GetGenericTypeDefinition(); #if !NET35 var isSet = typeDefinition == typeof(ISet<>) || typeDefinition == typeof(HashSet<>); #else var isSet = typeDefinition == typeof(HashSet<>); #endif //not checking "implements" interface as we are creating HashSet<T> or List<T> and also those checks are expensive if (isSet || typeDefinition == typeof(List<>) || typeDefinition == typeof(IList<>) || typeDefinition == typeof(IEnumerable<>)) //set or list/array etc { object hashsetComparer = isSet ? ExtractHashSetComparer(obj, propInfo) : null; //note: type.GenericTypeArguments is .NET 4.5+ collectionItemType = collectionType.GetGenericArguments()[0]; collectionObject = isSet ? CreateCollectionHashSetInstance(collectionItemType, hashsetComparer, out collectionAddMethod) : CreateCollectionListInstance(collectionItemType, out collectionAddMethod); //no support for array if (collectionObject is null) { throw new NLogConfigurationException($"Cannot create instance of {collectionType.ToString()} for value {valueRaw}"); } if (collectionAddMethod is null) { throw new NLogConfigurationException($"Add method on type {collectionType.ToString()} for value {valueRaw} not found"); } return true; } collectionObject = null; collectionAddMethod = null; collectionItemType = null; return false; } private static object CreateCollectionHashSetInstance(Type collectionItemType, object hashSetComparer, out MethodInfo collectionAddMethod) { var concreteType = typeof(HashSet<>).MakeGenericType(collectionItemType); collectionAddMethod = typeof(HashSet<>).MakeGenericType(collectionItemType).GetMethod("Add", BindingFlags.Instance | BindingFlags.Public); if (hashSetComparer != null) { var constructor = concreteType.GetConstructor(new[] { hashSetComparer.GetType() }); if (constructor != null) { return constructor.Invoke(new[] { hashSetComparer }); } } return Activator.CreateInstance(concreteType); } private static object CreateCollectionListInstance(Type collectionItemType, out MethodInfo collectionAddMethod) { var concreteType = typeof(List<>).MakeGenericType(collectionItemType); collectionAddMethod = typeof(List<>).MakeGenericType(collectionItemType).GetMethod("Add", BindingFlags.Instance | BindingFlags.Public); return Activator.CreateInstance(concreteType); } /// <summary> /// Attempt to reuse the HashSet.Comparer from the original HashSet-object (Ex. StringComparer.OrdinalIgnoreCase) /// </summary> private static object ExtractHashSetComparer(object obj, PropertyInfo propInfo) { var exitingValue = propInfo.IsValidPublicProperty() ? propInfo.GetPropertyValue(obj) : null; if (exitingValue != null) { // Found original HashSet-object. See if we can extract the Comparer if (exitingValue.GetType().GetGenericTypeDefinition() == typeof(HashSet<>)) { var comparerPropInfo = typeof(HashSet<>).MakeGenericType(exitingValue.GetType().GetGenericArguments()[0]).GetProperty("Comparer", BindingFlags.Instance | BindingFlags.Public); if (comparerPropInfo.IsValidPublicProperty()) { return comparerPropInfo.GetPropertyValue(exitingValue); } } } return null; } [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2026")] [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2067")] [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2072")] internal static bool TryTypeConverterConversion(Type type, string value, out object newValue) { if (typeof(IConvertible).IsAssignableFrom(type) || type.IsAssignableFrom(typeof(string))) { newValue = null; return false; } try { InternalLogger.Debug("Object reflection needed for creating external type: {0} from string-value: {1}", type, value); var converter = TypeDescriptor.GetConverter(type); if (converter.CanConvertFrom(typeof(string))) { newValue = converter.ConvertFromInvariantString(value); return true; } newValue = null; return false; } catch (MissingMethodException ex) { InternalLogger.Error(ex, "Error in lookup of TypeDescriptor for type={0} to convert value '{1}'", type, value); newValue = null; return false; } } private static bool TryCreatePropertyInfoDictionary(ConfigurationItemFactory configFactory, Type objectType, out Dictionary<string, PropertyInfo> result) { result = null; try { if (!objectType.IsDefined(_configPropertyAttribute.GetType(), true)) { return false; } var properties = configFactory.TryGetTypeProperties(objectType); if (properties is null) { return false; } if (properties.Count == 0) { result = properties; return true; } if (!HasCustomConfigurationProperties(objectType, properties)) { result = properties; return true; } bool checkDefaultValue = typeof(LayoutRenderers.LayoutRenderer).IsAssignableFrom(objectType); result = new Dictionary<string, PropertyInfo>(properties.Count + 4, StringComparer.OrdinalIgnoreCase); foreach (var property in properties) { var propInfo = property.Value; if (!IncludeConfigurationPropertyInfo(objectType, propInfo, checkDefaultValue, out var overridePropertyName)) continue; result[propInfo.Name] = propInfo; if (overridePropertyName is null) continue; result[overridePropertyName] = propInfo; } } catch (Exception ex) { InternalLogger.Debug(ex, "Type reflection not possible for type {0}. Maybe because of .NET Native.", objectType); } return result != null; } private static bool HasCustomConfigurationProperties(Type objectType, Dictionary<string, PropertyInfo> objectProperties) { bool checkDefaultValue = typeof(LayoutRenderers.LayoutRenderer).IsAssignableFrom(objectType); foreach (var property in objectProperties) { if (IncludeConfigurationPropertyInfo(objectType, property.Value, checkDefaultValue, out var overridePropertyName) && overridePropertyName is null) continue; return true; } return false; } private static bool IncludeConfigurationPropertyInfo(Type objectType, PropertyInfo propInfo, bool checkDefaultValue, out string overridePropertyName) { overridePropertyName = null; try { if (propInfo?.PropertyType is null) return false; if (checkDefaultValue && propInfo.IsDefined(_defaultParameterAttribute.GetType(), false)) { overridePropertyName = string.Empty; return true; } if (IsSimplePropertyType(propInfo.PropertyType)) return true; if (typeof(LayoutRenderers.LayoutRenderer).IsAssignableFrom(propInfo.PropertyType)) return true; if (typeof(Layout).IsAssignableFrom(propInfo.PropertyType)) return true; if (typeof(Target).IsAssignableFrom(propInfo.PropertyType)) return true; if (propInfo.IsDefined(_ignorePropertyAttribute.GetType(), false)) return false; if (typeof(IEnumerable).IsAssignableFrom(propInfo.PropertyType)) { var arrayParameterAttribute = propInfo.GetFirstCustomAttribute<ArrayParameterAttribute>(); if (arrayParameterAttribute != null) { overridePropertyName = arrayParameterAttribute.ElementName; return true; } } return true; } catch (Exception ex) { InternalLogger.Debug(ex, "Type reflection not possible for property {0} on type {1}. Maybe because of .NET Native.", propInfo.Name, objectType); return false; } } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.ComponentModel; using System.Text; using NLog.Config; using NLog.Internal.Fakeables; namespace NLog.LayoutRenderers { /// <summary> /// Used to render the application domain name. /// </summary> [LayoutRenderer("appdomain")] [AppDomainFixedOutput] [ThreadAgnostic] public class AppDomainLayoutRenderer : LayoutRenderer { private const string ShortFormat = "{0:00}"; private const string LongFormat = "{0:0000}:{1}"; private const string LongFormatCode = "Long"; private const string ShortFormatCode = "Short"; private readonly IAppEnvironment _currentAppEnvironment; /// <summary> /// Create a new renderer /// </summary> public AppDomainLayoutRenderer() : this(LogFactory.DefaultAppEnvironment) { } /// <summary> /// Create a new renderer /// </summary> internal AppDomainLayoutRenderer(IAppEnvironment appEnvironment) { _currentAppEnvironment = appEnvironment; } /// <summary> /// Format string. Possible values: "Short", "Long" or custom like {0} {1}. Default "Long" /// The first parameter is the AppDomain.Id, the second the second the AppDomain.FriendlyName /// This string is used in <see cref="string.Format(string,object[])"/> /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultParameter] public string Format { get; set; } = LongFormatCode; /// <inheritdoc/> protected override void InitializeLayoutRenderer() { _assemblyName = null; base.InitializeLayoutRenderer(); } /// <inheritdoc/> protected override void CloseLayoutRenderer() { _assemblyName = null; base.CloseLayoutRenderer(); } private string _assemblyName; /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (_assemblyName is null) { var formattingString = GetFormattingString(Format); _assemblyName = string.Format(formattingString, _currentAppEnvironment.AppDomainId, _currentAppEnvironment.AppDomainFriendlyName); } builder.Append(_assemblyName); } private static string GetFormattingString(string format) { string formattingString; if (format.Equals(LongFormatCode, StringComparison.OrdinalIgnoreCase)) { formattingString = LongFormat; } else if (format.Equals(ShortFormatCode, StringComparison.OrdinalIgnoreCase)) { formattingString = ShortFormat; } else { //custom format string formattingString = format; } return formattingString; } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NET35 using System.Collections.Generic; using NLog.Common; using NLog.Targets.Wrappers; using Xunit; namespace NLog.UnitTests.Targets.Wrappers { public class ConcurrentRequestQueueTests : NLogTestBase { [Theory] [InlineData(AsyncTargetWrapperOverflowAction.Block)] [InlineData(AsyncTargetWrapperOverflowAction.Discard)] [InlineData(AsyncTargetWrapperOverflowAction.Grow)] public void DequeueBatch_WithNonEmptyList_ReturnsValidCount(AsyncTargetWrapperOverflowAction overflowAction) { // Stage ConcurrentRequestQueue requestQueue = new ConcurrentRequestQueue(2, overflowAction); requestQueue.Enqueue(new AsyncLogEventInfo()); requestQueue.Enqueue(new AsyncLogEventInfo()); Assert.Equal(2, requestQueue.Count); // Act var batch = new List<AsyncLogEventInfo>(); requestQueue.DequeueBatch(1, batch); // Dequeue into empty-list Assert.Equal(1, requestQueue.Count); requestQueue.DequeueBatch(1, batch); // Dequeue into non-empty-list // Assert Assert.Equal(0, requestQueue.Count); Assert.Equal(2, batch.Count); } [Fact] public void RaiseEventLogEventQueueGrow_OnLogItems() { const int RequestsLimit = 2; const int EventsCount = 5; const int ExpectedCountOfGrovingTimes = 2; const int ExpectedFinalSize = 8; int grovingItemsCount = 0; ConcurrentRequestQueue requestQueue = new ConcurrentRequestQueue(RequestsLimit, AsyncTargetWrapperOverflowAction.Grow); requestQueue.LogEventQueueGrow += (o, e) => { grovingItemsCount++; }; for (int i = 0; i < EventsCount; i++) { requestQueue.Enqueue(new AsyncLogEventInfo()); } Assert.Equal(ExpectedCountOfGrovingTimes, grovingItemsCount); Assert.Equal(ExpectedFinalSize, requestQueue.RequestLimit); } [Fact] public void RaiseEventLogEventDropped_OnLogItems() { const int RequestsLimit = 2; const int EventsCount = 5; int discardedItemsCount = 0; int ExpectedDiscardedItemsCount = EventsCount - RequestsLimit; ConcurrentRequestQueue requestQueue = new ConcurrentRequestQueue(RequestsLimit, AsyncTargetWrapperOverflowAction.Discard); requestQueue.LogEventDropped+= (o, e) => { discardedItemsCount++; }; for (int i = 0; i < EventsCount; i++) { requestQueue.Enqueue(new AsyncLogEventInfo()); } Assert.Equal(ExpectedDiscardedItemsCount, discardedItemsCount); } } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 namespace NLog.Targets { using System.Text.RegularExpressions; using NLog.Conditions; using NLog.Config; using NLog.Internal; /// <summary> /// Highlighting rule for Win32 colorful console. /// </summary> [NLogConfigurationItem] public class ConsoleWordHighlightingRule { private readonly RegexHelper _regexHelper = new RegexHelper(); /// <summary> /// Initializes a new instance of the <see cref="ConsoleWordHighlightingRule" /> class. /// </summary> public ConsoleWordHighlightingRule() { BackgroundColor = ConsoleOutputColor.NoChange; ForegroundColor = ConsoleOutputColor.NoChange; } /// <summary> /// Initializes a new instance of the <see cref="ConsoleWordHighlightingRule" /> class. /// </summary> /// <param name="text">The text to be matched..</param> /// <param name="foregroundColor">Color of the foreground.</param> /// <param name="backgroundColor">Color of the background.</param> public ConsoleWordHighlightingRule(string text, ConsoleOutputColor foregroundColor, ConsoleOutputColor backgroundColor) { _regexHelper.SearchText = text; ForegroundColor = foregroundColor; BackgroundColor = backgroundColor; } /// <summary> /// Gets or sets the regular expression to be matched. You must specify either <c>text</c> or <c>regex</c>. /// </summary> /// <docgen category='Highlighting Rules' order='10' /> public string Regex { get => _regexHelper.RegexPattern; set => _regexHelper.RegexPattern = value; } /// <summary> /// Gets or sets the condition that must be met before scanning the row for highlight of words /// </summary> /// <docgen category='Highlighting Rules' order='10' /> public ConditionExpression Condition { get; set; } /// <summary> /// Compile the <see cref="Regex"/>? This can improve the performance, but at the costs of more memory usage. If <c>false</c>, the Regex Cache is used. /// </summary> /// <docgen category='Highlighting Rules' order='10' /> public bool CompileRegex { get => _regexHelper.CompileRegex; set => _regexHelper.CompileRegex = value; } /// <summary> /// Gets or sets the text to be matched. You must specify either <c>text</c> or <c>regex</c>. /// </summary> /// <docgen category='Highlighting Rules' order='10' /> public string Text { get => _regexHelper.SearchText; set => _regexHelper.SearchText = value; } /// <summary> /// Gets or sets a value indicating whether to match whole words only. /// </summary> /// <docgen category='Highlighting Rules' order='10' /> public bool WholeWords { get => _regexHelper.WholeWords; set => _regexHelper.WholeWords = value; } /// <summary> /// Gets or sets a value indicating whether to ignore case when comparing texts. /// </summary> /// <docgen category='Highlighting Rules' order='10' /> public bool IgnoreCase { get => _regexHelper.IgnoreCase; set => _regexHelper.IgnoreCase = value; } /// <summary> /// Gets or sets the foreground color. /// </summary> /// <docgen category='Highlighting Rules' order='10' /> public ConsoleOutputColor ForegroundColor { get; set; } /// <summary> /// Gets or sets the background color. /// </summary> /// <docgen category='Highlighting Rules' order='10' /> public ConsoleOutputColor BackgroundColor { get; set; } /// <summary> /// Gets the compiled regular expression that matches either Text or Regex property. Only used when <see cref="CompileRegex"/> is <c>true</c>. /// </summary> public Regex CompiledRegex => _regexHelper.Regex; internal MatchCollection Matches(LogEventInfo logEvent, string message) { if (Condition != null && false.Equals(Condition.Evaluate(logEvent))) { return null; } return _regexHelper.Matches(message); } } } #endif<file_sep>using System; using NLog; using NLog.Targets; class Example { static void Main(string[] args) { try { Console.WriteLine("Setting up the target..."); MailTarget target = new MailTarget(); target.SmtpServer = "192.168.0.15"; target.From = "<EMAIL>"; target.To = "<EMAIL>"; target.Subject = "sample subject"; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Console.WriteLine("Sending..."); Logger logger = LogManager.GetLogger("Example"); Console.WriteLine("Sent."); logger.Debug("log message"); } catch (Exception ex) { Console.WriteLine("EX: {0}", ex); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !MONO namespace NLog.UnitTests.Config { using System; using System.IO; using System.Threading; using NLog.Config; using Xunit; public class ReloadTests : NLogTestBase { public ReloadTests() { if (LogManager.LogFactory != null) { LogManager.LogFactory.ResetLoggerCache(); } } [Theory] [InlineData(true)] [InlineData(false)] public void TestNoAutoReload(bool useExplicitFileLoading) { string config1 = @"<nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string config2 = @"<nlog> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempDir); string configFilePath = Path.Combine(tempDir, "noreload.nlog"); WriteConfigFile(configFilePath, config1); try { SetLogManagerConfiguration(useExplicitFileLoading, configFilePath); Assert.False(((XmlLoggingConfiguration)LogManager.Configuration).AutoReload); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(configFilePath, config2, assertDidReload: false); logger.Debug("bbb"); // Assert that config1 is still loaded. AssertDebugLastMessage("debug", "bbb"); } finally { if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } private static void SetLogManagerConfiguration(bool useExplicitFileLoading, string configFilePath) { if (useExplicitFileLoading) { LogManager.Configuration = new XmlLoggingConfiguration(configFilePath); } else { #pragma warning disable CS0618 // Type or member is obsolete LogManager.LogFactory.SetCandidateConfigFilePaths(new string[] { configFilePath }); #pragma warning restore CS0618 // Type or member is obsolete } } [Theory] [InlineData(true)] [InlineData(false)] public void TestAutoReloadOnFileChange(bool useExplicitFileLoading) { #if NETSTANDARD || MONO if (IsLinux()) { Console.WriteLine("[SKIP] ReloadTests.TestAutoReloadOnFileChange because we are running in Travis"); return; } #endif string config1 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string config2 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string badConfig = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='(${message})' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>"; string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempDir); string configFilePath = Path.Combine(tempDir, "reload.nlog"); WriteConfigFile(configFilePath, config1); try { SetLogManagerConfiguration(useExplicitFileLoading, configFilePath); Assert.True(((XmlLoggingConfiguration)LogManager.Configuration).AutoReload); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(configFilePath, badConfig, assertDidReload: false); logger.Debug("bbb"); // Assert that config1 is still loaded. AssertDebugLastMessage("debug", "bbb"); ChangeAndReloadConfigFile(configFilePath, config2); logger.Debug("ccc"); // Assert that config2 is loaded. AssertDebugLastMessage("debug", "[ccc]"); } finally { if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Theory] [InlineData(true)] [InlineData(false)] public void TestAutoReloadOnFileMove(bool useExplicitFileLoading) { #if NETSTANDARD || MONO if (IsLinux()) { Console.WriteLine("[SKIP] ReloadTests.TestAutoReloadOnFileMove because we are running in Travis"); return; } #endif string config1 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string config2 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempDir); string configFilePath = Path.Combine(tempDir, "reload.nlog"); WriteConfigFile(configFilePath, config1); string otherFilePath = Path.Combine(tempDir, "other.nlog"); try { SetLogManagerConfiguration(useExplicitFileLoading, configFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); using (var reloadWaiter = new ConfigurationReloadWaiter()) { File.Move(configFilePath, otherFilePath); reloadWaiter.WaitForReload(); } logger.Debug("bbb"); // Assert that config1 is still loaded. AssertDebugLastMessage("debug", "bbb"); WriteConfigFile(otherFilePath, config2); using (var reloadWaiter = new ConfigurationReloadWaiter()) { File.Move(otherFilePath, configFilePath); reloadWaiter.WaitForReload(); Assert.True(reloadWaiter.DidReload); } logger.Debug("ccc"); // Assert that config2 is loaded. AssertDebugLastMessage("debug", "[ccc]"); } finally { if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Theory] [InlineData(true)] [InlineData(false)] public void TestAutoReloadOnFileCopy(bool useExplicitFileLoading) { #if NETSTANDARD || MONO if (IsLinux()) { Console.WriteLine("[SKIP] ReloadTests.TestAutoReloadOnFileCopy because we are running in Travis"); return; } #endif string config1 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string config2 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string configFilePath = Path.Combine(tempPath, "reload.nlog"); WriteConfigFile(configFilePath, config1); string otherFilePath = Path.Combine(tempPath, "other.nlog"); try { SetLogManagerConfiguration(useExplicitFileLoading, configFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); using (var reloadWaiter = new ConfigurationReloadWaiter()) { File.Delete(configFilePath); reloadWaiter.WaitForReload(); } logger.Debug("bbb"); // Assert that config1 is still loaded. AssertDebugLastMessage("debug", "bbb"); WriteConfigFile(otherFilePath, config2); using (var reloadWaiter = new ConfigurationReloadWaiter()) { File.Copy(otherFilePath, configFilePath); File.Delete(otherFilePath); reloadWaiter.WaitForReload(); Assert.True(reloadWaiter.DidReload); } logger.Debug("ccc"); // Assert that config2 is loaded. AssertDebugLastMessage("debug", "[ccc]"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Theory] [InlineData(true)] [InlineData(false)] public void TestIncludedConfigNoReload(bool useExplicitFileLoading) { #if NETSTANDARD || MONO if (IsLinux()) { Console.WriteLine("[SKIP] ReloadTests.TestIncludedConfigNoReload because we are running in Travis"); return; } #endif string mainConfig1 = @"<nlog> <include file='included.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string mainConfig2 = @"<nlog> <include file='included.nlog' /> <rules><logger name='*' minlevel='Info' writeTo='debug' /></rules> </nlog>"; string includedConfig1 = @"<nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> </nlog>"; string includedConfig2 = @"<nlog> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> </nlog>"; string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempDir); string mainConfigFilePath = Path.Combine(tempDir, "main.nlog"); WriteConfigFile(mainConfigFilePath, mainConfig1); string includedConfigFilePath = Path.Combine(tempDir, "included.nlog"); WriteConfigFile(includedConfigFilePath, includedConfig1); try { SetLogManagerConfiguration(useExplicitFileLoading, mainConfigFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2, assertDidReload: false); logger.Debug("bbb"); // Assert that mainConfig1 is still loaded. AssertDebugLastMessage("debug", "bbb"); WriteConfigFile(mainConfigFilePath, mainConfig1); ChangeAndReloadConfigFile(includedConfigFilePath, includedConfig2, assertDidReload: false); logger.Debug("ccc"); // Assert that includedConfig1 is still loaded. AssertDebugLastMessage("debug", "ccc"); } finally { if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Theory] [InlineData(true)] [InlineData(false)] public void TestIncludedConfigReload(bool useExplicitFileLoading) { #if NETSTANDARD || MONO if (IsLinux()) { Console.WriteLine("[SKIP] ReloadTests.TestIncludedConfigNoReload because we are running in Travis"); return; } #endif string mainConfig1 = @"<nlog> <include file='included.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string mainConfig2 = @"<nlog> <include file='included.nlog' /> <rules><logger name='*' minlevel='Info' writeTo='debug' /></rules> </nlog>"; string includedConfig1 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> </nlog>"; string includedConfig2 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> </nlog>"; string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempDir); string mainConfigFilePath = Path.Combine(tempDir, "main.nlog"); WriteConfigFile(mainConfigFilePath, mainConfig1); string includedConfigFilePath = Path.Combine(tempDir, "included.nlog"); WriteConfigFile(includedConfigFilePath, includedConfig1); try { SetLogManagerConfiguration(useExplicitFileLoading, mainConfigFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2, assertDidReload: false); logger.Debug("bbb"); // Assert that mainConfig1 is still loaded. AssertDebugLastMessage("debug", "bbb"); WriteConfigFile(mainConfigFilePath, mainConfig1); ChangeAndReloadConfigFile(includedConfigFilePath, includedConfig2); logger.Debug("ccc"); // Assert that includedConfig2 is loaded. AssertDebugLastMessage("debug", "[ccc]"); } finally { if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Theory] [InlineData(true)] [InlineData(false)] public void TestMainConfigReload(bool useExplicitFileLoading) { #if NETSTANDARD || MONO if (IsLinux()) { Console.WriteLine("[SKIP] ReloadTests.TestMainConfigReload because we are running in Travis"); return; } #endif string mainConfig1 = @"<nlog autoReload='true'> <include file='included.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string mainConfig2 = @"<nlog autoReload='true'> <include file='included2.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string included1Config = @"<nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> </nlog>"; string included2Config1 = @"<nlog> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> </nlog>"; string included2Config2 = @"<nlog> <targets><target name='debug' type='Debug' layout='(${message})' /></targets> </nlog>"; string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempDir); string mainConfigFilePath = Path.Combine(tempDir, "main.nlog"); WriteConfigFile(mainConfigFilePath, mainConfig1); string included1ConfigFilePath = Path.Combine(tempDir, "included.nlog"); WriteConfigFile(included1ConfigFilePath, included1Config); string included2ConfigFilePath = Path.Combine(tempDir, "included2.nlog"); WriteConfigFile(included2ConfigFilePath, included2Config1); try { SetLogManagerConfiguration(useExplicitFileLoading, mainConfigFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2); logger.Debug("bbb"); // Assert that mainConfig2 is loaded (which refers to included2.nlog). AssertDebugLastMessage("debug", "[bbb]"); ChangeAndReloadConfigFile(included2ConfigFilePath, included2Config2); logger.Debug("ccc"); // Assert that included2Config2 is loaded. AssertDebugLastMessage("debug", "(ccc)"); } finally { if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Theory] [InlineData(true)] [InlineData(false)] public void TestMainConfigReloadIncludedConfigNoReload(bool useExplicitFileLoading) { #if NETSTANDARD || MONO if (IsLinux()) { Console.WriteLine("[SKIP] ReloadTests.TestMainConfigReload because we are running in Travis"); return; } #endif string mainConfig1 = @"<nlog autoReload='true'> <include file='included.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string mainConfig2 = @"<nlog autoReload='true'> <include file='included2.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string included1Config = @"<nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> </nlog>"; string included2Config1 = @"<nlog autoReload='false'> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> </nlog>"; string included2Config2 = @"<nlog autoReload='false'> <targets><target name='debug' type='Debug' layout='(${message})' /></targets> </nlog>"; string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempDir); string mainConfigFilePath = Path.Combine(tempDir, "main.nlog"); WriteConfigFile(mainConfigFilePath, mainConfig1); string included1ConfigFilePath = Path.Combine(tempDir, "included.nlog"); WriteConfigFile(included1ConfigFilePath, included1Config); string included2ConfigFilePath = Path.Combine(tempDir, "included2.nlog"); WriteConfigFile(included2ConfigFilePath, included2Config1); try { SetLogManagerConfiguration(useExplicitFileLoading, mainConfigFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2); logger.Debug("bbb"); // Assert that mainConfig2 is loaded (which refers to included2.nlog). AssertDebugLastMessage("debug", "[bbb]"); ChangeAndReloadConfigFile(included2ConfigFilePath, included2Config2, assertDidReload: false); logger.Debug("ccc"); // Assert that included2Config1 is still loaded. AssertDebugLastMessage("debug", "[ccc]"); } finally { if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] [Obsolete("Replaced by ConfigurationChanged. Marked obsolete on NLog 5.2")] public void TestKeepVariablesOnReload() { string config = @"<nlog autoReload='true' keepVariablesOnReload='true'> <variable name='var1' value='' /> <variable name='var2' value='keep_value' /> </nlog>"; var configLoader = new LoggingConfigurationWatchableFileLoader(LogFactory.DefaultAppEnvironment); var logFactory = new LogFactory(configLoader); var configuration = XmlLoggingConfigurationMock.CreateFromXml(logFactory, config); logFactory.Configuration = configuration; logFactory.Configuration.Variables["var1"] = "new_value"; logFactory.Configuration.Variables["var3"] = "new_value3"; configLoader.ReloadConfigOnTimer(configuration); var nullEvent = LogEventInfo.CreateNullEvent(); Assert.Equal("new_value", logFactory.Configuration.Variables["var1"].Render(nullEvent)); Assert.Equal("keep_value", logFactory.Configuration.Variables["var2"].Render(nullEvent)); Assert.Equal("new_value3", logFactory.Configuration.Variables["var3"].Render(nullEvent)); logFactory.Setup().ReloadConfiguration(); Assert.Equal("new_value", logFactory.Configuration.Variables["var1"].Render(nullEvent)); Assert.Equal("keep_value", logFactory.Configuration.Variables["var2"].Render(nullEvent)); Assert.Equal("new_value3", logFactory.Configuration.Variables["var3"].Render(nullEvent)); } [Fact] public void TestKeepVariablesOnReloadAllowUpdate() { string config1 = @"<nlog autoReload='true' keepVariablesOnReload='true'> <variable name='var1' value='' /> <variable name='var2' value='old_value2' /> <targets><target name='mem' type='memory' layout='${var:var2}' /></targets> <rules><logger name='*' writeTo='mem' /></rules> </nlog>"; string config2 = @"<nlog autoReload='true' keepVariablesOnReload='true'> <variable name='var1' value='' /> <variable name='var2' value='new_value2' /> <targets><target name='mem' type='memory' layout='${var:var2}' /></targets> <rules><logger name='*' writeTo='mem' /></rules> </nlog>"; var logFactory = new LogFactory(); var xmlConfig = XmlLoggingConfigurationMock.CreateFromXml(logFactory, config1); logFactory.Configuration = xmlConfig; // Act logFactory.Configuration.Variables.Remove("var1"); logFactory.Configuration.Variables.Add("var3", "new_value3"); xmlConfig.ConfigXml = config2; logFactory.Configuration = xmlConfig.Reload(); // Assert var nullEvent = LogEventInfo.CreateNullEvent(); Assert.Equal("", logFactory.Configuration.Variables["var1"].Render(nullEvent)); Assert.Equal("new_value2", logFactory.Configuration.Variables["var2"].Render(nullEvent)); Assert.Equal("new_value3", logFactory.Configuration.Variables["var3"].Render(nullEvent)); } [Fact] [Obsolete("Replaced by ConfigurationChanged. Marked obsolete on NLog 5.2")] public void TestResetVariablesOnReload() { string config = @"<nlog autoReload='true' keepVariablesOnReload='false'> <variable name='var1' value='' /> <variable name='var2' value='keep_value' /> </nlog>"; var configLoader = new LoggingConfigurationWatchableFileLoader(LogFactory.DefaultAppEnvironment); var logFactory = new LogFactory(configLoader); var configuration = XmlLoggingConfigurationMock.CreateFromXml(logFactory, config); logFactory.Configuration = configuration; logFactory.Configuration.Variables["var1"] = "new_value"; logFactory.Configuration.Variables["var3"] = "new_value3"; configLoader.ReloadConfigOnTimer(configuration); LogEventInfo nullEvent = LogEventInfo.CreateNullEvent(); Assert.Equal("", logFactory.Configuration.Variables["var1"].Render(nullEvent)); Assert.Equal("keep_value", logFactory.Configuration.Variables["var2"].Render(nullEvent)); logFactory.Configuration = configuration.Reload(); Assert.Equal("", logFactory.Configuration.Variables["var1"].Render(nullEvent)); Assert.Equal("keep_value", logFactory.Configuration.Variables["var2"].Render(nullEvent)); } [Fact] public void KeepVariablesOnReloadWithStaticMode() { // Arrange string config = @"<nlog autoReload='true'> <variable name='maxArchiveDays' value='7' /> <targets> <target name='logfile' type='file' fileName='test.log' maxArchiveDays='${maxArchiveDays}' /> </targets> <rules> <logger name='*' minLevel='Debug' writeTo='logfile' /> </rules> </nlog>"; var logFactory = new LogFactory(); logFactory.Configuration = XmlLoggingConfigurationMock.CreateFromXml(logFactory, config); var fileTarget = logFactory.Configuration.AllTargets[0] as NLog.Targets.FileTarget; var beforeValue = fileTarget.MaxArchiveDays; // Act logFactory.Configuration.Variables["MaxArchiveDays"] = "42"; logFactory.Configuration = logFactory.Configuration.Reload(); fileTarget = logFactory.Configuration.AllTargets[0] as NLog.Targets.FileTarget; var afterValue = fileTarget.MaxArchiveDays; // Assert Assert.Equal(7, beforeValue); Assert.Equal(42, afterValue); } [Fact] [Obsolete("Replaced by ConfigurationChanged. Marked obsolete on NLog 5.2")] public void ReloadConfigOnTimer_When_No_Exception_Raises_ConfigurationReloadedEvent() { var called = false; LoggingConfigurationReloadedEventArgs arguments = null; object calledBy = null; var configLoader = new LoggingConfigurationWatchableFileLoader(LogFactory.DefaultAppEnvironment); var logFactory = new LogFactory(configLoader); var loggingConfiguration = XmlLoggingConfigurationMock.CreateFromXml(logFactory, "<nlog></nlog>"); logFactory.Configuration = loggingConfiguration; logFactory.ConfigurationReloaded += (sender, args) => { called = true; calledBy = sender; arguments = args; }; configLoader.ReloadConfigOnTimer(loggingConfiguration); Assert.True(called); Assert.Same(calledBy, logFactory); Assert.True(arguments.Succeeded); } [Fact] [Obsolete("Replaced by LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] public void TestReloadingInvalidConfiguration() { var validXmlConfig = @"<nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"; var invalidXmlConfig = @"<nlog autoReload='true' internalLogLevel='debug' internalLogLevel='error'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> </nlog>"; string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempDir); try { using (new NoThrowNLogExceptions()) { var nlogConfigFile = Path.Combine(tempDir, "NLog.config"); LogFactory logFactory = new LogFactory(); logFactory.SetCandidateConfigFilePaths(new[] { nlogConfigFile }); var config = logFactory.Configuration; Assert.Null(config); WriteConfigFile(nlogConfigFile, invalidXmlConfig); config = logFactory.Configuration; Assert.NotNull(config); Assert.Empty(config.AllTargets); // Failed to load Assert.Single(config.FileNamesToWatch); // But file-watcher is active WriteConfigFile(nlogConfigFile, validXmlConfig); config = logFactory.Configuration.Reload(); Assert.Single(config.AllTargets); } } finally { if (Directory.Exists(tempDir)) { Directory.Delete(tempDir, true); } } } [Fact] [Obsolete("Replaced by LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] public void TestThrowExceptionWhenInvalidXml() { var invalidXmlConfig = @"<nlog throwExceptions='true' internalLogLevel='debug' internalLogLevel='error'> </nlog>"; string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempDir); try { using (new NoThrowNLogExceptions()) { var nlogConfigFile = Path.Combine(tempDir, "NLog.config"); WriteConfigFile(nlogConfigFile, invalidXmlConfig); LogFactory logFactory = new LogFactory(); logFactory.SetCandidateConfigFilePaths(new[] { nlogConfigFile }); Assert.Throws<NLogConfigurationException>(() => logFactory.GetLogger("Hello")); } } finally { if (Directory.Exists(tempDir)) { Directory.Delete(tempDir, true); } } } private static void WriteConfigFile(string configFilePath, string config) { using (StreamWriter writer = File.CreateText(configFilePath)) writer.Write(config); } private static void ChangeAndReloadConfigFile(string configFilePath, string config, bool assertDidReload = true) { using (var reloadWaiter = new ConfigurationReloadWaiter()) { WriteConfigFile(configFilePath, config); reloadWaiter.WaitForReload(); if (assertDidReload) Assert.True(reloadWaiter.DidReload, $"Config '{configFilePath}' did not reload."); } } private class ConfigurationReloadWaiter : IDisposable { private ManualResetEvent counterEvent = new ManualResetEvent(false); public ConfigurationReloadWaiter() { LogManager.ConfigurationChanged += SignalCounterEvent(counterEvent); } public bool DidReload => counterEvent.WaitOne(0); public void Dispose() { LogManager.ConfigurationChanged -= SignalCounterEvent(counterEvent); } public void WaitForReload() { counterEvent.WaitOne(3000); } private static EventHandler<LoggingConfigurationChangedEventArgs> SignalCounterEvent(ManualResetEvent counterEvent) { return (sender, e) => { counterEvent.Set(); }; } } } /// <summary> /// Xml config with reload without file-reads for performance /// </summary> public class XmlLoggingConfigurationMock : XmlLoggingConfiguration { public string ConfigXml { get; set; } private XmlLoggingConfigurationMock(LogFactory logFactory, string configXml) :base(logFactory) { ConfigXml = configXml; } public override LoggingConfiguration Reload() { var newConfig = new XmlLoggingConfigurationMock(LogFactory, ConfigXml); newConfig.PrepareForReload(this); newConfig.LoadFromXmlContent(ConfigXml, null); return newConfig; } public static XmlLoggingConfigurationMock CreateFromXml(LogFactory logFactory, string configXml) { var newConfig = new XmlLoggingConfigurationMock(logFactory, configXml); newConfig.LoadFromXmlContent(configXml, null); return newConfig; } } } #endif <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Internal; using NLog.Layouts; using Xunit; namespace NLog.UnitTests.Internal { public class UrlHelperTests { [Theory] [InlineData("", true, "")] [InlineData("", false, "")] [InlineData(null, false, "")] [InlineData(null, true, "")] [InlineData("ab cd", true,"ab+cd")] [InlineData("ab cd", false, "ab%20cd")] [InlineData("one&two =three", true, "one%26two+%3dthree")] [InlineData("one&two =three", false, "one%26two%20%3dthree")] [InlineData(" €;✈ Ĕ ßß ßß ", true, "+%u20ac%3b%u2708+%u0114++%df%df+%df%df+")] //current implementation, not sure if correct [InlineData(" €;✈ Ĕ ßß ßß ", false, "%20%u20ac%3b%u2708%20%u0114%20%20%df%df%20%df%df%20")] //current implementation, not sure if correct [InlineData(".()*-_!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", true, ".()*-_!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")] [InlineData(".()*-_!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", false, ".()*-_!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")] [InlineData("《∠∠⊙⌒∈∽》`````", true, "%u300a%u2220%u2220%u2299%u2312%u2208%u223d%u300b%60%60%60%60%60")] //current implementation, not sure if correct public void UrlEncodeTest(string input, bool spaceAsPlus, string result) { SimpleLayout l = spaceAsPlus ? "${url-encode:escapeDataNLogLegacy=true:${message}}" : "${url-encode:escapeDataNLogLegacy=true:spaceAsPlus=false:${message}}"; string urlencoded = l.Render(LogEventInfo.Create(LogLevel.Debug, "logger", input)); Assert.Equal(result, urlencoded); } [Theory] [InlineData("", true, "")] [InlineData("", false, "")] [InlineData("ab cd", true, "ab+cd")] [InlineData("ab cd", false, "ab%20cd")] [InlineData("one&two =three", true, "one%26two+%3dthree")] [InlineData("one&two =three", false, "one%26two%20%3dthree")] [InlineData(" €;✈ Ĕ ßß ßß ", true, "+%e2%82%ac%3b%e2%9c%88+%c4%94++%c3%9f%c3%9f+%c3%9f%c3%9f+")] [InlineData(" €;✈ Ĕ ßß ßß ", false, "%20%e2%82%ac%3b%e2%9c%88%20%c4%94%20%20%c3%9f%c3%9f%20%c3%9f%c3%9f%20")] [InlineData(".()*-_!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", true, ".()*-_!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")] [InlineData(".()*-_!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", false, ".()*-_!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")] [InlineData(@"http://foo:bar@host:123/path?query=key_value+map_value#fragment", true, @"http%3a%2f%2ffoo%3abar%40host%3a123%2fpath%3fquery%3dkey_value%2bmap_value%23fragment")] [InlineData(@"http://foo:bar@host:123/path?query=key_value+map_value#fragment", false, @"http%3a%2f%2ffoo%3abar%40host%3a123%2fpath%3fquery%3dkey_value%2bmap_value%23fragment")] public void EscapeDataEncodeTestRfc2396(string input, bool spaceAsPlus, string result) { System.Text.StringBuilder builder = new System.Text.StringBuilder(input.Length + 20); UrlHelper.EscapeEncodingOptions encodingOptions = UrlHelper.EscapeEncodingOptions.LowerCaseHex | UrlHelper.EscapeEncodingOptions.LegacyRfc2396 | UrlHelper.EscapeEncodingOptions.UriString; if (spaceAsPlus) encodingOptions |= UrlHelper.EscapeEncodingOptions.SpaceAsPlus; UrlHelper.EscapeDataEncode(input, builder, encodingOptions); Assert.Equal(result, builder.ToString()); Assert.Equal(input.Replace('+', ' '), DecodeUrlString(builder.ToString())); } [Theory] [InlineData("", true, "")] [InlineData("", false, "")] [InlineData("ab cd", true, "ab+cd")] [InlineData("ab cd", false, "ab%20cd")] [InlineData(" €;✈ Ĕ ßß ßß ", true, "+%E2%82%AC;%E2%9C%88+%C4%94++%C3%9F%C3%9F+%C3%9F%C3%9F+")] [InlineData(" €;✈ Ĕ ßß ßß ", false, "%20%E2%82%AC;%E2%9C%88%20%C4%94%20%20%C3%9F%C3%9F%20%C3%9F%C3%9F%20")] [InlineData(@"http://foo:bar@host:123/path?query=key_value+map_value#fragment", true, @"http://foo:bar@host:123/path?query=key%5Fvalue+map%5Fvalue#fragment")] [InlineData(@"http://foo:bar@host:123/path?query=key_value+map_value#fragment", false, @"http://foo:bar@host:123/path?query=key%5Fvalue+map%5Fvalue#fragment")] public void EscapeDataEncodeTestRfc3986(string input, bool spaceAsPlus, string result) { System.Text.StringBuilder builder = new System.Text.StringBuilder(input.Length + 20); UrlHelper.EscapeEncodingOptions encodingOptions = UrlHelper.EscapeEncodingOptions.None; if (spaceAsPlus) encodingOptions |= UrlHelper.EscapeEncodingOptions.SpaceAsPlus; UrlHelper.EscapeDataEncode(input, builder, encodingOptions); Assert.Equal(result, builder.ToString()); Assert.Equal(input.Replace('+', ' '), DecodeUrlString(builder.ToString())); } private static string DecodeUrlString(string url) { string newUrl; while ((newUrl = System.Uri.UnescapeDataString(url)) != url) url = newUrl; return newUrl.Replace('+', ' '); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 namespace NLog.Targets { using System; using System.Collections.Generic; using System.IO; using System.Text; /// <summary> /// Color formatting for <see cref="ColoredConsoleTarget"/> using <see cref="Console.ForegroundColor"/> /// and <see cref="Console.BackgroundColor"/> /// </summary> internal class ColoredConsoleSystemPrinter : IColoredConsolePrinter { public TextWriter AcquireTextWriter(TextWriter consoleStream, StringBuilder reusableBuilder) { return consoleStream; } public void ReleaseTextWriter(TextWriter consoleWriter, TextWriter consoleStream, ConsoleColor? oldForegroundColor, ConsoleColor? oldBackgroundColor, bool flush) { ResetDefaultColors(consoleWriter, oldForegroundColor, oldBackgroundColor); if (flush) consoleWriter.Flush(); } public ConsoleColor? ChangeForegroundColor(TextWriter consoleWriter, ConsoleColor? foregroundColor, ConsoleColor? oldForegroundColor = null) { var previousForegroundColor = oldForegroundColor ?? Console.ForegroundColor; if (foregroundColor.HasValue && previousForegroundColor != foregroundColor.Value) { Console.ForegroundColor = foregroundColor.Value; } return previousForegroundColor; } public ConsoleColor? ChangeBackgroundColor(TextWriter consoleWriter, ConsoleColor? backgroundColor, ConsoleColor? oldBackgroundColor = null) { var previousBackgroundColor = oldBackgroundColor ?? Console.BackgroundColor; if (backgroundColor.HasValue && previousBackgroundColor != backgroundColor.Value) { Console.BackgroundColor = backgroundColor.Value; } return previousBackgroundColor; } public void ResetDefaultColors(TextWriter consoleWriter, ConsoleColor? foregroundColor, ConsoleColor? backgroundColor) { if (foregroundColor.HasValue) Console.ForegroundColor = foregroundColor.Value; if (backgroundColor.HasValue) Console.BackgroundColor = backgroundColor.Value; } public void WriteSubString(TextWriter consoleWriter, string text, int index, int endIndex) { consoleWriter.Write(text.Substring(index, endIndex - index)); } public void WriteChar(TextWriter consoleWriter, char text) { consoleWriter.Write(text); } public void WriteLine(TextWriter consoleWriter, string text) { consoleWriter.WriteLine(text); // Cannot be threadsafe, since colors are incrementally updated } public IList<ConsoleRowHighlightingRule> DefaultConsoleRowHighlightingRules { get; } = new List<ConsoleRowHighlightingRule>() { new ConsoleRowHighlightingRule("level == LogLevel.Fatal", ConsoleOutputColor.Red, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Error", ConsoleOutputColor.Yellow, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Warn", ConsoleOutputColor.Magenta, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Info", ConsoleOutputColor.White, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Debug", ConsoleOutputColor.Gray, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Trace", ConsoleOutputColor.DarkGray, ConsoleOutputColor.NoChange), }; } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; using NLog.Layouts; /// <summary> /// Retries in case of write error. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/RetryingWrapper-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/RetryingWrapper-target">Documentation on NLog Wiki</seealso> /// <example> /// <p>This example causes each write attempt to be repeated 3 times, /// sleeping 1 second between attempts if first one fails.</p> /// <p> /// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/RetryingWrapper/NLog.config" /> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/RetryingWrapper/Simple/Example.cs" /> /// </example> [Target("RetryingWrapper", IsWrapper = true)] public class RetryingTargetWrapper : WrapperTargetBase { /// <summary> /// Initializes a new instance of the <see cref="RetryingTargetWrapper" /> class. /// </summary> public RetryingTargetWrapper() : this(null, 3, 100) { } /// <summary> /// Initializes a new instance of the <see cref="RetryingTargetWrapper" /> class. /// </summary> /// <param name="name">Name of the target.</param> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="retryCount">The retry count.</param> /// <param name="retryDelayMilliseconds">The retry delay milliseconds.</param> public RetryingTargetWrapper(string name, Target wrappedTarget, int retryCount, int retryDelayMilliseconds) : this(wrappedTarget, retryCount, retryDelayMilliseconds) { Name = name ?? Name; } /// <summary> /// Initializes a new instance of the <see cref="RetryingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="retryCount">The retry count.</param> /// <param name="retryDelayMilliseconds">The retry delay milliseconds.</param> public RetryingTargetWrapper(Target wrappedTarget, int retryCount, int retryDelayMilliseconds) { Name = string.IsNullOrEmpty(wrappedTarget?.Name) ? Name : (wrappedTarget.Name + "_wrapped"); WrappedTarget = wrappedTarget; RetryCount = retryCount; RetryDelayMilliseconds = retryDelayMilliseconds; } /// <summary> /// Gets or sets the number of retries that should be attempted on the wrapped target in case of a failure. /// </summary> /// <docgen category='Retrying Options' order='10' /> public Layout<int> RetryCount { get; set; } /// <summary> /// Gets or sets the time to wait between retries in milliseconds. /// </summary> /// <docgen category='Retrying Options' order='10' /> public Layout<int> RetryDelayMilliseconds { get; set; } /// <summary> /// Gets or sets whether to enable batching, and only apply single delay when a whole batch fails /// </summary> /// <docgen category='Retrying Options' order='10' /> public bool EnableBatchWrite { get; set; } = true; /// <summary> /// Special SyncObject to allow closing down Target while busy retrying /// </summary> private readonly object _retrySyncObject = new object(); /// <summary> /// Writes the specified log event to the wrapped target, retrying and pausing in case of an error. /// </summary> /// <param name="logEvents">The log event.</param> protected override void WriteAsyncThreadSafe(IList<AsyncLogEventInfo> logEvents) { if (logEvents.Count == 1) { WriteAsyncThreadSafe(logEvents[0]); } else if (EnableBatchWrite) { int initialSleep = 1; Func<int, bool> sleepBeforeRetry = (retryNumber) => retryNumber > 1 || Interlocked.Exchange(ref initialSleep, 0) == 1; for (int i = 0; i < logEvents.Count; ++i) { logEvents[i] = WrapWithRetry(logEvents[i], sleepBeforeRetry); } lock (_retrySyncObject) { WrappedTarget.WriteAsyncLogEvents(logEvents); } } else { lock (_retrySyncObject) { for (int i = 0; i < logEvents.Count; ++i) { WriteAsyncThreadSafe(logEvents[i]); } } } } /// <summary> /// Writes the specified log event to the wrapped target in a thread-safe manner. /// </summary> /// <param name="logEvent">The log event.</param> protected override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { lock (_retrySyncObject) { // Uses RetrySyncObject instead of Target.SyncRoot to allow closing target while doing sleep and retry. Write(logEvent); } } /// <summary> /// Writes the specified log event to the wrapped target, retrying and pausing in case of an error. /// </summary> /// <param name="logEvent">The log event.</param> protected override void Write(AsyncLogEventInfo logEvent) { WrappedTarget.WriteAsyncLogEvent(WrapWithRetry(logEvent, (retryNumber) => true)); } private AsyncLogEventInfo WrapWithRetry(AsyncLogEventInfo logEvent, Func<int, bool> sleepBeforeRetry) { AsyncContinuation continuation = null; int counter = 0; continuation = ex => { if (ex is null) { logEvent.Continuation(null); return; } int retryNumber = Interlocked.Increment(ref counter); var retryCount = RetryCount.RenderValue(logEvent.LogEvent); var retryDelayMilliseconds = RetryDelayMilliseconds.RenderValue(logEvent.LogEvent); InternalLogger.Warn(ex, "{0}: Error while writing to '{1}'. Try {2}/{3}", this, WrappedTarget, retryNumber, retryCount); // exceeded retry count if (retryNumber >= retryCount) { InternalLogger.Warn("{0}: Too many retries. Aborting.", this); logEvent.Continuation(ex); return; } // sleep and try again (Check every 100 ms if target have been closed) if (sleepBeforeRetry(retryNumber)) { for (int i = 0; i < retryDelayMilliseconds;) { int retryDelay = Math.Min(100, retryDelayMilliseconds - i); AsyncHelpers.WaitForDelay(TimeSpan.FromMilliseconds(retryDelay)); i += retryDelay; if (!IsInitialized) { InternalLogger.Warn("{0}): Target closed. Aborting.", this); logEvent.Continuation(ex); return; } } } WrappedTarget.WriteAsyncLogEvent(logEvent.LogEvent.WithContinuation(continuation)); }; return logEvent.LogEvent.WithContinuation(continuation); } } } <file_sep>How to build your fork in the cloud --- Steps to set up CI for your own fork. **AppVeyor**: 1. Login with your Github account to https://ci.appveyor.com 2. Choose "projects" 3. Select your fork and press "+" button 4. Done. All config is in appveyor.yml already <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.IO; using NLog.Config; using NLog.Targets; using Xunit; using System.Threading.Tasks; public class ConsoleTargetTests : NLogTestBase { [Fact] public void ConsoleOutWriteLineTest() { ConsoleOutTest(false); } [Fact] public void ConsoleOutWriteBufferTest() { ConsoleOutTest(true); } private static void ConsoleOutTest(bool writeBuffer) { var target = new ConsoleTarget() { Header = "-- header --", Layout = "${logger} ${message}", Footer = "-- footer --", WriteBuffer = writeBuffer, }; var consoleOutWriter = new StringWriter(); TextWriter oldConsoleOutWriter = Console.Out; Console.SetOut(consoleOutWriter); try { var exceptions = new List<Exception>(); target.Initialize(null); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message1").WithContinuation(exceptions.Add)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message2").WithContinuation(exceptions.Add)); target.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "Logger1", "message3").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "message4").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "message5").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "message6").WithContinuation(exceptions.Add)); Assert.Equal(6, exceptions.Count); target.Flush((ex) => { }); target.Close(); } finally { Console.SetOut(oldConsoleOutWriter); } var actual = consoleOutWriter.ToString(); Assert.True(actual.IndexOf("-- header --") != -1); Assert.True(actual.IndexOf("Logger1 message1") != -1); Assert.True(actual.IndexOf("Logger1 message2") != -1); Assert.True(actual.IndexOf("Logger1 message3") != -1); Assert.True(actual.IndexOf("Logger2 message4") != -1); Assert.True(actual.IndexOf("Logger2 message5") != -1); Assert.True(actual.IndexOf("Logger1 message6") != -1); Assert.True(actual.IndexOf("-- footer --") != -1); } [Fact] public void ConsoleErrorTest() { var target = new ConsoleTarget() { Header = "-- header --", Layout = "${logger} ${message}", Footer = "-- footer --", StdErr = true, }; var consoleErrorWriter = new StringWriter(); TextWriter oldConsoleErrorWriter = Console.Error; Console.SetError(consoleErrorWriter); try { var exceptions = new List<Exception>(); target.Initialize(null); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message1").WithContinuation(exceptions.Add)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message2").WithContinuation(exceptions.Add)); target.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "Logger1", "message3").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "message4").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "message5").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "message6").WithContinuation(exceptions.Add)); Assert.Equal(6, exceptions.Count); target.Flush((ex) => { }); target.Close(); } finally { Console.SetError(oldConsoleErrorWriter); } string expectedResult = string.Format("-- header --{0}Logger1 message1{0}Logger1 message2{0}Logger1 message3{0}Logger2 message4{0}Logger2 message5{0}Logger1 message6{0}-- footer --{0}", Environment.NewLine); Assert.Equal(expectedResult, consoleErrorWriter.ToString()); } [Fact] public void SetupBuilder_WriteToConsole() { var logFactory = new LogFactory().Setup().LoadConfiguration(c => { c.ForLogger().FilterMinLevel(LogLevel.Error).WriteToConsole("${message}", stderr: true); }).LogFactory; var consoleErrorWriter = new StringWriter(); TextWriter oldConsoleErrorWriter = Console.Error; Console.SetError(consoleErrorWriter); try { logFactory.GetCurrentClassLogger().Error("Abort"); logFactory.GetCurrentClassLogger().Info("Continue"); } finally { Console.SetError(oldConsoleErrorWriter); } Assert.Equal($"Abort{System.Environment.NewLine}", consoleErrorWriter.ToString()); } #if !MONO [Fact] public void ConsoleEncodingTest() { var consoleOutputEncoding = Console.OutputEncoding; var target = new ConsoleTarget() { Header = "-- header --", Layout = "${logger} ${message}", Footer = "-- footer --", Encoding = System.Text.Encoding.UTF8 }; Assert.Equal(System.Text.Encoding.UTF8, target.Encoding); var consoleOutWriter = new StringWriter(); TextWriter oldConsoleOutWriter = Console.Out; Console.SetOut(consoleOutWriter); try { var exceptions = new List<Exception>(); target.Initialize(null); // Not really testing whether Console.OutputEncoding works, but just that it is configured without breaking ConsoleTarget Assert.Equal(System.Text.Encoding.UTF8, Console.OutputEncoding); Assert.Equal(System.Text.Encoding.UTF8, target.Encoding); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message1").WithContinuation(exceptions.Add)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message2").WithContinuation(exceptions.Add)); Assert.Equal(2, exceptions.Count); target.Encoding = consoleOutputEncoding; Assert.Equal(consoleOutputEncoding, Console.OutputEncoding); target.Close(); } finally { Console.OutputEncoding = consoleOutputEncoding; Console.SetOut(oldConsoleOutWriter); } string expectedResult = string.Format("-- header --{0}Logger1 message1{0}Logger1 message2{0}-- footer --{0}", Environment.NewLine); Assert.Equal(expectedResult, consoleOutWriter.ToString()); } #endif #if !MONO [Fact] public void ConsoleRaceCondtionIgnoreTest() { var configXml = @" <nlog throwExceptions='true'> <targets> <target name='console' type='console' layout='${message}' /> <target name='consoleError' type='console' layout='${message}' error='true' /> </targets> <rules> <logger name='*' minlevel='Trace' writeTo='console,consoleError' /> </rules> </nlog>"; var success = ConsoleRaceCondtionIgnoreInnerTest(configXml); Assert.True(success); } internal static bool ConsoleRaceCondtionIgnoreInnerTest(string configXml) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(configXml); // Console.Out.Writeline / Console.Error.Writeline could throw 'IndexOutOfRangeException', which is a bug. // See https://stackoverflow.com/questions/33915790/console-out-and-console-error-race-condition-error-in-a-windows-service-written // and https://connect.microsoft.com/VisualStudio/feedback/details/2057284/console-out-probable-i-o-race-condition-issue-in-multi-threaded-windows-service // // Full error: // Error during session close: System.IndexOutOfRangeException: Probable I/ O race condition detected while copying memory. // The I/ O package is not thread safe by default. In multi-threaded applications, // a stream must be accessed in a thread-safe way, such as a thread - safe wrapper returned by TextReader's or // TextWriter's Synchronized methods.This also applies to classes like StreamWriter and StreamReader. var oldOut = Console.Out; var oldError = Console.Error; try { Console.SetOut(StreamWriter.Null); Console.SetError(StreamWriter.Null); LogManager.ThrowExceptions = true; var logger = LogManager.GetCurrentClassLogger(); Parallel.For(0, 10, new ParallelOptions() { MaxDegreeOfParallelism = 10 }, (_) => { for (int i = 0; i < 100; i++) { logger.Trace("test message to the out and error stream"); } }); return true; } finally { Console.SetOut(oldOut); Console.SetError(oldError); } } #endif } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NET35 namespace NLog.Targets { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using NLog.Common; using NLog.Internal; using NLog.Targets.Wrappers; /// <summary> /// Abstract Target with async Task support /// </summary> /// <remarks> /// <a href="https://github.com/NLog/NLog/wiki/How-to-write-a-custom-async-target">See NLog Wiki</a> /// </remarks> /// <example><code> /// [Target("MyFirst")] /// public sealed class MyFirstTarget : AsyncTaskTarget /// { /// public MyFirstTarget() /// { /// this.Host = "localhost"; /// } /// /// [RequiredParameter] /// public Layout Host { get; set; } /// /// protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token) /// { /// string logMessage = this.RenderLogEvent(this.Layout, logEvent); /// string hostName = this.RenderLogEvent(this.Host, logEvent); /// return SendTheMessageToRemoteHost(hostName, logMessage); /// } /// /// private async Task SendTheMessageToRemoteHost(string hostName, string message) /// { /// // To be implemented /// } /// } /// </code></example> /// <seealso href="https://github.com/NLog/NLog/wiki/How-to-write-a-custom-async-target">Documentation on NLog Wiki</seealso> public abstract class AsyncTaskTarget : TargetWithContext { private readonly Timer _taskTimeoutTimer; private CancellationTokenSource _cancelTokenSource; AsyncRequestQueueBase _requestQueue; private readonly Action _taskCancelledTokenReInit; private readonly Action<Task, object> _taskCompletion; private Task _previousTask; private readonly Timer _lazyWriterTimer; private readonly ReusableAsyncLogEventList _reusableAsyncLogEventList = new ReusableAsyncLogEventList(200); private Tuple<List<LogEventInfo>, List<AsyncContinuation>> _reusableLogEvents; private AsyncHelpersTask? _flushEventsInQueueDelegate; private bool _missingServiceTypes; /// <summary> /// How many milliseconds to delay the actual write operation to optimize for batching /// </summary> /// <docgen category='Buffering Options' order='100' /> public int TaskDelayMilliseconds { get; set; } = 1; /// <summary> /// How many seconds a Task is allowed to run before it is cancelled. /// </summary> /// <docgen category='Buffering Options' order='100' /> public int TaskTimeoutSeconds { get; set; } = 150; /// <summary> /// How many attempts to retry the same Task, before it is aborted /// </summary> /// <docgen category='Buffering Options' order='100' /> public int RetryCount { get; set; } /// <summary> /// How many milliseconds to wait before next retry (will double with each retry) /// </summary> /// <docgen category='Buffering Options' order='100' /> public int RetryDelayMilliseconds { get; set; } = 500; /// <summary> /// Gets or sets whether to use the locking queue, instead of a lock-free concurrent queue /// The locking queue is less concurrent when many logger threads, but reduces memory allocation /// </summary> /// <docgen category='Buffering Options' order='100' /> public bool ForceLockingQueue { get => _forceLockingQueue ?? false; set => _forceLockingQueue = value; } private bool? _forceLockingQueue; /// <summary> /// Gets or sets the action to be taken when the lazy writer thread request queue count /// exceeds the set limit. /// </summary> /// <docgen category='Buffering Options' order='100' /> public AsyncTargetWrapperOverflowAction OverflowAction { get => _requestQueue.OnOverflow; set => _requestQueue.OnOverflow = value; } /// <summary> /// Gets or sets the limit on the number of requests in the lazy writer thread request queue. /// </summary> /// <docgen category='Buffering Options' order='100' /> public int QueueLimit { get => _requestQueue.RequestLimit; set => _requestQueue.RequestLimit = value; } /// <summary> /// Gets or sets the number of log events that should be processed in a batch /// by the lazy writer thread. /// </summary> /// <docgen category='Buffering Options' order='100' /> public int BatchSize { get; set; } = 1; /// <summary> /// Task Scheduler used for processing async Tasks /// </summary> protected virtual TaskScheduler TaskScheduler => TaskScheduler.Default; /// <summary> /// Constructor /// </summary> protected AsyncTaskTarget() { _taskCompletion = TaskCompletion; _taskCancelledTokenReInit = TaskCancelledTokenReInit; _taskTimeoutTimer = new Timer(TaskTimeout, null, Timeout.Infinite, Timeout.Infinite); #if NETSTANDARD2_0 // NetStandard20 includes many optimizations for ConcurrentQueue: // - See: https://blogs.msdn.microsoft.com/dotnet/2017/06/07/performance-improvements-in-net-core/ // Net40 ConcurrencyQueue can seem to leak, because it doesn't clear properly on dequeue // - See: https://blogs.msdn.microsoft.com/pfxteam/2012/05/08/concurrentqueuet-holding-on-to-a-few-dequeued-elements/ _requestQueue = new ConcurrentRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard); #else _requestQueue = new AsyncRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard); #endif _lazyWriterTimer = new Timer((s) => TaskStartNext(null, false), null, Timeout.Infinite, Timeout.Infinite); TaskCancelledTokenReInit(); } /// <inheritdoc/> protected override void InitializeTarget() { _missingServiceTypes = false; TaskCancelledTokenReInit(); base.InitializeTarget(); if (BatchSize <= 0) { BatchSize = 1; } if (!ForceLockingQueue && OverflowAction == AsyncTargetWrapperOverflowAction.Block && BatchSize * 1.5m > QueueLimit) { ForceLockingQueue = true; // ConcurrentQueue does not perform well if constantly hitting QueueLimit } #if !NET35 if (_forceLockingQueue.HasValue && _forceLockingQueue.Value != (_requestQueue is AsyncRequestQueue)) { _requestQueue = ForceLockingQueue ? (AsyncRequestQueueBase)new AsyncRequestQueue(QueueLimit, OverflowAction) : new ConcurrentRequestQueue(QueueLimit, OverflowAction); } #endif if (BatchSize > QueueLimit) { BatchSize = QueueLimit; // Avoid too much throttling } } /// <summary> /// Override this to provide async task for writing a single logevent. /// <example> /// Example of how to override this method, and call custom async method /// <code> /// protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token) /// { /// return CustomWriteAsync(logEvent, token); /// } /// /// private async Task CustomWriteAsync(LogEventInfo logEvent, CancellationToken token) /// { /// await MyLogMethodAsync(logEvent, token).ConfigureAwait(false); /// } /// </code></example> /// </summary> /// <param name="logEvent">The log event.</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns></returns> protected abstract Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken); /// <summary> /// Override this to provide async task for writing a batch of logevents. /// </summary> /// <param name="logEvents">A batch of logevents.</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns></returns> protected virtual Task WriteAsyncTask(IList<LogEventInfo> logEvents, CancellationToken cancellationToken) { if (logEvents.Count == 1) { return WriteAsyncTask(logEvents[0], cancellationToken); } else { // Should never come here. Only here if someone by mistake configured BatchSize > 1 for target that only handles single LogEventInfo Task taskChain = null; for (int i = 0; i < logEvents.Count; ++i) { LogEventInfo logEvent = logEvents[i]; if (taskChain is null) taskChain = WriteAsyncTask(logEvent, cancellationToken); else taskChain = taskChain.ContinueWith(t => WriteAsyncTask(logEvent, cancellationToken), cancellationToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler).Unwrap(); } return taskChain; } } /// <summary> /// Handle cleanup after failed write operation /// </summary> /// <param name="exception">Exception from previous failed Task</param> /// <param name="cancellationToken">The cancellation token</param> /// <param name="retryCountRemaining">Number of retries remaining</param> /// <param name="retryDelay">Time to sleep before retrying</param> /// <returns>Should attempt retry</returns> protected virtual bool RetryFailedAsyncTask(Exception exception, CancellationToken cancellationToken, int retryCountRemaining, out TimeSpan retryDelay) { if (cancellationToken.IsCancellationRequested || retryCountRemaining < 0) { retryDelay = TimeSpan.Zero; return false; } retryDelay = TimeSpan.FromMilliseconds(RetryDelayMilliseconds * Math.Pow(2d, RetryCount - (1 + retryCountRemaining))); return true; } /// <summary> /// Block for override. Instead override <see cref="WriteAsyncTask(LogEventInfo, CancellationToken)"/> /// </summary> protected override sealed void Write(LogEventInfo logEvent) { base.Write(logEvent); } /// <summary> /// Block for override. Instead override <see cref="WriteAsyncTask(IList{LogEventInfo}, CancellationToken)"/> /// </summary> protected override sealed void Write(IList<AsyncLogEventInfo> logEvents) { base.Write(logEvents); } /// <inheritdoc/> protected override sealed void Write(AsyncLogEventInfo logEvent) { if (_cancelTokenSource.IsCancellationRequested) { logEvent.Continuation(null); return; } PrecalculateVolatileLayouts(logEvent.LogEvent); bool queueWasEmpty = _requestQueue.Enqueue(logEvent); if (queueWasEmpty) { bool lockTaken = false; try { if (_previousTask is null) Monitor.Enter(SyncRoot, ref lockTaken); else Monitor.TryEnter(SyncRoot, 50, ref lockTaken); if (_previousTask is null) { _lazyWriterTimer.Change(TaskDelayMilliseconds, Timeout.Infinite); } } finally { if (lockTaken) Monitor.Exit(SyncRoot); } } } /// <summary> /// Write to queue without locking <see cref="Target.SyncRoot"/> /// </summary> /// <param name="logEvent"></param> protected override sealed void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { try { Write(logEvent); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception)) { throw; } logEvent.Continuation(exception); } } /// <summary> /// Block for override. Instead override <see cref="WriteAsyncTask(IList{LogEventInfo}, CancellationToken)"/> /// </summary> protected override sealed void WriteAsyncThreadSafe(IList<AsyncLogEventInfo> logEvents) { base.WriteAsyncThreadSafe(logEvents); } /// <summary> /// LogEvent is written to target, but target failed to successfully initialize /// /// Enqueue logevent for later processing when target failed to initialize because of unresolved service dependency. /// </summary> protected override void WriteFailedNotInitialized(AsyncLogEventInfo logEvent, Exception initializeException) { if (initializeException is Config.NLogDependencyResolveException && OverflowAction == AsyncTargetWrapperOverflowAction.Discard) { _missingServiceTypes = true; Write(logEvent); } else { base.WriteFailedNotInitialized(logEvent, initializeException); } } /// <summary> /// Schedules notification of when all messages has been written /// </summary> /// <param name="asyncContinuation"></param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { if (_previousTask?.IsCompleted == false || !_requestQueue.IsEmpty) { InternalLogger.Debug("{0}: Flushing {1}", this, _requestQueue.IsEmpty ? "empty queue" : "pending queue items"); if (_requestQueue.OnOverflow != AsyncTargetWrapperOverflowAction.Block) { _requestQueue.Enqueue(new AsyncLogEventInfo(null, asyncContinuation)); _lazyWriterTimer.Change(0, Timeout.Infinite); // Schedule timer to empty queue, and execute asyncContinuation } else { // We are holding target-SyncRoot, and might get blocked in queue, so need to schedule flush using async-task if (_flushEventsInQueueDelegate is null) { _flushEventsInQueueDelegate = new AsyncHelpersTask(cont => { _requestQueue.Enqueue(new AsyncLogEventInfo(null, (AsyncContinuation)cont)); lock (SyncRoot) _lazyWriterTimer.Change(0, Timeout.Infinite); // Schedule timer to empty queue, and execute asyncContinuation }); } AsyncHelpers.StartAsyncTask(_flushEventsInQueueDelegate.Value, asyncContinuation); _lazyWriterTimer.Change(0, Timeout.Infinite); // Schedule timer to empty queue, so room for flush-request } } else { InternalLogger.Debug("{0}: Flushing Nothing", this); asyncContinuation(null); } } /// <summary> /// Closes Target by updating CancellationToken /// </summary> protected override void CloseTarget() { _taskTimeoutTimer.Change(Timeout.Infinite, Timeout.Infinite); _cancelTokenSource.Cancel(); _requestQueue.Clear(); _previousTask = null; base.CloseTarget(); } /// <summary> /// Releases any managed resources /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _cancelTokenSource.Dispose(); _taskTimeoutTimer.WaitForDispose(TimeSpan.Zero); _lazyWriterTimer.WaitForDispose(TimeSpan.Zero); } } /// <summary> /// Checks the internal queue for the next <see cref="LogEventInfo"/> to create a new task for /// </summary> /// <param name="previousTask">Used for race-condition validation between task-completion and timeout</param> /// <param name="fullBatchCompleted">Signals whether previousTask completed an almost full BatchSize</param> private void TaskStartNext(object previousTask, bool fullBatchCompleted) { do { lock (SyncRoot) { if (CheckOtherTask(previousTask)) { break; // Other Task is already running } if (_missingServiceTypes) { _previousTask = null; _lazyWriterTimer.Change(50, Timeout.Infinite); break; // Throttle using Timer, since we are not ready yet } if (!IsInitialized) { _previousTask = null; break; } if (previousTask != null && !fullBatchCompleted && TaskDelayMilliseconds >= 50 && !_requestQueue.IsEmpty) { _previousTask = null; _lazyWriterTimer.Change(TaskDelayMilliseconds, Timeout.Infinite); break; // Throttle using Timer, since we didn't write a full batch } using (var targetList = _reusableAsyncLogEventList.Allocate()) { var logEvents = targetList.Result; _requestQueue.DequeueBatch(BatchSize, logEvents); if (logEvents.Count > 0) { if (TaskCreation(logEvents)) return; } else { _previousTask = null; break; // Empty queue, let Task Queue Timer begin next task } } } } while (!_requestQueue.IsEmpty || previousTask != null); } private bool CheckOtherTask(object previousTask) { if (previousTask != null) { // Task Completed if (_previousTask != null && !ReferenceEquals(previousTask, _previousTask)) return true; } else { // Task Queue Timer if (_previousTask?.IsCompleted == false) return true; } return false; } /// <summary> /// Generates recursive task-chain to perform retry of writing logevents with increasing retry-delay /// </summary> internal Task WriteAsyncTaskWithRetry(Task firstTask, IList<LogEventInfo> logEvents, CancellationToken cancellationToken, int retryCount) { var tcs = #if !NET45 new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); #else new TaskCompletionSource<object>(); #endif return firstTask.ContinueWith(t => { if (t.IsFaulted || t.IsCanceled) { if (t.Exception != null) tcs.TrySetException(t.Exception); Exception actualException = ExtractActualException(t.Exception); if (RetryFailedAsyncTask(actualException, cancellationToken, retryCount - 1, out var retryDelay)) { InternalLogger.Warn(actualException, "{0}: Write operation failed. {1} attempts left. Sleep {2} ms", this, retryCount, retryDelay.TotalMilliseconds); AsyncHelpers.WaitForDelay(retryDelay); if (!cancellationToken.IsCancellationRequested) { Task retryTask; lock (SyncRoot) { retryTask = StartWriteAsyncTask(logEvents, cancellationToken); } if (retryTask != null) { return WriteAsyncTaskWithRetry(retryTask, logEvents, cancellationToken, retryCount - 1); } } } InternalLogger.Warn(actualException, "{0}: Write operation failed after {1} retries", this, RetryCount - retryCount); } else { tcs.SetResult(null); } return tcs.Task; }, cancellationToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler).Unwrap(); } /// <summary> /// Creates new task to handle the writing of the input <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvents">LogEvents to write</param> /// <returns>New Task created [true / false]</returns> private bool TaskCreation(IList<AsyncLogEventInfo> logEvents) { System.Tuple<List<LogEventInfo>, List<AsyncContinuation>> reusableLogEvents = null; try { if (_cancelTokenSource.IsCancellationRequested) { for (int i = 0; i < logEvents.Count; ++i) logEvents[i].Continuation(null); return false; } reusableLogEvents = Interlocked.CompareExchange(ref _reusableLogEvents, null, _reusableLogEvents) ?? System.Tuple.Create(new List<LogEventInfo>(), new List<AsyncContinuation>()); for (int i = 0; i < logEvents.Count; ++i) { if (logEvents[i].LogEvent is null) { // Flush Request reusableLogEvents.Item2.Add(logEvents[i].Continuation); } else { reusableLogEvents.Item1.Add(logEvents[i].LogEvent); reusableLogEvents.Item2.Add(logEvents[i].Continuation); } } if (reusableLogEvents.Item1.Count == 0) { // Everything was flush events, no need to schedule write NotifyTaskCompletion(reusableLogEvents.Item2, null); reusableLogEvents.Item2.Clear(); Interlocked.CompareExchange(ref _reusableLogEvents, reusableLogEvents, null); InternalLogger.Debug("{0}: Flush Completed", this); return false; } Task newTask = StartWriteAsyncTask(reusableLogEvents.Item1, _cancelTokenSource.Token); if (newTask is null) { InternalLogger.Debug("{0}: WriteAsyncTask returned null", this); NotifyTaskCompletion(reusableLogEvents.Item2, null); return false; } if (RetryCount > 0) newTask = WriteAsyncTaskWithRetry(newTask, reusableLogEvents.Item1, _cancelTokenSource.Token, RetryCount); _previousTask = newTask; if (TaskTimeoutSeconds > 0) _taskTimeoutTimer.Change(TaskTimeoutSeconds * 1000, Timeout.Infinite); // NOTE - Not using _cancelTokenSource for ContinueWith, or else they will also be cancelled on timeout newTask.ContinueWith(_taskCompletion, reusableLogEvents, TaskScheduler); return true; } catch (Exception ex) { _previousTask = null; InternalLogger.Error(ex, "{0}: WriteAsyncTask failed on creation", this); NotifyTaskCompletion(reusableLogEvents?.Item2, ex); } return false; } private Task StartWriteAsyncTask(IList<LogEventInfo> logEvents, CancellationToken cancellationToken) { try { var newTask = WriteAsyncTask(logEvents, cancellationToken); if (newTask?.Status == TaskStatus.Created) newTask.Start(TaskScheduler); return newTask; } catch (Exception ex) { #if DEBUG if (ex.MustBeRethrownImmediately()) throw; // Throwing exceptions here might crash the entire application (.NET 2.0 behavior) #endif InternalLogger.Error(ex, "{0}: WriteAsyncTask failed on creation", this); #if !NET35 && !NET45 return Task.FromException(ex); #else return Task.Factory.StartNew(e => throw (Exception)e, new AggregateException(ex), _cancelTokenSource.Token, TaskCreationOptions.None, TaskScheduler); #endif } } private void NotifyTaskCompletion(IList<AsyncContinuation> reusableContinuations, Exception ex) { try { for (int i = 0; i < reusableContinuations?.Count; ++i) reusableContinuations[i](ex); } catch { // Don't wanna die } } /// <summary> /// Handles that scheduled task has completed (successfully or failed), and starts the next pending task /// </summary> /// <param name="completedTask">Task just completed</param> /// <param name="continuation">AsyncContinuation to notify of success or failure</param> private void TaskCompletion(Task completedTask, object continuation) { bool success = true; bool fullBatchCompleted = true; try { if (ReferenceEquals(completedTask, _previousTask)) { if (TaskTimeoutSeconds > 0) { // Prevent timeout-timer from triggering task cancellation token _taskTimeoutTimer.Change(Timeout.Infinite, Timeout.Infinite); } } else { // Not the expected task to complete, most likely noise from retry/recovery success = false; if (!IsInitialized) return; } var actualException = ExtractActualException(completedTask.Exception); if (completedTask.IsCanceled) { success = false; if (completedTask.Exception != null) InternalLogger.Warn(completedTask.Exception, "{0}: WriteAsyncTask was cancelled", this); else InternalLogger.Info("{0}: WriteAsyncTask was cancelled", this); } else if (actualException != null) { success = false; if (RetryCount <= 0) { if (RetryFailedAsyncTask(actualException, CancellationToken.None, 0, out var retryDelay)) { InternalLogger.Warn(actualException, "{0}: WriteAsyncTask failed on completion. Sleep {1} ms", this, retryDelay.TotalMilliseconds); AsyncHelpers.WaitForDelay(retryDelay); } } else { InternalLogger.Warn(actualException, "{0}: WriteAsyncTask failed on completion", this); } } var reusableLogEvents = continuation as System.Tuple<List<LogEventInfo>, List<AsyncContinuation>>; if (reusableLogEvents != null) NotifyTaskCompletion(reusableLogEvents.Item2, actualException); else success = false; if (success) { // The expected Task completed with success, allow buffer reuse fullBatchCompleted = reusableLogEvents.Item2.Count * 2 > BatchSize; reusableLogEvents.Item1.Clear(); reusableLogEvents.Item2.Clear(); Interlocked.CompareExchange(ref _reusableLogEvents, reusableLogEvents, null); } } finally { TaskStartNext(completedTask, fullBatchCompleted); } } /// <summary> /// Timer method, that is fired when pending task fails to complete within timeout /// </summary> /// <param name="state"></param> private void TaskTimeout(object state) { try { if (!IsInitialized) return; InternalLogger.Warn("{0}: WriteAsyncTask had timeout. Task will be cancelled.", this); var previousTask = _previousTask; try { lock (SyncRoot) { // Check if active Task changed while waiting for SyncRoot-lock if (previousTask != null && ReferenceEquals(previousTask, _previousTask)) { _previousTask = null; _cancelTokenSource.Cancel(); // Notice how TaskCancelledToken auto recreates token } else { // Not the expected task to timeout, most likely noise from retry/recovery previousTask = null; } } if (previousTask != null) { if (!WaitTaskIsCompleted(previousTask, TimeSpan.FromSeconds(TaskTimeoutSeconds / 10.0))) { InternalLogger.Debug("{0}: WriteAsyncTask had timeout. Task did not cancel properly: {1}.", this, previousTask.Status); } Exception actualException = ExtractActualException(previousTask.Exception); RetryFailedAsyncTask(actualException ?? new TimeoutException("WriteAsyncTask had timeout"), CancellationToken.None, 0, out var retryDelay); } } catch (Exception ex) { InternalLogger.Debug(ex, "{0}: WriteAsyncTask had timeout. Task failed to cancel properly.", this); } TaskStartNext(null, false); } catch (Exception ex) { InternalLogger.Error(ex, "{0}: WriteAsyncTask failed on timeout", this); } } private bool WaitTaskIsCompleted(Task task, TimeSpan timeout) { while (!task.IsCompleted && timeout > TimeSpan.Zero) { timeout -= TimeSpan.FromMilliseconds(10); AsyncHelpers.WaitForDelay(TimeSpan.FromMilliseconds(10)); } return task.IsCompleted; } private static Exception ExtractActualException(AggregateException taskException) { var flattenExceptions = taskException?.Flatten()?.InnerExceptions; Exception actualException = flattenExceptions?.Count == 1 ? flattenExceptions[0] : taskException; return actualException; } private void TaskCancelledTokenReInit() { _cancelTokenSource = new CancellationTokenSource(); _cancelTokenSource.Token.Register(_taskCancelledTokenReInit); } } } #endif <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Text; using NLog.Filters; using NLog.Targets; /// <summary> /// Represents a logging rule. An equivalent of &lt;logger /&gt; configuration element. /// </summary> [NLogConfigurationItem] public class LoggingRule { private ILoggingRuleLevelFilter _logLevelFilter = LoggingRuleLevelFilter.Off; private LoggerNameMatcher _loggerNameMatcher = LoggerNameMatcher.Create(null); private readonly List<Target> _targets = new List<Target>(); /// <summary> /// Create an empty <see cref="LoggingRule" />. /// </summary> public LoggingRule() :this(null) { } /// <summary> /// Create an empty <see cref="LoggingRule" />. /// </summary> public LoggingRule(string ruleName) { RuleName = ruleName; } /// <summary> /// Create a new <see cref="LoggingRule" /> with a <paramref name="minLevel"/> and <paramref name="maxLevel"/> which writes to <paramref name="target"/>. /// </summary> /// <param name="loggerNamePattern">Logger name pattern used for <see cref="LoggerNamePattern"/>. It may include one or more '*' or '?' wildcards at any position.</param> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> /// <param name="target">Target to be written to when the rule matches.</param> public LoggingRule(string loggerNamePattern, LogLevel minLevel, LogLevel maxLevel, Target target) : this() { LoggerNamePattern = loggerNamePattern; _targets.Add(target); EnableLoggingForLevels(minLevel, maxLevel); } /// <summary> /// Create a new <see cref="LoggingRule" /> with a <paramref name="minLevel"/> which writes to <paramref name="target"/>. /// </summary> /// <param name="loggerNamePattern">Logger name pattern used for <see cref="LoggerNamePattern"/>. It may include one or more '*' or '?' wildcards at any position.</param> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="target">Target to be written to when the rule matches.</param> public LoggingRule(string loggerNamePattern, LogLevel minLevel, Target target) : this() { LoggerNamePattern = loggerNamePattern; _targets.Add(target); EnableLoggingForLevels(minLevel, LogLevel.MaxLevel); } /// <summary> /// Create a (disabled) <see cref="LoggingRule" />. You should call <see cref="EnableLoggingForLevel"/> or <see cref="EnableLoggingForLevels"/> to enable logging. /// </summary> /// <param name="loggerNamePattern">Logger name pattern used for <see cref="LoggerNamePattern"/>. It may include one or more '*' or '?' wildcards at any position.</param> /// <param name="target">Target to be written to when the rule matches.</param> public LoggingRule(string loggerNamePattern, Target target) : this() { LoggerNamePattern = loggerNamePattern; _targets.Add(target); } /// <summary> /// Rule identifier to allow rule lookup /// </summary> public string RuleName { get; set; } /// <summary> /// Gets a collection of targets that should be written to when this rule matches. /// </summary> public IList<Target> Targets => _targets; /// <summary> /// Gets a collection of child rules to be evaluated when this rule matches. /// </summary> public IList<LoggingRule> ChildRules { get; } = new List<LoggingRule>(); internal List<LoggingRule> GetChildRulesThreadSafe() { lock (ChildRules) return ChildRules.ToList(); } internal Target[] GetTargetsThreadSafe() { lock (_targets) return _targets.Count == 0 ? NLog.Internal.ArrayHelper.Empty<Target>() : _targets.ToArray(); } internal bool RemoveTargetThreadSafe(Target target) { lock (_targets) return _targets.Remove(target); } /// <summary> /// Gets a collection of filters to be checked before writing to targets. /// </summary> public IList<Filter> Filters { get; } = new List<Filter>(); /// <summary> /// Gets or sets a value indicating whether to quit processing any following rules when this one matches. /// </summary> public bool Final { get; set; } /// <summary> /// Gets or sets the <see cref="NLog.LogLevel"/> whether to quit processing any following rules when lower severity and this one matches. /// </summary> /// <remarks> /// Loggers matching will be restricted to specified minimum level for following rules. /// </remarks> public LogLevel FinalMinLevel { get => _logLevelFilter.FinalMinLevel; set => _logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetFinalMinLevel(value); } /// <summary> /// Gets or sets logger name pattern. /// </summary> /// <remarks> /// Logger name pattern used by <see cref="NameMatches(string)"/> to check if a logger name matches this rule. /// It may include one or more '*' or '?' wildcards at any position. /// <list type="bullet"> /// <item>'*' means zero or more occurrences of any character</item> /// <item>'?' means exactly one occurrence of any character</item> /// </list> /// </remarks> public string LoggerNamePattern { get => _loggerNameMatcher.Pattern; set => _loggerNameMatcher = LoggerNameMatcher.Create(value); } internal bool[] LogLevels => _logLevelFilter.LogLevels; /// <summary> /// Gets the collection of log levels enabled by this rule. /// </summary> [NLogConfigurationIgnoreProperty] public ReadOnlyCollection<LogLevel> Levels { get { var enabledLogLevels = new List<LogLevel>(); var currentLogLevels = _logLevelFilter.LogLevels; for (int i = LogLevel.MinLevel.Ordinal; i <= LogLevel.MaxLevel.Ordinal; ++i) { if (currentLogLevels[i]) { enabledLogLevels.Add(LogLevel.FromOrdinal(i)); } } return enabledLogLevels.AsReadOnly(); } } /// <summary> /// Default action if none of the filters match /// </summary> [Obsolete("Replaced by FilterDefaultAction. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public FilterResult DefaultFilterResult { get => FilterDefaultAction; set => FilterDefaultAction = value; } /// <summary> /// Default action if none of the filters match /// </summary> public FilterResult FilterDefaultAction { get; set; } = FilterResult.Ignore; /// <summary> /// Enables logging for a particular level. /// </summary> /// <param name="level">Level to be enabled.</param> public void EnableLoggingForLevel(LogLevel level) { if (level == LogLevel.Off) { return; } _logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(level, level, true); } /// <summary> /// Enables logging for a particular levels between (included) <paramref name="minLevel"/> and <paramref name="maxLevel"/>. /// </summary> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> public void EnableLoggingForLevels(LogLevel minLevel, LogLevel maxLevel) { _logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(minLevel, maxLevel, true); } internal void EnableLoggingForLevelLayout(NLog.Layouts.SimpleLayout simpleLayout, NLog.Layouts.SimpleLayout finalMinLevel) { _logLevelFilter = new DynamicLogLevelFilter(this, simpleLayout, finalMinLevel); } internal void EnableLoggingForLevelsLayout(Layouts.SimpleLayout minLevel, Layouts.SimpleLayout maxLevel, NLog.Layouts.SimpleLayout finalMinLevel) { _logLevelFilter = new DynamicRangeLevelFilter(this, minLevel, maxLevel, finalMinLevel); } /// <summary> /// Disables logging for a particular level. /// </summary> /// <param name="level">Level to be disabled.</param> public void DisableLoggingForLevel(LogLevel level) { if (level == LogLevel.Off) { return; } _logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(level, level, false); } /// <summary> /// Disables logging for particular levels between (included) <paramref name="minLevel"/> and <paramref name="maxLevel"/>. /// </summary> /// <param name="minLevel">Minimum log level to be disables.</param> /// <param name="maxLevel">Maximum log level to be disabled.</param> public void DisableLoggingForLevels(LogLevel minLevel, LogLevel maxLevel) { _logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(minLevel, maxLevel, false); } /// <summary> /// Enables logging the levels between (included) <paramref name="minLevel"/> and <paramref name="maxLevel"/>. All the other levels will be disabled. /// </summary> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> public void SetLoggingLevels(LogLevel minLevel, LogLevel maxLevel) { _logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(LogLevel.MinLevel, LogLevel.MaxLevel, false).SetLoggingLevels(minLevel, maxLevel, true); } /// <summary> /// Returns a string representation of <see cref="LoggingRule"/>. Used for debugging. /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append(_loggerNameMatcher.ToString()); sb.Append(" levels: [ "); var currentLogLevels = _logLevelFilter.LogLevels; for (int i = 0; i < currentLogLevels.Length; ++i) { if (currentLogLevels[i]) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0} ", LogLevel.FromOrdinal(i).ToString()); } } sb.Append("] writeTo: [ "); foreach (Target writeTo in GetTargetsThreadSafe()) { var targetName = string.IsNullOrEmpty(writeTo.Name) ? writeTo.ToString() : writeTo.Name; sb.AppendFormat(CultureInfo.InvariantCulture, "{0} ", targetName); } sb.Append(']'); return sb.ToString(); } /// <summary> /// Checks whether the particular log level is enabled for this rule. /// </summary> /// <param name="level">Level to be checked.</param> /// <returns>A value of <see langword="true"/> when the log level is enabled, <see langword="false" /> otherwise.</returns> public bool IsLoggingEnabledForLevel(LogLevel level) { if (level == LogLevel.Off) { return false; } var currentLogLevels = _logLevelFilter.LogLevels; return currentLogLevels[level.Ordinal]; } /// <summary> /// Checks whether given name matches the <see cref="LoggerNamePattern"/>. /// </summary> /// <param name="loggerName">String to be matched.</param> /// <returns>A value of <see langword="true"/> when the name matches, <see langword="false" /> otherwise.</returns> public bool NameMatches(string loggerName) { return _loggerNameMatcher.NameMatches(loggerName); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; namespace NLog.Targets.Wrappers { using System.Collections.Generic; using NLog.Common; internal abstract class AsyncRequestQueueBase { public abstract bool IsEmpty { get; } /// <summary> /// Gets or sets the request limit. /// </summary> public int RequestLimit { get; set; } /// <summary> /// Gets or sets the action to be taken when there's no more room in /// the queue and another request is enqueued. /// </summary> public AsyncTargetWrapperOverflowAction OnOverflow { get; set; } /// <summary> /// Occurs when LogEvent has been dropped, because internal queue is full and <see cref="OnOverflow"/> set to <see cref="AsyncTargetWrapperOverflowAction.Discard"/> /// </summary> public event EventHandler<LogEventDroppedEventArgs> LogEventDropped; /// <summary> /// Occurs when internal queue size is growing, because internal queue is full and <see cref="OnOverflow"/> set to <see cref="AsyncTargetWrapperOverflowAction.Grow"/> /// </summary> public event EventHandler<LogEventQueueGrowEventArgs> LogEventQueueGrow; public abstract bool Enqueue(AsyncLogEventInfo logEventInfo); public abstract AsyncLogEventInfo[] DequeueBatch(int count); public abstract void DequeueBatch(int count, IList<AsyncLogEventInfo> result); public abstract void Clear(); /// <summary> /// Raise event when queued element was dropped because of queue overflow /// </summary> /// <param name="logEventInfo">Dropped queue item</param> protected void OnLogEventDropped(LogEventInfo logEventInfo) => LogEventDropped?.Invoke(this, new LogEventDroppedEventArgs(logEventInfo)); /// <summary> /// Raise event when RequestCount overflow <see cref="RequestLimit"/> /// </summary> /// <param name="requestsCount"> current requests count</param> protected void OnLogEventQueueGrows(long requestsCount) => LogEventQueueGrow?.Invoke(this, new LogEventQueueGrowEventArgs(RequestLimit, requestsCount)); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 && !NETSTANDARD1_5 namespace NLog.LayoutRenderers { using System; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text; using NLog.Common; using NLog.Config; using NLog.Internal; /// <summary> /// The IP address from the network interface card (NIC) on the local machine /// </summary> /// <remarks> /// Skips loopback-adapters and tunnel-interfaces. Skips devices without any MAC-address /// </remarks> [LayoutRenderer("local-ip")] [ThreadAgnostic] public class LocalIpAddressLayoutRenderer : LayoutRenderer { private AddressFamily? _addressFamily; private readonly INetworkInterfaceRetriever _networkInterfaceRetriever; /// <summary> /// Get or set whether to prioritize IPv6 or IPv4 (default) /// </summary> /// <docgen category='Layout Options' order='10' /> public AddressFamily AddressFamily { get => _addressFamily ?? AddressFamily.InterNetwork; set => _addressFamily = value; } /// <inheritdoc/> public LocalIpAddressLayoutRenderer() { _networkInterfaceRetriever = new NetworkInterfaceRetriever(); } /// <inheritdoc/> internal LocalIpAddressLayoutRenderer(INetworkInterfaceRetriever networkInterfaceRetriever) { _networkInterfaceRetriever = networkInterfaceRetriever; } /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(LookupIpAddress()); } private string LookupIpAddress() { int currentNetworkScore = 0; string currentIpAddress = string.Empty; try { foreach (var networkInterface in _networkInterfaceRetriever.AllNetworkInterfaces) { int networkScore = CalculateNetworkInterfaceScore(networkInterface); if (networkScore == 0) continue; var ipProperties = networkInterface.GetIPProperties(); foreach (var networkAddress in ipProperties.UnicastAddresses) { int unicastScore = CalculateNetworkAddressScore(networkAddress, ipProperties); if (unicastScore == 0) continue; if (CheckOptimalNetworkScore(networkAddress, networkScore + unicastScore, ref currentNetworkScore, ref currentIpAddress)) { return currentIpAddress; } } } return currentIpAddress; } catch (Exception ex) { InternalLogger.Warn(ex, "Failed to lookup NetworkInterface.GetAllNetworkInterfaces()"); return currentIpAddress; } } private bool CheckOptimalNetworkScore(UnicastIPAddressInformation networkAddress, int networkScore, ref int currentNetworkScore, ref string currentIpAddress) { const int greatNetworkScore = 30; // 16 = Good Address Family + 9 = Good NetworkStatus + 3 = Valid gateway + Extra Bonus Points if (networkScore > currentNetworkScore) { currentIpAddress = networkAddress.Address.ToString(); currentNetworkScore = networkScore; if (currentNetworkScore >= greatNetworkScore) return true; } return false; } private static int CalculateNetworkInterfaceScore(NetworkInterface networkInterface) { if (networkInterface.NetworkInterfaceType == NetworkInterfaceType.Loopback) return 0; if (networkInterface.NetworkInterfaceType == NetworkInterfaceType.Tunnel) return 0; const int macAddressMinLength = 12; if (networkInterface.GetPhysicalAddress()?.ToString()?.Length >= macAddressMinLength) { int currentScore = 1; if (networkInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet || networkInterface.NetworkInterfaceType == NetworkInterfaceType.GigabitEthernet) currentScore += 1; if (networkInterface.OperationalStatus == OperationalStatus.Up) currentScore += 9; // Better to have Ipv6 that is Up, than Ipv4 that is Down return currentScore; } return 0; } private int CalculateNetworkAddressScore(UnicastIPAddressInformation networkAddress, IPInterfaceProperties ipProperties) { var currentScore = CalculateIpAddressScore(networkAddress.Address); if (currentScore == 0) return 0; var gatewayAddresses = ipProperties.GatewayAddresses; if (gatewayAddresses?.Count > 0) { foreach (var gateway in gatewayAddresses) { if (!IsLoopbackAddressValue(gateway.Address)) { currentScore += 3; break; } } } var dnsAddresses = ipProperties.DnsAddresses; if (dnsAddresses?.Count > 0) { foreach (var dns in dnsAddresses) { if (!IsLoopbackAddressValue(dns)) { currentScore += 1; break; } } } return currentScore; } private int CalculateIpAddressScore(IPAddress ipAddress) { if (ipAddress.AddressFamily != AddressFamily.InterNetwork && ipAddress.AddressFamily != AddressFamily.InterNetworkV6 && ipAddress.AddressFamily != _addressFamily) return 0; if (IsLoopbackAddressValue(ipAddress)) return 0; int currentScore = 0; if (_addressFamily.HasValue) { if (ipAddress.AddressFamily == _addressFamily.Value) currentScore += 16; else currentScore += 4; } else if (ipAddress.AddressFamily == AddressFamily.InterNetwork) { currentScore += 16; } else { currentScore += 8; } return currentScore; } private static bool IsLoopbackAddressValue(IPAddress ipAddress) { if (ipAddress is null) return true; if (IPAddress.IsLoopback(ipAddress)) return true; var ipAddressValue = ipAddress.ToString(); return string.IsNullOrEmpty(ipAddressValue) || ipAddressValue == "127.0.0.1" || ipAddressValue == "0.0.0.0" || ipAddressValue == "::1" || ipAddressValue == "::"; } } } #endif <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Diagnostics; using Xunit; namespace NLog.UnitTests.Targets { public class DebugSystemTargetTests : NLogTestBase { [Fact] public void DebugWriteLineTest() { var sw = new System.IO.StringWriter(); try { // Arrange #if !NETSTANDARD Debug.Listeners.Clear(); Debug.Listeners.Add(new TextWriterTraceListener(sw)); #endif var logFactory = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteToDebug(); }).LogFactory; // Act logFactory.GetCurrentClassLogger().Info("Hello World"); // Assert Assert.Single(logFactory.Configuration.AllTargets); #if !NETSTANDARD Assert.Contains("Hello World", sw.ToString()); #endif } finally { #if !NETSTANDARD Debug.Listeners.Clear(); #endif } } [Fact] public void DebugWriteLineHeaderFooterTest() { var sw = new System.IO.StringWriter(); try { // Arrange #if !NETSTANDARD Debug.Listeners.Clear(); Debug.Listeners.Add(new TextWriterTraceListener(sw)); #endif var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target type='debugsystem' name='Debug' layout='${message}'> <header>Startup</header> <footer>Shutdown</footer> </target> </targets> <rules> <logger name='*' writeTo='Debug' /> </rules> </nlog>").LogFactory; // Act logFactory.GetCurrentClassLogger().Info("Hello World"); // Assert Assert.Single(logFactory.Configuration.AllTargets); #if !NETSTANDARD Assert.Contains("Startup", sw.ToString()); Assert.Contains("Hello World", sw.ToString()); Assert.DoesNotContain("Shutdown", sw.ToString()); logFactory.Shutdown(); Assert.Contains("Shutdown", sw.ToString()); #endif } finally { #if !NETSTANDARD Debug.Listeners.Clear(); #endif } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD && !MONO using System; using System.IO; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using NLog.Config; using Xunit; namespace NLog.UnitTests.Internal { public class AppDomainPartialTrustTests : NLogTestBase { [Fact] public void MediumTrustWithExternalClass() { var fileWritePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); try { int times = 25; RunAppDomainTestMethod(fileWritePath, times, true); // this also checks that thread-volatile layouts // such as ${threadid} are properly cached and not recalculated // in logging threads. var threadID = Thread.CurrentThread.ManagedThreadId.ToString(); Assert.False(File.Exists(Path.Combine(fileWritePath, "Trace.txt"))); AssertFileContents(Path.Combine(fileWritePath, "Debug.txt"), StringRepeat(times, "aaa " + threadID + "\n"), Encoding.UTF8); AssertFileContents(Path.Combine(fileWritePath, "Info.txt"), StringRepeat(times, "bbb " + threadID + "\n"), Encoding.UTF8); AssertFileContents(Path.Combine(fileWritePath, "Warn.txt"), StringRepeat(times, "ccc " + threadID + "\n"), Encoding.UTF8); AssertFileContents(Path.Combine(fileWritePath, "Error.txt"), StringRepeat(times, "ddd " + threadID + "\n"), Encoding.UTF8); AssertFileContents(Path.Combine(fileWritePath, "Fatal.txt"), StringRepeat(times, "eee " + threadID + "\n"), Encoding.UTF8); } finally { if (Directory.Exists(fileWritePath)) Directory.Delete(fileWritePath, true); } } [Fact] public void MediumTrustWithExternalClassNoAutoFlush() { var fileWritePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); try { int times = 5; RunAppDomainTestMethod(fileWritePath, times, false); Assert.False(File.Exists(Path.Combine(fileWritePath, "Trace.txt"))); Assert.False(File.Exists(Path.Combine(fileWritePath, "Debug.txt"))); Assert.False(File.Exists(Path.Combine(fileWritePath, "Warn.txt"))); Assert.False(File.Exists(Path.Combine(fileWritePath, "Error.txt"))); Assert.False(File.Exists(Path.Combine(fileWritePath, "Fatal.txt"))); } finally { if (Directory.Exists(fileWritePath)) Directory.Delete(fileWritePath, true); } } private static void RunAppDomainTestMethod(string fileWritePath, int times, bool autoShutdown) { // ClassUnderTest must extend MarshalByRefObject AppDomain partialTrusted = MediumTrustContext.CreatePartialTrustDomain(fileWritePath); var classUnderTest = (ClassUnderTest)partialTrusted.CreateInstanceAndUnwrap(typeof(ClassUnderTest).Assembly.FullName, typeof(ClassUnderTest).FullName); using (ScopeContext.PushProperty("Winner", new { Hero = "Zero" })) using (ScopeContext.PushNestedState(new { Hello = "World" })) { partialTrusted.DoCallBack(HelloWorld); classUnderTest.PartialTrustSuccess(times, fileWritePath, autoShutdown); } AppDomain.Unload(partialTrusted); } #pragma warning disable xUnit1013 // Public method should be marked as test public static void HelloWorld() #pragma warning restore xUnit1013 // Public method should be marked as test { Console.WriteLine("Hello World"); } } [Serializable] public class ClassUnderTest : MarshalByRefObject { public void PartialTrustSuccess(int times, string fileWritePath, bool autoShutdown) { var filePath = Path.Combine(fileWritePath, "${level}.txt"); // NOTE Using BufferingWrapper to validate that DomainUnload remembers to perform flush var configXml = $@" <nlog throwExceptions='false' autoShutdown='{autoShutdown}'> <targets async='true'> <target name='file' type='BufferingWrapper' bufferSize='10000'> <target name='filewrapped' type='file' layout='${{message}} ${{threadid}}' filename='{ filePath }' LineEnding='lf' concurrentWrites='true' /> </target> </targets> <rules> <logger name='*' minlevel='Debug' appendto='file'> </logger> </rules> </nlog>"; using (new NLogTestBase.NoThrowNLogExceptions()) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(configXml); //this method gave issues LogFactory.LogNLogAssemblyVersion(); var logger = LogManager.GetLogger("NLog.UnitTests.Targets.FileTargetTests"); for (var i = 0; i < times; ++i) { logger.Trace("@@@"); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); logger.Error("{d:l}", "ddd"); logger.Fatal("eee"); } } } } internal static class MediumTrustContext { public static AppDomain CreatePartialTrustDomain(string fileWritePath) { var setup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory }; var permissions = new PermissionSet(null); permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); permissions.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess)); permissions.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess, fileWritePath)); return AppDomain.CreateDomain("Partial Trust AppDomain: " + DateTime.Now.Ticks, null, setup, permissions); } } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Threading.Tasks; using NLog.Config; using Xunit; namespace NLog.UnitTests.LayoutRenderers { public class CallSiteLineNumberTests : NLogTestBase { #if !DEBUG [Fact(Skip = "RELEASE not working, only DEBUG")] #else [Fact] #endif public void LineNumberOnlyTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite-linenumber} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); #if DEBUG #line 100000 #endif logger.Debug("msg"); var linenumber = GetPrevLineNumber(); var lastMessage = GetDebugLastMessage("debug", logFactory); // There's a difference in handling line numbers between .NET and Mono // We're just interested in checking if it's above 100000 Assert.True(lastMessage.IndexOf(linenumber.ToString(), StringComparison.OrdinalIgnoreCase) == 0, "Invalid line number. Expected prefix of 10000, got: " + lastMessage); #if DEBUG #line default #endif } #if !MONO [Fact] #else [Fact(Skip = "MONO is not good with callsite line numbers")] #endif public void LineNumberOnlyAsyncTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite-linenumber}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); Func<string> getLastMessage = () => GetDebugLastMessage("debug", logFactory); logger.Debug("msg"); var lastMessage = getLastMessage(); Assert.NotEqual(0, int.Parse(lastMessage)); WriteMessages(logger, getLastMessage).Wait(); } [Fact] public void LineNumberNoCaptureStackTraceTest() { // Arrange var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite-linenumber:captureStackTrace=false} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; // Act logFactory.GetLogger("A").Debug("msg"); // Assert logFactory.AssertDebugLastMessage(" msg"); } [Fact] public void LineNumberNoCaptureStackTraceWithStackTraceTest() { // Arrange var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite-linenumber:captureStackTrace=false} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; // Act var logEvent = new LogEventInfo(LogLevel.Info, null, "msg"); logEvent.SetStackTrace(new System.Diagnostics.StackTrace(true), 0); logFactory.GetLogger("A").Log(logEvent); // Assert logFactory.AssertDebugLastMessageContains(" msg"); Assert.NotEqual(" msg", GetDebugLastMessage("debug", logFactory)); } private static async Task WriteMessages(Logger logger, Func<string> getLastMessage) { logger.Info("Line number should be non-zero"); var lastMessage1 = getLastMessage(); Assert.NotEqual(0, int.Parse(lastMessage1)); try { await Task.Delay(1); logger.Info("Line number should be non-zero"); var lastMessage2 = getLastMessage(); Assert.NotEqual(0, int.Parse(lastMessage2)); // Here I have some other logic ... } catch (Exception ex) { logger.Error(ex); } logger.Info("Line number should be non-zero"); var lastMessage3 = getLastMessage(); Assert.NotEqual(0, int.Parse(lastMessage3)); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; using JetBrains.Annotations; using NLog.Config; using NLog.Internal; namespace NLog.MessageTemplates { /// <summary> /// Convert, Render or serialize a value, with optionally backwards-compatible with <see cref="string.Format(System.IFormatProvider,string,object[])"/> /// </summary> internal class ValueFormatter : IValueFormatter { private static readonly IEqualityComparer<object> _referenceEqualsComparer = SingleItemOptimizedHashSet<object>.ReferenceEqualityComparer.Default; private readonly MruCache<Enum, string> _enumCache = new MruCache<Enum, string>(2000); private readonly IServiceProvider _serviceProvider; private IJsonConverter JsonConverter => _jsonConverter ?? (_jsonConverter = _serviceProvider.GetService<IJsonConverter>()); private IJsonConverter _jsonConverter; public ValueFormatter([NotNull] IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } private const int MaxRecursionDepth = 2; private const int MaxValueLength = 512 * 1024; private const string LiteralFormatSymbol = "l"; public const string FormatAsJson = "@"; public const string FormatAsString = "$"; /// <summary> /// Serialization of an object, e.g. JSON and append to <paramref name="builder"/> /// </summary> /// <param name="value">The object to serialize to string.</param> /// <param name="format">Parameter Format</param> /// <param name="captureType">Parameter CaptureType</param> /// <param name="formatProvider">An object that supplies culture-specific formatting information.</param> /// <param name="builder">Output destination.</param> /// <returns>Serialize succeeded (true/false)</returns> public bool FormatValue(object value, string format, CaptureType captureType, IFormatProvider formatProvider, StringBuilder builder) { switch (captureType) { case CaptureType.Serialize: { return JsonConverter.SerializeObject(value, builder); } case CaptureType.Stringify: { builder.Append('"'); FormatToString(value, null, formatProvider, builder); builder.Append('"'); return true; } default: { return FormatObject(value, format, formatProvider, builder); } } } /// <summary> /// Format an object to a readable string, or if it's an object, serialize /// </summary> /// <param name="value">The value to convert</param> /// <param name="format"></param> /// <param name="formatProvider"></param> /// <param name="builder"></param> /// <returns></returns> public bool FormatObject(object value, string format, IFormatProvider formatProvider, StringBuilder builder) { if (SerializeSimpleObject(value, format, formatProvider, builder, false)) { return true; } IEnumerable collection = value as IEnumerable; if (collection != null) { return SerializeWithoutCyclicLoop(collection, format, formatProvider, builder, default(SingleItemOptimizedHashSet<object>), 0); } SerializeConvertToString(value, formatProvider, builder); return true; } /// <summary> /// Try serializing a scalar (string, int, NULL) or simple type (IFormattable) /// </summary> private bool SerializeSimpleObject(object value, string format, IFormatProvider formatProvider, StringBuilder builder, bool convertToString = true) { if (value is string stringValue) { SerializeStringObject(stringValue, format, builder); return true; } if (value is null) { builder.Append("NULL"); return true; } // Optimize for types that are pretty much invariant in all cultures when no format-string if (value is IConvertible convertibleValue) { SerializeConvertibleObject(convertibleValue, format, formatProvider, builder); return true; } else { if (!string.IsNullOrEmpty(format) && value is IFormattable formattable) { builder.Append(formattable.ToString(format, formatProvider)); return true; } if (convertToString) { SerializeConvertToString(value, formatProvider, builder); return true; } return false; } } private void SerializeConvertibleObject(IConvertible value, string format, IFormatProvider formatProvider, StringBuilder builder) { TypeCode convertibleTypeCode = value.GetTypeCode(); if (convertibleTypeCode == TypeCode.String) { SerializeStringObject(value.ToString(), format, builder); return; } if (!string.IsNullOrEmpty(format) && value is IFormattable formattable) { builder.Append(formattable.ToString(format, formatProvider)); return; } switch (convertibleTypeCode) { case TypeCode.Boolean: { builder.Append(value.ToBoolean(CultureInfo.InvariantCulture) ? "true" : "false"); break; } case TypeCode.Char: { bool includeQuotes = format != LiteralFormatSymbol; if (includeQuotes) builder.Append('"'); builder.Append(value.ToChar(CultureInfo.InvariantCulture)); if (includeQuotes) builder.Append('"'); break; } case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: { if (value is Enum enumValue) { AppendEnumAsString(builder, enumValue); } else { builder.AppendNumericInvariant(value, convertibleTypeCode); } break; } case TypeCode.Object: // Guid, TimeSpan, DateTimeOffset default: // Single, Double, Decimal, etc. SerializeConvertToString(value, formatProvider, builder); break; } } private static void SerializeConvertToString(object value, IFormatProvider formatProvider, StringBuilder builder) { #if NETSTANDARD if (value is IFormattable) builder.AppendFormat(formatProvider, "{0}", value); // Support ISpanFormattable else #endif builder.Append(Convert.ToString(value, formatProvider)); } private static void SerializeStringObject(string stringValue, string format, StringBuilder builder) { bool includeQuotes = format != LiteralFormatSymbol; if (includeQuotes) builder.Append('"'); builder.Append(stringValue); if (includeQuotes) builder.Append('"'); } private void AppendEnumAsString(StringBuilder sb, Enum value) { if (!_enumCache.TryGetValue(value, out var textValue)) { textValue = value.ToString(); _enumCache.TryAddValue(value, textValue); } sb.Append(textValue); } private bool SerializeWithoutCyclicLoop(IEnumerable collection, string format, IFormatProvider formatProvider, StringBuilder builder, SingleItemOptimizedHashSet<object> objectsInPath, int depth) { if (objectsInPath.Contains(collection)) { return false; // detected reference loop, skip serialization } if (depth > MaxRecursionDepth) { return false; // reached maximum recursion level, no further serialization } IDictionary dictionary = collection as IDictionary; if (dictionary != null) { using (new SingleItemOptimizedHashSet<object>.SingleItemScopedInsert(dictionary, ref objectsInPath, true, _referenceEqualsComparer)) { return SerializeDictionaryObject(dictionary, format, formatProvider, builder, objectsInPath, depth); } } using (new SingleItemOptimizedHashSet<object>.SingleItemScopedInsert(collection, ref objectsInPath, true, _referenceEqualsComparer)) { return SerializeCollectionObject(collection, format, formatProvider, builder, objectsInPath, depth); } } /// <summary> /// Serialize Dictionary as JSON like structure, without { and } /// </summary> /// <example> /// "FirstOrder"=true, "Previous login"=20-12-2017 14:55:32, "number of tries"=1 /// </example> /// <param name="dictionary"></param> /// <param name="format">format string of an item</param> /// <param name="formatProvider"></param> /// <param name="builder"></param> /// <param name="objectsInPath"></param> /// <param name="depth"></param> /// <returns></returns> private bool SerializeDictionaryObject(IDictionary dictionary, string format, IFormatProvider formatProvider, StringBuilder builder, SingleItemOptimizedHashSet<object> objectsInPath, int depth) { bool separator = false; foreach (var item in new DictionaryEntryEnumerable(dictionary)) { if (builder.Length > MaxValueLength) return false; if (separator) builder.Append(", "); SerializeCollectionItem(item.Key, format, formatProvider, builder, ref objectsInPath, depth); builder.Append('='); SerializeCollectionItem(item.Value, format, formatProvider, builder, ref objectsInPath, depth); separator = true; } return true; } private bool SerializeCollectionObject(IEnumerable collection, string format, IFormatProvider formatProvider, StringBuilder builder, SingleItemOptimizedHashSet<object> objectsInPath, int depth) { bool separator = false; foreach (var item in collection) { if (builder.Length > MaxValueLength) return false; if (separator) builder.Append(", "); SerializeCollectionItem(item, format, formatProvider, builder, ref objectsInPath, depth); separator = true; } return true; } private void SerializeCollectionItem(object item, string format, IFormatProvider formatProvider, StringBuilder builder, ref SingleItemOptimizedHashSet<object> objectsInPath, int depth) { if (item is IConvertible convertible) SerializeConvertibleObject(convertible, format, formatProvider, builder); else if (item is IEnumerable enumerable) SerializeWithoutCyclicLoop(enumerable, format, formatProvider, builder, objectsInPath, depth + 1); else SerializeSimpleObject(item, format, formatProvider, builder); } /// <summary> /// Convert a value to a string with format and append to <paramref name="builder"/>. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="format">Format sting for the value.</param> /// <param name="formatProvider">Format provider for the value.</param> /// <param name="builder">Append to this</param> public static void FormatToString(object value, string format, IFormatProvider formatProvider, StringBuilder builder) { var stringValue = value as string; if (stringValue != null) { builder.Append(stringValue); } else { if (value is IFormattable formattable) { #if NETSTANDARD if (string.IsNullOrEmpty(format)) builder.AppendFormat(formatProvider, "{0}", formattable); // Support ISpanFormattable else #endif builder.Append(formattable.ToString(format, formatProvider)); } else { builder.Append(Convert.ToString(value, formatProvider)); } } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal.NetworkSenders { using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using NLog.Common; /// <summary> /// A base class for all network senders. Supports one-way sending of messages /// over various protocols. /// </summary> internal abstract class NetworkSender : IDisposable { private static int currentSendTime; /// <summary> /// Initializes a new instance of the <see cref="NetworkSender" /> class. /// </summary> /// <param name="url">The network URL.</param> protected NetworkSender(string url) { Address = url; LastSendTime = Interlocked.Increment(ref currentSendTime); } /// <summary> /// Gets the address of the network endpoint. /// </summary> public string Address { get; private set; } /// <summary> /// Gets the last send time. /// </summary> public int LastSendTime { get; private set; } /// <summary> /// Initializes this network sender. /// </summary> public void Initialize() { DoInitialize(); } /// <summary> /// Closes the sender and releases any unmanaged resources. /// </summary> /// <param name="continuation">The continuation.</param> public void Close(AsyncContinuation continuation) { DoClose(continuation); } /// <summary> /// Flushes any pending messages and invokes the <paramref name="continuation"/> on completion. /// </summary> /// <param name="continuation">The continuation.</param> public void FlushAsync(AsyncContinuation continuation) { DoFlush(continuation); } /// <summary> /// Send the given text over the specified protocol. /// </summary> /// <param name="bytes">Bytes to be sent.</param> /// <param name="offset">Offset in buffer.</param> /// <param name="length">Number of bytes to send.</param> /// <param name="asyncContinuation">The asynchronous continuation.</param> public void Send(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation) { try { LastSendTime = Interlocked.Increment(ref currentSendTime); DoSend(bytes, offset, length, asyncContinuation); } catch (Exception ex) { InternalLogger.Error(ex, "NetworkTarget: Error sending network request"); asyncContinuation(ex); } } /// <summary> /// Closes the sender and releases any unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Initializes resources for the protocol specific implementation. /// </summary> protected virtual void DoInitialize() { } /// <summary> /// Closes resources for the protocol specific implementation. /// </summary> /// <param name="continuation">The continuation.</param> protected virtual void DoClose(AsyncContinuation continuation) { continuation(null); } /// <summary> /// Performs the flush and invokes the <paramref name="continuation"/> on completion. /// </summary> /// <param name="continuation">The continuation.</param> protected virtual void DoFlush(AsyncContinuation continuation) { continuation(null); } /// <summary> /// Sends the payload using the protocol specific implementation. /// </summary> /// <param name="bytes">The bytes to be sent.</param> /// <param name="offset">Offset in buffer.</param> /// <param name="length">Number of bytes to send.</param> /// <param name="asyncContinuation">The async continuation to be invoked after the buffer has been sent.</param> protected abstract void DoSend(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation); /// <summary> /// Parses the URI into an IP address. /// </summary> /// <param name="uri">The URI to parse.</param> /// <param name="addressFamily">The address family.</param> /// <returns>Parsed endpoint.</returns> protected virtual IPAddress ResolveIpAddress(Uri uri, AddressFamily addressFamily) { switch (uri.HostNameType) { case UriHostNameType.IPv4: case UriHostNameType.IPv6: return IPAddress.Parse(uri.Host); default: { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 var addresses = Dns.GetHostEntry(uri.Host).AddressList; // Dns.GetHostEntry returns IPv6 + IPv4 addresses, but Dns.GetHostAddresses() might only return IPv6 addresses #else var addresses = Dns.GetHostEntryAsync(uri.Host).ConfigureAwait(false).GetAwaiter().GetResult().AddressList; #endif if (addressFamily == AddressFamily.Unspecified && addresses.Length > 1) { Array.Sort(addresses, IPAddressComparer.Default); // Prioritize IPv4 addresses over IPv6, unless explicitly specified } foreach (var addr in addresses) { if (addr.AddressFamily == addressFamily || (addressFamily == AddressFamily.Unspecified && (addr.AddressFamily == AddressFamily.InterNetwork || addr.AddressFamily == AddressFamily.InterNetworkV6))) { return addr; } } throw new IOException($"Cannot resolve '{uri.Host}' to an address in '{addressFamily}'"); } } } public virtual ISocket CheckSocket() { return null; } private void Dispose(bool disposing) { if (disposing) { Close(ex => { }); } } private sealed class IPAddressComparer : System.Collections.Generic.IComparer<IPAddress> { public static readonly IPAddressComparer Default = new IPAddressComparer(); public int Compare(IPAddress x, IPAddress y) { return ((int)x.AddressFamily).CompareTo((int)y.AddressFamily); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LayoutRenderers { using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using NLog.Internal; using NLog.LayoutRenderers; using NSubstitute; using NSubstitute.ExceptionExtensions; using Xunit; public class LocalIpAddressLayoutRendererTests : NLogTestBase { private const string Mac1 = "F0-E1-D2-C3-B4-A5"; /// <summary> /// Integration test /// </summary> [Fact] public void LocalIpAddress_CurrentMachine_NotEmpty() { var ipAddressRenderer = new LocalIpAddressLayoutRenderer(); var result = ipAddressRenderer.Render(LogEventInfo.CreateNullEvent()); Assert.NotEmpty(result); } [Fact] public void LocalIpAddress_RendersSuccessfulIp() { // Arrange var ipString = "10.0.1.2"; var networkInterfaceRetrieverMock = new NetworkInterfaceRetrieverBuilder() .WithInterface(NetworkInterfaceType.Ethernet, Mac1) .WithIp(ipString) .Build(); var ipAddressRenderer = new LocalIpAddressLayoutRenderer(networkInterfaceRetrieverMock); // Act var result = ipAddressRenderer.Render(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal(ipString, result); } [Fact] public void LocalIpAddress_OneInterfaceWithMultipleIps_RendersFirstIp() { // Arrange var networkInterfaceRetrieverMock = new NetworkInterfaceRetrieverBuilder() .WithInterface(NetworkInterfaceType.Ethernet, Mac1) .WithIp("10.0.1.1") .WithIp("10.0.1.2") .WithIp("10.0.1.3") .Build(); var ipAddressRenderer = new LocalIpAddressLayoutRenderer(networkInterfaceRetrieverMock); // Act var result = ipAddressRenderer.Render(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal("10.0.1.1", result); } [Fact] public void LocalIpAddress_SkipsLoopback() { // Arrange var networkInterfaceRetrieverMock = new NetworkInterfaceRetrieverBuilder() .WithInterface(NetworkInterfaceType.Loopback, "F0-E0-D2-C3-B4-A5") .WithIp("1.2.3.4") .WithInterface(NetworkInterfaceType.Ethernet, Mac1) .WithIp("10.0.1.2") .Build(); var ipAddressRenderer = new LocalIpAddressLayoutRenderer(networkInterfaceRetrieverMock); // Act var result = ipAddressRenderer.Render(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal("10.0.1.2", result); } [Fact] public void LocalIpAddress_Multiple_TakesFirst() { // Arrange var networkInterfaceRetrieverMock = new NetworkInterfaceRetrieverBuilder() .WithInterface(NetworkInterfaceType.Ethernet, "F0-E0-D2-C3-B4-A5") .WithIp("10.0.1.1") .WithInterface(NetworkInterfaceType.Ethernet, Mac1) .WithIp("10.0.1.2") .Build(); var ipAddressRenderer = new LocalIpAddressLayoutRenderer(networkInterfaceRetrieverMock); // Act var result = ipAddressRenderer.Render(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal("10.0.1.1", result); } [Fact] public void LocalIpAddress_Multiple_TakesFirstUp() { // Arrange var networkInterfaceRetrieverMock = new NetworkInterfaceRetrieverBuilder() .WithInterface(NetworkInterfaceType.Ethernet, "F0-E0-D2-C3-B4-A5", OperationalStatus.Dormant) .WithIp("10.0.1.1") .WithInterface(NetworkInterfaceType.Ethernet, Mac1, OperationalStatus.Up) .WithIp("10.0.1.2") .WithInterface(NetworkInterfaceType.Ethernet, Mac1, OperationalStatus.Down) .WithIp("10.0.1.3", "10.0.1.0") .Build(); var ipAddressRenderer = new LocalIpAddressLayoutRenderer(networkInterfaceRetrieverMock); // Act var result = ipAddressRenderer.Render(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal("10.0.1.2", result); } [Fact] public void LocalIpAddress_Multiple_TakesFirstWithGatewayUp() { // Arrange var networkInterfaceRetrieverMock = new NetworkInterfaceRetrieverBuilder() .WithInterface(NetworkInterfaceType.Ethernet, "F0-E0-D2-C3-B4-A5", OperationalStatus.Dormant) .WithIp("10.0.1.1", "10.0.1.0") .WithInterface(NetworkInterfaceType.Ethernet, Mac1, OperationalStatus.Up) .WithIp("10.0.1.2") .WithInterface(NetworkInterfaceType.Ethernet, Mac1, OperationalStatus.Up) .WithIp("10.0.1.3", "10.0.1.0") .Build(); var ipAddressRenderer = new LocalIpAddressLayoutRenderer(networkInterfaceRetrieverMock); // Act var result = ipAddressRenderer.Render(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal("10.0.1.3", result); } [Fact] public void LocalIpAddress_Multiple_TakesFirstIpv4() { // Arrange var ipString = "10.0.1.2"; var networkInterfaceRetrieverMock = new NetworkInterfaceRetrieverBuilder() .WithInterface(NetworkInterfaceType.Ethernet, "F0-E0-D2-C3-B4-A5") .WithIp("fe80:0:0:0:200:f8ff:fe21:67cf") .WithInterface(NetworkInterfaceType.Ethernet, Mac1) .WithIp(ipString) .Build(); var ipAddressRenderer = new LocalIpAddressLayoutRenderer(networkInterfaceRetrieverMock); // Act var result = ipAddressRenderer.Render(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal(ipString, result); } [Fact] public void LocalIpAddress_Multiple_TakesFirstIpv6IfRequested() { // Arrange var ipv6 = "fe80::200:f8ff:fe21:67cf"; var networkInterfaceRetrieverMock = new NetworkInterfaceRetrieverBuilder() .WithInterface(NetworkInterfaceType.Ethernet, "F0-E0-D2-C3-B4-A5") .WithIp("1.0.10.11") .WithInterface(NetworkInterfaceType.Ethernet, Mac1) .WithIp(ipv6) .Build(); var ipAddressRenderer = new LocalIpAddressLayoutRenderer(networkInterfaceRetrieverMock) {AddressFamily = AddressFamily.InterNetworkV6}; // Act var result = ipAddressRenderer.Render(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal(ipv6, result); } [Fact] public void LocalIpAddress_RetrieverThrowsException_RenderEmptyString() { var networkInterfaceRetrieverMock = Substitute.For<INetworkInterfaceRetriever>(); networkInterfaceRetrieverMock.AllNetworkInterfaces.Throws(new Exception("oops")); var ipAddressRenderer = new LocalIpAddressLayoutRenderer(networkInterfaceRetrieverMock); // Act var result = ipAddressRenderer.Render(LogEventInfo.CreateNullEvent()); // Assert Assert.Equal(string.Empty, result); } } internal class NetworkInterfaceRetrieverBuilder { private readonly IDictionary<int, List<KeyValuePair<string, string>>> _ips = new Dictionary<int, List<KeyValuePair<string, string>>>(); private IList<(NetworkInterfaceType networkInterfaceType, string mac, OperationalStatus status)> _networkInterfaces = new List<(NetworkInterfaceType networkInterfaceType, string mac, OperationalStatus status)>(); private readonly INetworkInterfaceRetriever _networkInterfaceRetrieverMock; /// <inheritdoc/> public NetworkInterfaceRetrieverBuilder() { _networkInterfaceRetrieverMock = Substitute.For<INetworkInterfaceRetriever>(); } public NetworkInterfaceRetrieverBuilder WithInterface(NetworkInterfaceType networkInterfaceType, string mac, OperationalStatus status = OperationalStatus.Up) { _networkInterfaces.Add((networkInterfaceType, mac, status)); return this; } /// <summary> /// One or more ips for an interface added with <see cref="WithInterface"/> /// </summary> public NetworkInterfaceRetrieverBuilder WithIp(string ip, string gateway = null) { if (_networkInterfaces.Count == 0) { throw new Exception("add interface first"); } var key = _networkInterfaces.Count - 1; if (!_ips.ContainsKey(key)) { _ips.Add(key, new List<KeyValuePair<string,string>>()); } var list = _ips[key]; list.Add(new KeyValuePair<string, string>(ip, gateway)); return this; } public INetworkInterfaceRetriever Build() { var networkInterfaces = BuildAllNetworkInterfaces().ToArray(); _networkInterfaceRetrieverMock.AllNetworkInterfaces.Returns(networkInterfaces); return _networkInterfaceRetrieverMock; } private IEnumerable<NetworkInterface> BuildAllNetworkInterfaces() { for (var i = 0; i < _networkInterfaces.Count; i++) { var networkInterface = _networkInterfaces[i]; if (_ips.TryGetValue(i, out var ips)) { var networkInterfaceMock = BuildNetworkInterfaceMock(ips, networkInterface.mac, networkInterface.networkInterfaceType, networkInterface.status); networkInterfaceMock.Id.Returns($"#{i}"); networkInterfaceMock.Description.Returns("ips: " + string.Join(";", ips.ToArray())); yield return networkInterfaceMock; } } } private static NetworkInterface BuildNetworkInterfaceMock(IEnumerable<KeyValuePair<string, string>> ips, string mac, NetworkInterfaceType type, OperationalStatus status) { var networkInterfaceMock = Substitute.For<NetworkInterface>(); networkInterfaceMock.NetworkInterfaceType.Returns(type); networkInterfaceMock.OperationalStatus.Returns(status); networkInterfaceMock.GetPhysicalAddress().Returns(PhysicalAddress.Parse(mac)); var unicastIpAddressInformations = new List<UnicastIPAddressInformation>(BuildUnicastInfoMocks(ips.Select(p => p.Key))); var gatewayIpAddressInformations = new List<GatewayIPAddressInformation>(BuildGatewayInfoMocks(ips.Select(p => p.Value))); var unicastIpAddressInformationCollection = Substitute.For<UnicastIPAddressInformationCollection>(); unicastIpAddressInformationCollection.GetEnumerator().Returns(unicastIpAddressInformations.GetEnumerator()); unicastIpAddressInformationCollection.Count.Returns(unicastIpAddressInformations.Count); var gatewayIpAddressInformationCollection = Substitute.For<GatewayIPAddressInformationCollection>(); gatewayIpAddressInformationCollection.GetEnumerator().Returns(gatewayIpAddressInformations.GetEnumerator()); gatewayIpAddressInformationCollection.Count.Returns(gatewayIpAddressInformations.Count); var interfacePropertiesMock = Substitute.For<IPInterfaceProperties>(); interfacePropertiesMock.UnicastAddresses.Returns(unicastIpAddressInformationCollection); interfacePropertiesMock.GatewayAddresses.Returns(gatewayIpAddressInformationCollection); networkInterfaceMock.GetIPProperties().Returns(interfacePropertiesMock); return networkInterfaceMock; } private static IEnumerable<UnicastIPAddressInformation> BuildUnicastInfoMocks(IEnumerable<string> ips) { foreach (var ip in ips) { var ipInfoMock = Substitute.For<UnicastIPAddressInformation>(); ipInfoMock.Address.Returns(IPAddress.Parse(ip)); yield return ipInfoMock; } } private static IEnumerable<GatewayIPAddressInformation> BuildGatewayInfoMocks(IEnumerable<string> ips) { foreach (var ip in ips) { if (string.IsNullOrEmpty(ip)) continue; var ipInfoMock = Substitute.For<GatewayIPAddressInformation>(); ipInfoMock.Address.Returns(IPAddress.Parse(ip)); yield return ipInfoMock; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; /// <summary> /// Represents a factory of named items (such as targets, layouts, layout renderers, etc.). /// </summary> /// <typeparam name="TInstanceType">Base type for each item instance.</typeparam> /// <typeparam name="TDefinitionType">Item definition type (typically <see cref="System.Type"/>).</typeparam> [Obsolete("Instead use NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public interface INamedItemFactory<TInstanceType, TDefinitionType> where TInstanceType : class { /// <summary> /// Registers new item definition. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="itemDefinition">Item definition.</param> void RegisterDefinition(string itemName, TDefinitionType itemDefinition); /// <summary> /// Tries to get registered item definition. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="result">Reference to a variable which will store the item definition.</param> /// <returns>Item definition.</returns> bool TryGetDefinition(string itemName, out TDefinitionType result); /// <summary> /// Creates item instance. /// </summary> /// <param name="itemName">Name of the item.</param> /// <returns>Newly created item instance.</returns> TInstanceType CreateInstance(string itemName); /// <summary> /// Tries to create an item instance. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="result">The result.</param> /// <returns>True if instance was created successfully, false otherwise.</returns> bool TryCreateInstance(string itemName, out TInstanceType result); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal.NetworkSenders { using System; using System.IO; using System.Net; using System.Net.Sockets; using NLog.Common; /// <summary> /// Sends messages over the network as UDP datagrams. /// </summary> internal class UdpNetworkSender : QueuedNetworkSender { private ISocket _socket; private EndPoint _endpoint; private readonly EventHandler<SocketAsyncEventArgs> _socketOperationCompletedAsync; private AsyncHelpersTask? _asyncBeginRequest; /// <summary> /// Initializes a new instance of the <see cref="UdpNetworkSender"/> class. /// </summary> /// <param name="url">URL. Must start with udp://.</param> /// <param name="addressFamily">The address family.</param> public UdpNetworkSender(string url, AddressFamily addressFamily) : base(url) { AddressFamily = addressFamily; _socketOperationCompletedAsync = SocketOperationCompletedAsync; } internal AddressFamily AddressFamily { get; set; } internal int MaxMessageSize { get; set; } /// <summary> /// Creates the socket. /// </summary> /// <param name="ipAddress">The IP address.</param> /// <returns>Implementation of <see cref="ISocket"/> to use.</returns> protected internal virtual ISocket CreateSocket(IPAddress ipAddress) { var proxy = new SocketProxy(ipAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); if (ipAddress.AddressFamily != AddressFamily.InterNetworkV6 && ipAddress.Equals(IPAddress.Broadcast)) { proxy.UnderlyingSocket.EnableBroadcast = true; } return proxy; } protected override void DoInitialize() { var uri = new Uri(Address); var address = ResolveIpAddress(uri, AddressFamily); _endpoint = new IPEndPoint(address, uri.Port); _socket = CreateSocket(address); } protected override void DoClose(AsyncContinuation continuation) { base.DoClose(ex => CloseSocket(continuation, ex)); } private void CloseSocket(AsyncContinuation continuation, Exception pendingException) { try { var sock = _socket; _socket = null; sock?.Close(); continuation(pendingException); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } continuation(exception); } } protected override void BeginRequest(NetworkRequestArgs eventArgs) { var socketEventArgs = new SocketAsyncEventArgs(); socketEventArgs.Completed += _socketOperationCompletedAsync; socketEventArgs.RemoteEndPoint = _endpoint; SetSocketNetworkRequest(socketEventArgs, eventArgs); // Schedule async network operation to avoid blocking socket-operation (Allow adding more request) if (_asyncBeginRequest is null) _asyncBeginRequest = new AsyncHelpersTask(BeginRequestAsync); AsyncHelpers.StartAsyncTask(_asyncBeginRequest.Value, socketEventArgs); } private void BeginRequestAsync(object state) { BeginSocketRequest((SocketAsyncEventArgs)state); } private void BeginSocketRequest(SocketAsyncEventArgs args) { bool asyncOperation = false; do { try { asyncOperation = _socket.SendToAsync(args); } catch (SocketException ex) { InternalLogger.Error(ex, "NetworkTarget: Error sending udp request"); args.SocketError = ex.SocketErrorCode; } catch (Exception ex) { InternalLogger.Error(ex, "NetworkTarget: Error sending udp request"); if (ex.InnerException is SocketException socketException) args.SocketError = socketException.SocketErrorCode; else args.SocketError = SocketError.OperationAborted; } args = asyncOperation ? null : SocketOperationCompleted(args); } while (args != null); } private void SetSocketNetworkRequest(SocketAsyncEventArgs socketEventArgs, NetworkRequestArgs networkRequest) { var messageLength = MaxMessageSize > 0 ? Math.Min(networkRequest.RequestBufferLength, MaxMessageSize) : networkRequest.RequestBufferLength; socketEventArgs.SetBuffer(networkRequest.RequestBuffer, networkRequest.RequestBufferOffset, messageLength); socketEventArgs.UserToken = networkRequest.AsyncContinuation; } private void SocketOperationCompletedAsync(object sender, SocketAsyncEventArgs args) { var nextRequest = SocketOperationCompleted(args); if (nextRequest != null) { BeginSocketRequest(nextRequest); } } private SocketAsyncEventArgs SocketOperationCompleted(SocketAsyncEventArgs args) { Exception socketException = null; if (args.SocketError != SocketError.Success) { socketException = new IOException($"Error: {args.SocketError.ToString()}, Address: {Address}"); } if (socketException is null && (args.Buffer.Length - args.Offset) > MaxMessageSize && MaxMessageSize > 0) { var messageLength = Math.Min(args.Buffer.Length - args.Offset - MaxMessageSize, MaxMessageSize); args.SetBuffer(args.Buffer, args.Offset + MaxMessageSize, messageLength); return args; } var asyncContinuation = args.UserToken as AsyncContinuation; var nextRequest = EndRequest(asyncContinuation, socketException); if (nextRequest.HasValue) { SetSocketNetworkRequest(args, nextRequest.Value); return args; } else { args.Completed -= _socketOperationCompletedAsync; args.Dispose(); return null; } } public override ISocket CheckSocket() { if (_socket is null) { DoInitialize(); } return _socket; } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.MessageTemplates; using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Xunit; namespace NLog.UnitTests.MessageTemplates { public class ValueFormatterTest : NLogTestBase { enum TestData { Foo,Bar }; private class Test : IFormattable, IConvertible { public Test() { Str = "Test"; Integer = 1; } public Test(TypeCode typeCode) : this() { TypeCode = typeCode; } public TestData Data { get; set; } public string Str { get; set; } public int Integer { get; set; } public TypeCode TypeCode { get; set; } public TypeCode GetTypeCode() { return TypeCode; } public bool ToBoolean(IFormatProvider provider) { return true; } public byte ToByte(IFormatProvider provider) { return 1; } public char ToChar(IFormatProvider provider) { return 't'; } public DateTime ToDateTime(IFormatProvider provider) { return new DateTime(2019, 7, 28); } public decimal ToDecimal(IFormatProvider provider) { return Integer; } public double ToDouble(IFormatProvider provider) { return Integer; } public short ToInt16(IFormatProvider provider) { return 1; } public int ToInt32(IFormatProvider provider) { return Integer; } public long ToInt64(IFormatProvider provider) { return Integer; } public sbyte ToSByte(IFormatProvider provider) { return 1; } public float ToSingle(IFormatProvider provider) { return Integer; } public string ToString(string format, IFormatProvider formatProvider) { return Str; } public string ToString(IFormatProvider provider) { return Str; } public object ToType(Type conversionType, IFormatProvider provider) { return Integer; } public ushort ToUInt16(IFormatProvider provider) { return 1; } public uint ToUInt32(IFormatProvider provider) { return 1; } public ulong ToUInt64(IFormatProvider provider) { return 1; } } private class Test1 { public Test1() { Str = "Test"; Integer = 1; } public string Str { get; set; } public int Integer { get; set; } } private class Test2 { public Test2() { Str = "Test"; Integer = 1; } public string Str { get; set; } public int Integer { get; set; } } private class RecursiveTest { public RecursiveTest(int integer) { Integer = integer + 1; } public RecursiveTest Next => new RecursiveTest(Integer); public int Integer { get; set; } } private static ValueFormatter CreateValueFormatter() { return new ValueFormatter(LogManager.LogFactory.ServiceRepository); } [Fact] public void TestSerialisationOfStringToJsonIsSuccessful() { var str = "Test"; StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(str, string.Empty, CaptureType.Serialize, null, builder); Assert.True(result); Assert.Equal("\"Test\"", builder.ToString()); } [Fact] public void TestSerialisationOfClassObjectToJsonIsSuccessful() { var @class = new Test2(); StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(@class, string.Empty, CaptureType.Serialize, null, builder); Assert.True(result); Assert.Equal("{\"Str\":\"Test\", \"Integer\":1}", builder.ToString()); } [Fact] public void TestSerialisationOfRecursiveClassObjectToJsonIsSuccessful() { var @class = new RecursiveTest(0); StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(@class, string.Empty, CaptureType.Serialize, null, builder); Assert.True(result); var actual = builder.ToString(); var deepestInteger = @"""Integer"":10"; Assert.Contains(deepestInteger, actual); var deepestNext = @"""Next"":""NLog.UnitTests.MessageTemplates.ValueFormatterTest+RecursiveTest"""; Assert.Contains(deepestNext, actual); } [Fact] public void TestStringifyOfStringIsSuccessful() { var @class = "str"; StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(@class, string.Empty, CaptureType.Stringify, new CultureInfo("fr-FR"), builder); Assert.True(result); Assert.Equal("\"str\"", builder.ToString()); } [Fact] public void TestStringifyOfIFormatableObjectIsSuccessful() { var @class = new Test(); StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(@class, string.Empty, CaptureType.Stringify, new CultureInfo("fr-FR"), builder); Assert.True(result); Assert.Equal("\"Test\"", builder.ToString()); } [Fact] public void TestStringifyOfNonIFormatableObjectIsSuccessful() { var @class = new Test1(); StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(@class, string.Empty, CaptureType.Stringify, new CultureInfo("fr-FR"), builder); Assert.True(result); var expectedValue = $"\"{typeof(Test1).FullName}\""; Assert.Equal(expectedValue, builder.ToString()); } [Fact] public void TestSerializationOfListObjectIsSuccessful() { var list = new List<int>() { 1, 2, 3, 4, 5, 6 }; StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(list, string.Empty, CaptureType.Normal, new CultureInfo("fr-FR"), builder); Assert.True(result); Assert.Equal("1, 2, 3, 4, 5, 6", builder.ToString()); } [Fact] public void TestSerializationOfDictionaryObjectIsSuccessful() { var list = new Dictionary<int, object>() { { 1, new Test() }, { 2, new Test1() } }; StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(list, string.Empty, CaptureType.Normal, new CultureInfo("fr-FR"), builder); Assert.True(result); Assert.Equal($"1=Test, 2={typeof(Test1).FullName}", builder.ToString()); } [Fact] public void TestSerializationOfCollectionOfListObjectWithDepth2IsNotSuccessful() { var list = new List<List<List<List<int>>>>() { new List<List<List<int>>>() { new List<List<int>>() { new List<int>() { 1, 2 }, new List<int>() { 3, 4 } }, new List<List<int>>() { new List<int>() { 4, 5 }, new List<int>() { 6, 7 } } } }; StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(list, string.Empty, CaptureType.Normal, new CultureInfo("fr-FR"), builder); Assert.True(result); Assert.NotEqual("1,2,3,4,5,6,7", builder.ToString()); } [Fact] public void TestSerializationWillbeSkippedForElementsThatHaveRepeatedElements() { var list = new List<List<List<List<int>>>>() { new List<List<List<int>>>() { new List<List<int>>() { new List<int>() { 1, 2 }, new List<int>() { 1, 2 } }, new List<List<int>>() { new List<int>() { 1, 2 }, new List<int>() { 1, 2 } } } }; StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(list, string.Empty, CaptureType.Normal, new CultureInfo("fr-FR"), builder); Assert.True(result); Assert.NotEqual("1,2", builder.ToString()); } [Theory] [InlineData(CaptureType.Normal, "NULL")] [InlineData(CaptureType.Serialize, "null")] [InlineData(CaptureType.Stringify, "\"\"")] public void TestSerializationWillBeSuccessfulForNull(CaptureType captureType, string expected) { StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(null, string.Empty, captureType, null, builder); Assert.True(result); Assert.Equal(expected, builder.ToString()); } [Fact] public void TestSerializationWillBeSuccessfulForNullObjects() { object list = null; StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(list, string.Empty, CaptureType.Normal, new CultureInfo("fr-FR"), builder); Assert.True(result); Assert.Equal("NULL", builder.ToString()); } [Fact] public void TestSerializationOfStringIsSuccessful() { var @class = "str"; StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(@class, string.Empty, CaptureType.Normal, new CultureInfo("fr-FR"), builder); Assert.True(result); Assert.Equal("\"str\"", builder.ToString()); } [Fact] public void TestSerialisationOfIConvertibleObjectIsSuccessful() { var @class = new Test(TypeCode.Object); StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(@class, string.Empty, CaptureType.Normal, new CultureInfo("fr-FR"), builder); Assert.True(result); Assert.Equal("Test", builder.ToString()); } [Fact] public void TestSerialisationOfIConvertibleStringObjectIsSuccessful() { var @class = new Test(TypeCode.String); StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(@class, string.Empty, CaptureType.Normal, new CultureInfo("fr-FR"), builder); Assert.True(result); var expectedValue = $"\"{typeof(Test).FullName}\""; Assert.Equal(expectedValue, builder.ToString()); } [Fact] public void TestSerialisationOfIConvertibleBooleanObjectIsSuccessful() { var @class = new Test(TypeCode.Boolean); StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(@class, string.Empty, CaptureType.Normal, new CultureInfo("fr-FR"), builder); Assert.True(result); Assert.Equal("true", builder.ToString()); } [Fact] public void TestSerialisationOfIConvertibleCharObjectIsSuccessful() { var @class = new Test(TypeCode.Char); StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(@class, string.Empty, CaptureType.Normal, new CultureInfo("fr-FR"), builder); Assert.True(result); Assert.Equal("\"t\"", builder.ToString()); } [Theory] [InlineData(TypeCode.Byte)] [InlineData(TypeCode.SByte)] [InlineData(TypeCode.Int16)] [InlineData(TypeCode.Int32)] [InlineData(TypeCode.Int64)] [InlineData(TypeCode.UInt16)] [InlineData(TypeCode.UInt32)] [InlineData(TypeCode.UInt64)] public void TestSerialisationOfIConvertibleNumericObjectIsSuccessful(TypeCode code) { var @class = new Test(code); StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(@class, string.Empty, CaptureType.Normal, new CultureInfo("fr-FR"), builder); Assert.True(result); Assert.Equal("1", builder.ToString()); } [Fact] public void TestSerialisationOfIConvertibleEnumObjectIsSuccessful() { var @class = new Test(TypeCode.Byte); StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(@class.Data, string.Empty, CaptureType.Normal, new CultureInfo("fr-FR"), builder); Assert.True(result); Assert.Equal("Foo", builder.ToString()); } [Fact] public void TestSerialisationOfIConvertibleDateTimeObjectIsSuccessful() { var @class = new Test(TypeCode.DateTime); StringBuilder builder = new StringBuilder(); var result = CreateValueFormatter().FormatValue(@class, string.Empty, CaptureType.Normal, new CultureInfo("fr-FR"), builder); Assert.True(result); Assert.Equal("Test", builder.ToString()); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Diagnostics; using System.Reflection; internal class CallSiteInformation { /// <summary> /// Sets the stack trace for the event info. /// </summary> /// <param name="stackTrace">The stack trace.</param> /// <param name="userStackFrame">Index of the first user stack frame within the stack trace.</param> /// <param name="loggerType">Type of the logger or logger wrapper. This is still Logger if it's a subclass of Logger.</param> public void SetStackTrace(StackTrace stackTrace, int? userStackFrame = null, Type loggerType = null) { StackTrace = stackTrace; if (!userStackFrame.HasValue && stackTrace != null) { var stackFrames = stackTrace.GetFrames(); var firstUserFrame = loggerType != null ? FindCallingMethodOnStackTrace(stackFrames, loggerType) : 0; var firstLegacyUserFrame = firstUserFrame.HasValue ? SkipToUserStackFrameLegacy(stackFrames, firstUserFrame.Value) : firstUserFrame; UserStackFrameNumber = firstUserFrame ?? 0; UserStackFrameNumberLegacy = firstLegacyUserFrame != firstUserFrame ? firstLegacyUserFrame : null; } else { UserStackFrameNumber = userStackFrame ?? 0; UserStackFrameNumberLegacy = null; } } /// <summary> /// Sets the details retrieved from the Caller Information Attributes /// </summary> /// <param name="callerClassName"></param> /// <param name="callerMethodName"></param> /// <param name="callerFilePath"></param> /// <param name="callerLineNumber"></param> public void SetCallerInfo(string callerClassName, string callerMethodName, string callerFilePath, int callerLineNumber) { CallerClassName = callerClassName; CallerMethodName = callerMethodName; CallerFilePath = callerFilePath; CallerLineNumber = callerLineNumber; } /// <summary> /// Gets the stack frame of the method that did the logging. /// </summary> public StackFrame UserStackFrame => StackTrace?.GetFrame(UserStackFrameNumberLegacy ?? UserStackFrameNumber); /// <summary> /// Gets the number index of the stack frame that represents the user /// code (not the NLog code). /// </summary> public int UserStackFrameNumber { get; private set; } /// <summary> /// Legacy attempt to skip async MoveNext, but caused source file line number to be lost /// </summary> public int? UserStackFrameNumberLegacy { get; private set; } /// <summary> /// Gets the entire stack trace. /// </summary> public StackTrace StackTrace { get; private set; } public MethodBase GetCallerStackFrameMethod(int skipFrames) { StackFrame frame = StackTrace?.GetFrame(UserStackFrameNumber + skipFrames); return StackTraceUsageUtils.GetStackMethod(frame); } public string GetCallerClassName(MethodBase method, bool includeNameSpace, bool cleanAsyncMoveNext, bool cleanAnonymousDelegates) { if (!string.IsNullOrEmpty(CallerClassName)) { if (includeNameSpace) { return CallerClassName; } else { int lastDot = CallerClassName.LastIndexOf('.'); if (lastDot < 0 || lastDot >= CallerClassName.Length - 1) return CallerClassName; else return CallerClassName.Substring(lastDot + 1); } } method = method ?? GetCallerStackFrameMethod(0); if (method is null) return string.Empty; cleanAsyncMoveNext = cleanAsyncMoveNext || UserStackFrameNumberLegacy.HasValue; cleanAnonymousDelegates = cleanAnonymousDelegates || UserStackFrameNumberLegacy.HasValue; return StackTraceUsageUtils.GetStackFrameMethodClassName(method, includeNameSpace, cleanAsyncMoveNext, cleanAnonymousDelegates) ?? string.Empty; } public string GetCallerMethodName(MethodBase method, bool includeMethodInfo, bool cleanAsyncMoveNext, bool cleanAnonymousDelegates) { if (!string.IsNullOrEmpty(CallerMethodName)) return CallerMethodName; method = method ?? GetCallerStackFrameMethod(0); if (method is null) return string.Empty; cleanAsyncMoveNext = cleanAsyncMoveNext || UserStackFrameNumberLegacy.HasValue; cleanAnonymousDelegates = cleanAnonymousDelegates || UserStackFrameNumberLegacy.HasValue; return StackTraceUsageUtils.GetStackFrameMethodName(method, includeMethodInfo, cleanAsyncMoveNext, cleanAnonymousDelegates) ?? string.Empty; } public string GetCallerFilePath(int skipFrames) { if (!string.IsNullOrEmpty(CallerFilePath)) return CallerFilePath; StackFrame frame = StackTrace?.GetFrame(UserStackFrameNumber + skipFrames); return frame?.GetFileName() ?? string.Empty; } public int GetCallerLineNumber(int skipFrames) { if (CallerLineNumber.HasValue) return CallerLineNumber.Value; StackFrame frame = StackTrace?.GetFrame(UserStackFrameNumber + skipFrames); return frame?.GetFileLineNumber() ?? 0; } public string CallerClassName { get; internal set; } public string CallerMethodName { get; private set; } public string CallerFilePath { get; private set; } public int? CallerLineNumber { get; private set; } /// <summary> /// Finds first user stack frame in a stack trace /// </summary> /// <param name="stackFrames">The stack trace of the logging method invocation</param> /// <param name="loggerType">Type of the logger or logger wrapper. This is still Logger if it's a subclass of Logger.</param> /// <returns>Index of the first user stack frame or 0 if all stack frames are non-user</returns> private static int? FindCallingMethodOnStackTrace(StackFrame[] stackFrames, Type loggerType) { if (stackFrames is null || stackFrames.Length == 0) return null; int? firstStackFrameAfterLogger = null; int? firstUserStackFrame = null; for (int i = 0; i < stackFrames.Length; ++i) { var stackFrame = stackFrames[i]; if (SkipAssembly(stackFrame)) continue; if (!firstUserStackFrame.HasValue) firstUserStackFrame = i; if (IsLoggerType(stackFrame, loggerType)) { firstStackFrameAfterLogger = null; continue; } if (!firstStackFrameAfterLogger.HasValue) firstStackFrameAfterLogger = i; } return firstStackFrameAfterLogger ?? firstUserStackFrame; } /// <summary> /// This is only done for legacy reason, as the correct method-name and line-number should be extracted from the MoveNext-StackFrame /// </summary> /// <param name="stackFrames">The stack trace of the logging method invocation</param> /// <param name="firstUserStackFrame">Starting point for skipping async MoveNext-frames</param> private static int SkipToUserStackFrameLegacy(StackFrame[] stackFrames, int firstUserStackFrame) { #if !NET35 && !NET40 for (int i = firstUserStackFrame; i < stackFrames.Length; ++i) { var stackFrame = stackFrames[i]; if (SkipAssembly(stackFrame)) continue; var stackMethod = StackTraceUsageUtils.GetStackMethod(stackFrame); if (stackMethod?.Name == "MoveNext" && stackFrames.Length > i) { var nextStackFrame = stackFrames[i + 1]; var nextStackMethod = StackTraceUsageUtils.GetStackMethod(nextStackFrame); var declaringType = nextStackMethod?.DeclaringType; if (declaringType?.Namespace == "System.Runtime.CompilerServices" || declaringType == typeof(System.Threading.ExecutionContext)) { //async, search further continue; } } return i; } #endif return firstUserStackFrame; } /// <summary> /// Assembly to skip? /// </summary> /// <param name="frame">Find assembly via this frame. </param> /// <returns><c>true</c>, we should skip.</returns> private static bool SkipAssembly(StackFrame frame) { var assembly = StackTraceUsageUtils.LookupAssemblyFromStackFrame(frame); return assembly is null || LogManager.IsHiddenAssembly(assembly); } /// <summary> /// Is this the type of the logger? /// </summary> /// <param name="frame">get type of this logger in this frame.</param> /// <param name="loggerType">Type of the logger.</param> /// <returns></returns> private static bool IsLoggerType(StackFrame frame, Type loggerType) { var method = StackTraceUsageUtils.GetStackMethod(frame); Type declaringType = method?.DeclaringType; var isLoggerType = declaringType != null && (loggerType == declaringType || declaringType.IsSubclassOf(loggerType) || loggerType.IsAssignableFrom(declaringType)); return isLoggerType; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Config { using System; using System.Globalization; using System.Threading; using NLog.Config; using NLog.LayoutRenderers; using NLog.Targets; using Xunit; public class CultureInfoTests : NLogTestBase { [Fact] public void WhenInvariantCultureDefinedThenDefaultCultureIsInvariantCulture() { var configuration = XmlLoggingConfiguration.CreateFromXmlString("<nlog useInvariantCulture='true'></nlog>"); Assert.Equal(CultureInfo.InvariantCulture, configuration.DefaultCultureInfo); } [Fact] public void DifferentConfigurations_UseDifferentDefaultCulture() { var currentCulture = CultureInfo.CurrentCulture; try { // set the current thread culture to be definitely different from the InvariantCulture Thread.CurrentThread.CurrentCulture = GetCultureInfo("de-DE"); var configurationTemplate = @"<nlog useInvariantCulture='{0}'> <targets> <target name='debug' type='Debug' layout='${{message}}' /> </targets> <rules> <logger name='*' writeTo='debug'/> </rules> </nlog>"; // configuration with current culture var logFactory1 = new LogFactory(); var configuration1 = XmlLoggingConfiguration.CreateFromXmlString(string.Format(configurationTemplate, false), logFactory1); Assert.Null(configuration1.DefaultCultureInfo); logFactory1.Configuration = configuration1; // configuration with invariant culture var logFactory2 = new LogFactory(); var configuration2 = XmlLoggingConfiguration.CreateFromXmlString(string.Format(configurationTemplate, true), logFactory2); Assert.Equal(CultureInfo.InvariantCulture, configuration2.DefaultCultureInfo); logFactory2.Configuration = configuration2; Assert.NotEqual(configuration1.DefaultCultureInfo, configuration2.DefaultCultureInfo); var testNumber = 3.14; var testDate = DateTime.Now; const string formatString = "{0},{1:d}"; AssertMessageFormattedWithCulture(logFactory1, CultureInfo.CurrentCulture, formatString, testNumber, testDate); AssertMessageFormattedWithCulture(logFactory2, CultureInfo.InvariantCulture, formatString, testNumber, testDate); } finally { // restore current thread culture Thread.CurrentThread.CurrentCulture = currentCulture; } } private static void AssertMessageFormattedWithCulture(LogFactory logFactory, CultureInfo culture, string formatString, params object[] parameters) { var expected = string.Format(culture, formatString, parameters); var logger = logFactory.GetLogger("test"); logger.Debug(formatString, parameters); Assert.Equal(expected, GetDebugLastMessage("debug", logFactory)); } [Fact] public void EventPropRendererCultureTest() { string cultureName = "de-DE"; string expected = "1,23"; // with decimal comma var logEventInfo = CreateLogEventInfo(cultureName); logEventInfo.Properties["ADouble"] = 1.23; var renderer = new EventPropertiesLayoutRenderer(); renderer.Item = "ADouble"; string output = renderer.Render(logEventInfo); Assert.Equal(expected, output); } [Fact] public void ProcessInfoLayoutRendererCultureTest() { string cultureName = "de-DE"; string expected = "."; // dot as date separator (01.10.2008) string output = string.Empty; var logEventInfo = CreateLogEventInfo(cultureName); if (IsLinux()) { Console.WriteLine("[SKIP] CultureInfoTests.ProcessInfoLayoutRendererCultureTest because we are running in Travis"); } else { var renderer = new ProcessInfoLayoutRenderer(); renderer.Property = ProcessInfoProperty.StartTime; renderer.Format = "d"; output = renderer.Render(logEventInfo); Assert.Contains(expected, output); Assert.DoesNotContain("/", output); Assert.DoesNotContain("-", output); } var renderer2 = new ProcessInfoLayoutRenderer(); renderer2.Property = ProcessInfoProperty.PriorityClass; renderer2.Format = "d"; output = renderer2.Render(logEventInfo); Assert.True(output.Length >= 1); Assert.True("012345678".IndexOf(output[0]) > 0); } [Fact] public void AllEventPropRendererCultureTest() { string cultureName = "de-DE"; string expected = "ADouble=1,23"; // with decimal comma var logEventInfo = CreateLogEventInfo(cultureName); logEventInfo.Properties["ADouble"] = 1.23; var renderer = new AllEventPropertiesLayoutRenderer(); string output = renderer.Render(logEventInfo); Assert.Equal(expected, output); } private static LogEventInfo CreateLogEventInfo(string cultureName) { var logEventInfo = new LogEventInfo( LogLevel.Info, "SomeName", CultureInfo.GetCultureInfo(cultureName), "SomeMessage", null); return logEventInfo; } /// <summary> /// expected: exactly the same exception message + stack trace regardless of the CurrentUICulture /// </summary> [Fact] public void ExceptionTest() { var target = new MemoryTarget { Layout = @"${exception:format=tostring}" }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(target); }).GetCurrentClassLogger(); try { throw new InvalidOperationException(); } catch (Exception ex) { Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US", false); Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false); logger.Error(ex, ""); #if !NETSTANDARD Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE", false); Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE", false); #endif logger.Error(ex, ""); Assert.Equal(2, target.Logs.Count); Assert.NotNull(target.Logs[0]); Assert.NotNull(target.Logs[1]); Assert.Equal(target.Logs[0], target.Logs[1]); } } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using JetBrains.Annotations; using NLog.Config; using NLog.Internal; using NLog.Common; using NLog.Targets; /// <summary> /// Abstract interface that layouts must implement. /// </summary> [NLogConfigurationItem] public abstract class Layout : ISupportsInitialize, IRenderable { /// <summary> /// Is this layout initialized? See <see cref="Initialize(NLog.Config.LoggingConfiguration)"/> /// </summary> internal bool IsInitialized; private bool _scannedForObjects; /// <summary> /// Gets a value indicating whether this layout is thread-agnostic (can be rendered on any thread). /// </summary> /// <remarks> /// Layout is thread-agnostic if it has been marked with [ThreadAgnostic] attribute and all its children are /// like that as well. /// /// Thread-agnostic layouts only use contents of <see cref="LogEventInfo"/> for its output. /// </remarks> internal bool ThreadAgnostic { get; set; } internal bool MutableUnsafe { get; set; } /// <summary> /// Gets the level of stack trace information required for rendering. /// </summary> internal StackTraceUsage StackTraceUsage { get; set; } /// <summary> /// Gets the logging configuration this target is part of. /// </summary> [CanBeNull] protected internal LoggingConfiguration LoggingConfiguration { get; private set; } /// <summary> /// Converts a given text to a <see cref="Layout" />. /// </summary> /// <param name="text">Text to be converted.</param> /// <returns><see cref="SimpleLayout"/> object represented by the text.</returns> public static implicit operator Layout([Localizable(false)] string text) { return FromString(text, ConfigurationItemFactory.Default); } /// <summary> /// Implicitly converts the specified string to a <see cref="SimpleLayout"/>. /// </summary> /// <param name="layoutText">The layout string.</param> /// <returns>Instance of <see cref="SimpleLayout"/>.</returns>' public static Layout FromString([Localizable(false)] string layoutText) { return FromString(layoutText, ConfigurationItemFactory.Default); } /// <summary> /// Implicitly converts the specified string to a <see cref="SimpleLayout"/>. /// </summary> /// <param name="layoutText">The layout string.</param> /// <param name="configurationItemFactory">The NLog factories to use when resolving layout renderers.</param> /// <returns>Instance of <see cref="SimpleLayout"/>.</returns> public static Layout FromString([Localizable(false)] string layoutText, ConfigurationItemFactory configurationItemFactory) { return new SimpleLayout(layoutText, configurationItemFactory); } /// <summary> /// Implicitly converts the specified string to a <see cref="SimpleLayout"/>. /// </summary> /// <param name="layoutText">The layout string.</param> /// <param name="throwConfigExceptions">Whether <see cref="NLogConfigurationException"/> should be thrown on parse errors (false = replace unrecognized tokens with a space).</param> /// <returns>Instance of <see cref="SimpleLayout"/>.</returns> public static Layout FromString([Localizable(false)] string layoutText, bool throwConfigExceptions) { try { return new SimpleLayout(layoutText, ConfigurationItemFactory.Default, throwConfigExceptions); } catch (NLogConfigurationException) { throw; } catch (Exception ex) { if (!throwConfigExceptions || ex.MustBeRethrownImmediately()) throw; throw new NLogConfigurationException($"Invalid Layout: {layoutText}", ex); } } /// <summary> /// Create a <see cref="SimpleLayout"/> from a lambda method. /// </summary> /// <param name="layoutMethod">Method that renders the layout.</param> /// <param name="options">Tell if method is safe for concurrent threading.</param> /// <returns>Instance of <see cref="SimpleLayout"/>.</returns> public static Layout FromMethod(Func<LogEventInfo, object> layoutMethod, LayoutRenderOptions options = LayoutRenderOptions.None) { Guard.ThrowIfNull(layoutMethod); #if !NETSTANDARD1_3 && !NETSTANDARD1_5 var name = $"{layoutMethod.Method?.DeclaringType?.ToString()}.{layoutMethod.Method?.Name}"; #else var name = $"{layoutMethod.Target?.ToString()}"; #endif var layoutRenderer = CreateFuncLayoutRenderer((l, c) => layoutMethod(l), options, name); return new SimpleLayout(new[] { layoutRenderer }, layoutRenderer.LayoutRendererName, ConfigurationItemFactory.Default); } internal static LayoutRenderers.FuncLayoutRenderer CreateFuncLayoutRenderer(Func<LogEventInfo, LoggingConfiguration, object> layoutMethod, LayoutRenderOptions options, string name) { if ((options & LayoutRenderOptions.ThreadAgnostic) == LayoutRenderOptions.ThreadAgnostic) return new LayoutRenderers.FuncThreadAgnosticLayoutRenderer(name, layoutMethod); else return new LayoutRenderers.FuncLayoutRenderer(name, layoutMethod); } /// <summary> /// Precalculates the layout for the specified log event and stores the result /// in per-log event cache. /// /// Only if the layout doesn't have [ThreadAgnostic] and doesn't contain layouts with [ThreadAgnostic]. /// </summary> /// <param name="logEvent">The log event.</param> /// <remarks> /// Calling this method enables you to store the log event in a buffer /// and/or potentially evaluate it in another thread even though the /// layout may contain thread-dependent renderer. /// </remarks> public virtual void Precalculate(LogEventInfo logEvent) { if (!ThreadAgnostic || MutableUnsafe) { using (var localTarget = new AppendBuilderCreator(true)) { RenderAppendBuilder(logEvent, localTarget.Builder, true); } } } /// <summary> /// Renders formatted output using the log event as context. /// </summary> /// <remarks>Inside a <see cref="Target"/>, <see cref="Target.RenderLogEvent"/> is preferred for performance reasons.</remarks> /// <param name="logEvent">The logging event.</param> /// <returns>The formatted output as string.</returns> public string Render(LogEventInfo logEvent) { if (!IsInitialized) { Initialize(LoggingConfiguration); } if (!ThreadAgnostic || MutableUnsafe) { object cachedValue; if (logEvent.TryGetCachedLayoutValue(this, out cachedValue)) { return cachedValue?.ToString() ?? string.Empty; } } string layoutValue = GetFormattedMessage(logEvent) ?? string.Empty; if (!ThreadAgnostic || MutableUnsafe) { // Would be nice to only do this in Precalculate(), but we need to ensure internal cache // is updated for custom Layouts that overrides Precalculate (without calling base.Precalculate) logEvent.AddCachedLayoutValue(this, layoutValue); } return layoutValue; } /// <summary> /// Optimized version of <see cref="Render(LogEventInfo)"/> that works best when /// override of <see cref="RenderFormattedMessage(LogEventInfo, StringBuilder)"/> is available. /// </summary> /// <param name="logEvent">The logging event.</param> /// <param name="target">Appends the formatted output to target</param> public void Render(LogEventInfo logEvent, StringBuilder target) { RenderAppendBuilder(logEvent, target, false); } internal virtual void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { Precalculate(logEvent); // Allow custom Layouts to also work } /// <summary> /// Optimized version of <see cref="Render(LogEventInfo)"/> that works best when /// override of <see cref="RenderFormattedMessage(LogEventInfo, StringBuilder)"/> is available. /// </summary> /// <param name="logEvent">The logging event.</param> /// <param name="target">Appends the string representing log event to target</param> /// <param name="cacheLayoutResult">Should rendering result be cached on LogEventInfo</param> private void RenderAppendBuilder(LogEventInfo logEvent, StringBuilder target, bool cacheLayoutResult) { if (!IsInitialized) { Initialize(LoggingConfiguration); } if (!ThreadAgnostic || MutableUnsafe) { object cachedValue; if (logEvent.TryGetCachedLayoutValue(this, out cachedValue)) { target.Append(cachedValue?.ToString()); return; } } else { cacheLayoutResult = false; } using (var localTarget = new AppendBuilderCreator(target, cacheLayoutResult)) { RenderFormattedMessage(logEvent, localTarget.Builder); if (cacheLayoutResult) { // when needed as it generates garbage logEvent.AddCachedLayoutValue(this, localTarget.Builder.ToString()); } } } /// <summary> /// Valid default implementation of <see cref="GetFormattedMessage" />, when having implemented the optimized <see cref="RenderFormattedMessage"/> /// </summary> /// <param name="logEvent">The logging event.</param> /// <returns>The rendered layout.</returns> internal string RenderAllocateBuilder(LogEventInfo logEvent) { using (var localTarget = new AppendBuilderCreator(true)) { RenderFormattedMessage(logEvent, localTarget.Builder); return localTarget.Builder.ToString(); } } internal string RenderAllocateBuilder(LogEventInfo logEvent, StringBuilder target) { RenderFormattedMessage(logEvent, target); return target.ToString(); } /// <summary> /// Renders formatted output using the log event as context. /// </summary> /// <param name="logEvent">The logging event.</param> /// <param name="target">Appends the formatted output to target</param> protected virtual void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { target.Append(GetFormattedMessage(logEvent)); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> void ISupportsInitialize.Initialize(LoggingConfiguration configuration) { Initialize(configuration); } /// <summary> /// Closes this instance. /// </summary> void ISupportsInitialize.Close() { Close(); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> internal void Initialize(LoggingConfiguration configuration) { if (!IsInitialized) { try { LoggingConfiguration = configuration; _scannedForObjects = false; PropertyHelper.CheckRequiredParameters(ConfigurationItemFactory.Default, this); InitializeLayout(); if (!_scannedForObjects) { InternalLogger.Debug("{0} Initialized Layout done but not scanned for objects", GetType()); PerformObjectScanning(); } } finally { IsInitialized = true; } } } internal void PerformObjectScanning() { var objectGraphScannerList = ObjectGraphScanner.FindReachableObjects<IRenderable>(ConfigurationItemFactory.Default, true, this); var objectGraphTypes = new HashSet<Type>(objectGraphScannerList.Select(o => o.GetType())); objectGraphTypes.Remove(typeof(SimpleLayout)); objectGraphTypes.Remove(typeof(NLog.LayoutRenderers.LiteralLayoutRenderer)); // determine whether the layout is thread-agnostic // layout is thread agnostic if it is thread-agnostic and // all its nested objects are thread-agnostic. ThreadAgnostic = objectGraphTypes.All(t => t.IsDefined(typeof(ThreadAgnosticAttribute), true)); MutableUnsafe = objectGraphTypes.Any(t => t.IsDefined(typeof(MutableUnsafeAttribute), true)); if ((ThreadAgnostic || !MutableUnsafe) && objectGraphScannerList.Count > 1 && objectGraphTypes.Count > 0) { foreach (var nestedLayout in objectGraphScannerList.OfType<Layout>()) { if (!ReferenceEquals(nestedLayout, this)) { nestedLayout.Initialize(LoggingConfiguration); ThreadAgnostic = nestedLayout.ThreadAgnostic && ThreadAgnostic; MutableUnsafe = nestedLayout.MutableUnsafe || MutableUnsafe; } } } // determine the max StackTraceUsage, to decide if Logger needs to capture callsite StackTraceUsage = StackTraceUsage.None; // In case this Layout should implement IUsesStackTrace StackTraceUsage = objectGraphScannerList.OfType<IUsesStackTrace>().DefaultIfEmpty().Aggregate(StackTraceUsage.None, (usage, item) => usage | item?.StackTraceUsage ?? StackTraceUsage.None); _scannedForObjects = true; } internal Layout[] ResolveLayoutPrecalculation(IEnumerable<Layout> allLayouts) { if (!_scannedForObjects || (ThreadAgnostic && !MutableUnsafe)) return null; int layoutCount = 0; int precalculateLayoutCount = 0; int precalculateSimpleLayoutCount = 0; foreach (var layout in allLayouts) { ++layoutCount; if (layout?.ThreadAgnostic == false || layout?.MutableUnsafe == true) { precalculateLayoutCount++; if (layout is SimpleLayout) { precalculateSimpleLayoutCount++; } } } if (layoutCount <= 1 || precalculateLayoutCount > 4 || (precalculateLayoutCount - precalculateSimpleLayoutCount) > 2 || (layoutCount - precalculateSimpleLayoutCount) <= 1) { return null; } else { return allLayouts.Where(layout => layout?.ThreadAgnostic == false || layout?.MutableUnsafe == true).ToArray(); } } /// <summary> /// Closes this instance. /// </summary> internal void Close() { if (IsInitialized) { LoggingConfiguration = null; IsInitialized = false; CloseLayout(); } } /// <summary> /// Initializes the layout. /// </summary> protected virtual void InitializeLayout() { PerformObjectScanning(); } /// <summary> /// Closes the layout. /// </summary> protected virtual void CloseLayout() { } /// <summary> /// Renders formatted output using the log event as context. /// </summary> /// <param name="logEvent">The logging event.</param> /// <returns>The formatted output.</returns> protected abstract string GetFormattedMessage(LogEventInfo logEvent); /// <summary> /// Register a custom Layout. /// </summary> /// <remarks>Short-cut for registering to default <see cref="ConfigurationItemFactory"/></remarks> /// <typeparam name="T"> Type of the Layout.</typeparam> /// <param name="name"> Name of the Layout.</param> [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public static void Register<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(string name) where T : Layout { var layoutRendererType = typeof(T); Register(name, layoutRendererType); } /// <summary> /// Register a custom Layout. /// </summary> /// <remarks>Short-cut for registering to default <see cref="ConfigurationItemFactory"/></remarks> /// <param name="layoutType"> Type of the Layout.</param> /// <param name="name"> Name of the Layout.</param> [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public static void Register(string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type layoutType) { ConfigurationItemFactory.Default.GetLayoutFactory().RegisterDefinition(name, layoutType); } /// <summary> /// Optimized version of <see cref="Precalculate(LogEventInfo)"/> for internal Layouts, when /// override of <see cref="RenderFormattedMessage(LogEventInfo, StringBuilder)"/> is available. /// </summary> internal void PrecalculateBuilderInternal(LogEventInfo logEvent, StringBuilder target, Layout[] precalculateLayout) { if (!ThreadAgnostic || MutableUnsafe) { if (precalculateLayout is null) { RenderAppendBuilder(logEvent, target, true); } else { foreach (var layout in precalculateLayout) { layout.PrecalculateBuilder(logEvent, target); target.Length = 0; } } } } internal string ToStringWithNestedItems<T>(IList<T> nestedItems, Func<T, string> nextItemToString) { if (nestedItems?.Count > 0) { var nestedNames = nestedItems.Select(nextItemToString).ToArray(); return string.Concat(GetType().Name, "=", string.Join("|", nestedNames)); } return base.ToString(); } /// <summary> /// Try get value /// </summary> /// <param name="logEvent"></param> /// <param name="rawValue">rawValue if return result is true</param> /// <returns>false if we could not determine the rawValue</returns> internal virtual bool TryGetRawValue(LogEventInfo logEvent, out object rawValue) { rawValue = null; return false; } /// <summary> /// Resolve from DI <see cref="LogFactory.ServiceRepository"/> /// </summary> /// <remarks>Avoid calling this while handling a LogEvent, since random deadlocks can occur</remarks> protected T ResolveService<T>() where T : class { return LoggingConfiguration.GetServiceProvider().ResolveService<T>(IsInitialized); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LayoutRenderers { using System; using Xunit; public class ExceptionDataLayoutRendererTests : NLogTestBase { [Fact] public void ExceptionWithDataItemIsLoggedTest() { const string exceptionMessage = "Test exception"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exceptiondata:" + exceptionDataKey + @"}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; Exception ex = new ArgumentException(exceptionMessage); ex.Data.Add(exceptionDataKey, exceptionDataValue); logFactory.GetCurrentClassLogger().Error(ex, "msg"); logFactory.AssertDebugLastMessage("debug", exceptionDataValue); } [Fact] public void ExceptionWithOutDataIsNotLoggedTest() { const string exceptionMessage = "Test exception"; const string exceptionDataKey = "testkey"; var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exceptiondata:" + exceptionDataKey + @"}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; Exception ex = new ArgumentException(exceptionMessage); logFactory.GetCurrentClassLogger().Error(ex, "msg"); logFactory.AssertDebugLastMessage(""); } [Fact] public void ExceptionUsingSpecifiedParamLogsProperlyTest() { const string exceptionMessage = "I don't like nullref exception!"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exceptiondata:item=" + exceptionDataKey + @"}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; Exception ex = new ArgumentException(exceptionMessage); ex.Data.Add(exceptionDataKey, exceptionDataValue); logFactory.GetCurrentClassLogger().Error(ex); logFactory.AssertDebugLastMessage(exceptionDataValue); } [Fact] public void BadDataForItemResultsInEmptyValueTest() { const string exceptionMessage = "I don't like nullref exception!"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exceptiondata:item=@}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; Exception ex = new ArgumentException(exceptionMessage); ex.Data.Add(exceptionDataKey, exceptionDataValue); logFactory.GetCurrentClassLogger().Error(ex); logFactory.AssertDebugLastMessage(""); } [Fact] public void NoDatkeyTest() { const string exceptionMessage = "I don't like nullref exception!"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exceptiondata:}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; Exception ex = new ArgumentException(exceptionMessage); ex.Data.Add(exceptionDataKey, exceptionDataValue); logFactory.GetCurrentClassLogger().Error(ex); logFactory.AssertDebugLastMessage(""); } [Fact] public void NoDatkeyUingParamTest() { const string exceptionMessage = "I don't like nullref exception!"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exceptiondata:item=}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; Exception ex = new ArgumentException(exceptionMessage); ex.Data.Add(exceptionDataKey, exceptionDataValue); logFactory.GetCurrentClassLogger().Error(ex); logFactory.AssertDebugLastMessage(""); } [Fact] public void BaseExceptionFlippedTest() { const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exceptiondata:item=" + exceptionDataKey + @":BaseException=true}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; Exception exceptionToTest; try { try { try { var except = new ArgumentException("Inner Exception"); except.Data[exceptionDataKey] = exceptionDataValue; throw except; } catch (Exception exception) { throw new System.ArgumentException("Wrapper1", exception); } } catch (Exception exception) { throw new ApplicationException("Wrapper2", exception); } } catch (Exception ex) { exceptionToTest = ex; } logFactory.GetCurrentClassLogger().Fatal(exceptionToTest, "msg"); logFactory.AssertDebugLastMessage(exceptionDataValue); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; // ReSharper disable once RedundantUsingDirective using NLog.Internal; /// <summary> /// Provides context for install/uninstall operations. /// </summary> public sealed class InstallationContext : IDisposable { #if !NETSTANDARD1_3 /// <summary> /// Mapping between log levels and console output colors. /// </summary> private static readonly Dictionary<LogLevel, ConsoleColor> LogLevel2ConsoleColor = new Dictionary<LogLevel, ConsoleColor>() { { LogLevel.Trace, ConsoleColor.DarkGray }, { LogLevel.Debug, ConsoleColor.Gray }, { LogLevel.Info, ConsoleColor.White }, { LogLevel.Warn, ConsoleColor.Yellow }, { LogLevel.Error, ConsoleColor.Red }, { LogLevel.Fatal, ConsoleColor.DarkRed }, }; #endif /// <summary> /// Initializes a new instance of the <see cref="InstallationContext"/> class. /// </summary> public InstallationContext() : this(TextWriter.Null) { } /// <summary> /// Initializes a new instance of the <see cref="InstallationContext"/> class. /// </summary> /// <param name="logOutput">The log output.</param> public InstallationContext(TextWriter logOutput) { LogOutput = logOutput; Parameters = new Dictionary<string, string>(); LogLevel = LogLevel.Info; ThrowExceptions = false; } /// <summary> /// Gets or sets the installation log level. /// </summary> public LogLevel LogLevel { get; set; } /// <summary> /// Gets or sets a value indicating whether to ignore failures during installation. /// </summary> public bool IgnoreFailures { get; set; } /// <summary> /// Whether installation exceptions should be rethrown. If IgnoreFailures is set to true, /// this property has no effect (there are no exceptions to rethrow). /// </summary> public bool ThrowExceptions { get; set; } /// <summary> /// Gets the installation parameters. /// </summary> public IDictionary<string, string> Parameters { get; private set; } /// <summary> /// Gets or sets the log output. /// </summary> public TextWriter LogOutput { get; set; } /// <summary> /// Logs the specified trace message. /// </summary> /// <param name="message">The message.</param> /// <param name="arguments">The arguments.</param> public void Trace([Localizable(false)] string message, params object[] arguments) { Log(LogLevel.Trace, message, arguments); } /// <summary> /// Logs the specified debug message. /// </summary> /// <param name="message">The message.</param> /// <param name="arguments">The arguments.</param> public void Debug([Localizable(false)] string message, params object[] arguments) { Log(LogLevel.Debug, message, arguments); } /// <summary> /// Logs the specified informational message. /// </summary> /// <param name="message">The message.</param> /// <param name="arguments">The arguments.</param> public void Info([Localizable(false)] string message, params object[] arguments) { Log(LogLevel.Info, message, arguments); } /// <summary> /// Logs the specified warning message. /// </summary> /// <param name="message">The message.</param> /// <param name="arguments">The arguments.</param> public void Warning([Localizable(false)] string message, params object[] arguments) { Log(LogLevel.Warn, message, arguments); } /// <summary> /// Logs the specified error message. /// </summary> /// <param name="message">The message.</param> /// <param name="arguments">The arguments.</param> public void Error([Localizable(false)] string message, params object[] arguments) { Log(LogLevel.Error, message, arguments); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { LogOutput?.Close(); LogOutput = null; } /// <summary> /// Creates the log event which can be used to render layouts during install/uninstall. /// </summary> /// <returns>Log event info object.</returns> public LogEventInfo CreateLogEvent() { var eventInfo = LogEventInfo.CreateNullEvent(); // set properties on the event foreach (var kvp in Parameters) { eventInfo.Properties.Add(kvp.Key, kvp.Value); } return eventInfo; } private void Log(LogLevel logLevel, string message, object[] arguments) { if (logLevel >= LogLevel) { if (arguments?.Length > 0) { message = string.Format(CultureInfo.InvariantCulture, message, arguments); } #if !NETSTANDARD1_3 var oldColor = Console.ForegroundColor; Console.ForegroundColor = LogLevel2ConsoleColor[logLevel]; try { LogOutput.WriteLine(message); } finally { Console.ForegroundColor = oldColor; } #else this.LogOutput.WriteLine(message); #endif } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.IO; using NLog.Common; using NLog.Layouts; using NLog.Targets; namespace NLog.Internal { /// <summary> /// A layout that represents a filePath. /// </summary> internal class FilePathLayout : IRenderable { /// <summary> /// Cached directory separator char array to avoid memory allocation on each method call. /// </summary> private static readonly char[] DirectorySeparatorChars = new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; /// <summary> /// Cached invalid file names char array to avoid memory allocation every time Path.GetInvalidFileNameChars() is called. /// </summary> private static readonly HashSet<char> InvalidFileNameChars = new HashSet<char>(Path.GetInvalidFileNameChars()); private readonly Layout _layout; private readonly FilePathKind _filePathKind; /// <summary> /// not null when <see cref="_filePathKind"/> == <c>false</c> /// </summary> private readonly string _baseDir; /// <summary> /// non null is fixed, /// </summary> private readonly string _cleanedFixedResult; private readonly bool _cleanupInvalidChars; /// <summary> /// <see cref="_cachedPrevRawFileName"/> is the cache-key, and when newly rendered filename matches the cache-key, /// then it reuses the cleaned cache-value <see cref="_cachedPrevCleanFileName"/>. /// </summary> private string _cachedPrevRawFileName; /// <summary> /// <see cref="_cachedPrevCleanFileName"/> is the cache-value that is reused, when the newly rendered filename /// matches the cache-key <see cref="_cachedPrevRawFileName"/> /// </summary> private string _cachedPrevCleanFileName; public bool IsFixedFilePath => _cleanedFixedResult != null; /// <summary>Initializes a new instance of the <see cref="FilePathLayout" /> class.</summary> public FilePathLayout(Layout layout, bool cleanupInvalidChars, FilePathKind filePathKind) { _layout = layout ?? new SimpleLayout(null); _cleanupInvalidChars = cleanupInvalidChars; _filePathKind = filePathKind == FilePathKind.Unknown ? DetectFilePathKind(_layout as SimpleLayout) : filePathKind; _cleanedFixedResult = (_layout as SimpleLayout)?.FixedText; if (_filePathKind == FilePathKind.Relative) { _baseDir = LogFactory.DefaultAppEnvironment.AppDomainBaseDirectory; InternalLogger.Debug("FileTarget FilePathLayout with FilePathKind.Relative using AppDomain.BaseDirectory: {0}", _baseDir); } if (_cleanedFixedResult != null) { if (!StringHelpers.IsNullOrWhiteSpace(_cleanedFixedResult)) { _cleanedFixedResult = GetCleanFileName(_cleanedFixedResult); _filePathKind = FilePathKind.Absolute; } else { _filePathKind = FilePathKind.Unknown; } } } public Layout GetLayout() { return _layout; } /// <summary> /// Render the raw filename from Layout /// </summary> /// <param name="logEvent">The log event.</param> /// <param name="reusableBuilder">StringBuilder to minimize allocations [optional].</param> /// <returns>String representation of a layout.</returns> private string GetRenderedFileName(LogEventInfo logEvent, System.Text.StringBuilder reusableBuilder = null) { if (reusableBuilder is null) { return _layout.Render(logEvent); } else { if (!_layout.ThreadAgnostic || _layout.MutableUnsafe) { object cachedResult; if (logEvent.TryGetCachedLayoutValue(_layout, out cachedResult)) { return cachedResult?.ToString() ?? string.Empty; } } _layout.Render(logEvent, reusableBuilder); if (_cachedPrevRawFileName != null && reusableBuilder.EqualTo(_cachedPrevRawFileName)) { // If old filename matches the newly rendered, then no need to call StringBuilder.ToString() return _cachedPrevRawFileName; } _cachedPrevRawFileName = reusableBuilder.ToString(); _cachedPrevCleanFileName = null; return _cachedPrevRawFileName; } } /// <summary> /// Convert the raw filename to a correct filename /// </summary> /// <param name="rawFileName">The filename generated by Layout.</param> /// <returns>String representation of a correct filename.</returns> private string GetCleanFileName(string rawFileName) { var cleanFileName = rawFileName; if (_cleanupInvalidChars) { cleanFileName = CleanupInvalidFilePath(rawFileName); } if (_filePathKind == FilePathKind.Absolute) { return cleanFileName; } if (_filePathKind == FilePathKind.Relative && _baseDir != null) { //use basedir, faster than Path.GetFullPath cleanFileName = Path.Combine(_baseDir, cleanFileName); return cleanFileName; } //unknown, use slow method cleanFileName = Path.GetFullPath(cleanFileName); return cleanFileName; } public string Render(LogEventInfo logEvent) { return RenderWithBuilder(logEvent); } internal string RenderWithBuilder(LogEventInfo logEvent, System.Text.StringBuilder reusableBuilder = null) { if (_cleanedFixedResult != null) return _cleanedFixedResult; // Always absolute path var rawFileName = GetRenderedFileName(logEvent, reusableBuilder); if (string.IsNullOrEmpty(rawFileName)) return rawFileName; if (_filePathKind == FilePathKind.Absolute && !_cleanupInvalidChars) return rawFileName; // Skip clean filename string-allocation if (string.Equals(_cachedPrevRawFileName, rawFileName, StringComparison.Ordinal) && _cachedPrevCleanFileName != null) return _cachedPrevCleanFileName; // Cache Hit, reuse clean filename string-allocation var cleanFileName = GetCleanFileName(rawFileName); _cachedPrevCleanFileName = cleanFileName; _cachedPrevRawFileName = rawFileName; return cleanFileName; } /// <summary> /// Is this (templated/invalid) path an absolute, relative or unknown? /// </summary> internal static FilePathKind DetectFilePathKind(SimpleLayout pathLayout) { if (pathLayout is null) return FilePathKind.Unknown; var isFixedText = pathLayout.IsFixedText; //nb: ${basedir} has already been rewritten in the SimpleLayout.compile var path = isFixedText ? pathLayout.FixedText : pathLayout.Text; return DetectFilePathKind(path, isFixedText); } internal static FilePathKind DetectFilePathKind(string path, bool isFixedText = true) { if (!string.IsNullOrEmpty(path)) { path = path.TrimStart(ArrayHelper.Empty<char>()); int length = path.Length; if (length >= 1) { var firstChar = path[0]; if (IsAbsoluteStartChar(firstChar)) return FilePathKind.Absolute; if (firstChar == '.') //. and .. { return FilePathKind.Relative; } if (length >= 2) { var secondChar = path[1]; //on unix VolumeSeparatorChar == DirectorySeparatorChar if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar && secondChar == Path.VolumeSeparatorChar) return FilePathKind.Absolute; } if (IsLayoutRenderer(path, isFixedText)) { //if first part is a layout, then unknown return FilePathKind.Unknown; } //not a layout renderer, but text return FilePathKind.Relative; } } return FilePathKind.Unknown; } private static bool IsLayoutRenderer(string path, bool isFixedText) { return !isFixedText && path.StartsWith("${", StringComparison.OrdinalIgnoreCase); } private static bool IsAbsoluteStartChar(char firstChar) { return firstChar == Path.DirectorySeparatorChar || firstChar == Path.AltDirectorySeparatorChar; } private static string CleanupInvalidFilePath(string filePath) { if (StringHelpers.IsNullOrWhiteSpace(filePath)) { return filePath; } var lastDirSeparator = filePath.LastIndexOfAny(DirectorySeparatorChars); char[] fileNameChars = null; for (int i = lastDirSeparator + 1; i < filePath.Length; i++) { if (InvalidFileNameChars.Contains(filePath[i])) { //delay char[] creation until first invalid char //is found to avoid memory allocation. if (fileNameChars is null) { fileNameChars = filePath.Substring(lastDirSeparator + 1).ToCharArray(); } fileNameChars[i - (lastDirSeparator + 1)] = '_'; } } //only if an invalid char was replaced do we create a new string. if (fileNameChars != null) { //keep the / in the dirname, because dirname could be c:/ and combine of c: and file name won't work well. var dirName = lastDirSeparator > 0 ? filePath.Substring(0, lastDirSeparator + 1) : string.Empty; string fileName = new string(fileNameChars); return Path.Combine(dirName, fileName); } return filePath; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System.Collections.Generic; using System.Text; using NLog.Config; /// <summary> /// A layout containing one or more nested layouts. /// </summary> /// <remarks> /// <a href="https://github.com/NLog/NLog/wiki/CompoundLayout">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/NLog/NLog/wiki/CompoundLayout">Documentation on NLog Wiki</seealso> [Layout("CompoundLayout")] [ThreadAgnostic] [AppDomainFixedOutput] public class CompoundLayout : Layout { private Layout[] _precalculateLayouts = null; /// <summary> /// Initializes a new instance of the <see cref="CompoundLayout"/> class. /// </summary> public CompoundLayout() { Layouts = new List<Layout>(); } /// <summary> /// Gets the inner layouts. /// </summary> /// <docgen category='Layout Options' order='10' /> [ArrayParameter(typeof(Layout), "layout")] public IList<Layout> Layouts { get; private set; } /// <inheritdoc/> protected override void InitializeLayout() { foreach (var layout in Layouts) layout.Initialize(LoggingConfiguration); base.InitializeLayout(); _precalculateLayouts = ResolveLayoutPrecalculation(Layouts); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { PrecalculateBuilderInternal(logEvent, target, _precalculateLayouts); } /// <inheritdoc/> protected override string GetFormattedMessage(LogEventInfo logEvent) { return RenderAllocateBuilder(logEvent); } /// <inheritdoc/> protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < Layouts.Count; i++) { Layout layout = Layouts[i]; layout.Render(logEvent, target); } } /// <inheritdoc/> protected override void CloseLayout() { _precalculateLayouts = null; foreach (var layout in Layouts) layout.Close(); base.CloseLayout(); } /// <inheritdoc/> public override string ToString() { return ToStringWithNestedItems(Layouts, l => l.ToString()); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using JetBrains.Annotations; namespace NLog.Internal { internal static class CollectionExtensions { /// <summary> /// Memory optimized filtering /// </summary> /// <remarks>Passing state too avoid delegate capture and memory-allocations.</remarks> [NotNull] public static IList<TItem> Filter<TItem, TState>([NotNull] this IList<TItem> items, TState state, Func<TItem, TState, bool> filter) { var hasIgnoredLogEvents = false; IList<TItem> filterLogEvents = null; for (var i = 0; i < items.Count; ++i) { var item = items[i]; if (filter(item, state)) { if (hasIgnoredLogEvents && filterLogEvents is null) { filterLogEvents = new List<TItem>(); } filterLogEvents?.Add(item); } else { if (!hasIgnoredLogEvents && i > 0) { filterLogEvents = new List<TItem>(); for (var j = 0; j < i; ++j) filterLogEvents.Add(items[j]); } hasIgnoredLogEvents = true; } } return filterLogEvents ?? (hasIgnoredLogEvents ? ArrayHelper.Empty<TItem>() : items); } } } <file_sep>using System; using System.Web; using NLog; using NLog.Targets; namespace SomeWebApplication { public class Global : System.Web.HttpApplication { // // this event handler is executed at the very start of the web application // so this is a good place to configure targets programmatically // // alternative you could place this code in a static type constructor // protected void Application_Start(Object sender, EventArgs e) { ASPNetTraceTarget target = new ASPNetTraceTarget(); target.Layout = "${logger} ${message}"; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using NLog.Config; using NLog.LayoutRenderers; using NLog.Layouts; /// <summary> /// Sends log messages to the remote instance of NLog Viewer. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/NLogViewer-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/NLogViewer-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/NLogViewer/NLog.config" /> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/NLogViewer/Simple/Example.cs" /> /// </example> [Target("NLogViewer")] public class NLogViewerTarget : NetworkTarget, IIncludeContext { private readonly Log4JXmlEventLayout _log4JLayout = new Log4JXmlEventLayout(); /// <summary> /// Initializes a new instance of the <see cref="NLogViewerTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> public NLogViewerTarget() { IncludeNLogData = true; IncludeEventProperties = false; // Already included when IncludeNLogData = true } /// <summary> /// Initializes a new instance of the <see cref="NLogViewerTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> /// <param name="name">Name of the target.</param> public NLogViewerTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets a value indicating whether to include NLog-specific extensions to log4j schema. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeNLogData { get => Renderer.IncludeNLogData; set => Renderer.IncludeNLogData = value; } /// <summary> /// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain. /// </summary> /// <docgen category='Layout Options' order='10' /> public Layout AppInfo { get => Renderer.AppInfo; set => Renderer.AppInfo = value; } /// <summary> /// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeCallSite { get => Renderer.IncludeCallSite; set => Renderer.IncludeCallSite = value; } /// <summary> /// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeSourceInfo { get => Renderer.IncludeSourceInfo; set => Renderer.IncludeSourceInfo = value; } /// <summary> /// Gets or sets a value indicating whether to include <see cref="MappedDiagnosticsContext"/> dictionary contents. /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeMdc { get => Renderer.IncludeMdc; set => Renderer.IncludeMdc = value; } /// <summary> /// Gets or sets whether to include log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeNdc { get => Renderer.IncludeNdc; set => Renderer.IncludeNdc = value; } /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeEventProperties { get => Renderer.IncludeEventProperties; set => Renderer.IncludeEventProperties = value; } /// <summary> /// Gets or sets whether to include the contents of the <see cref="ScopeContext"/> properties-dictionary. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeScopeProperties { get => Renderer.IncludeScopeProperties; set => Renderer.IncludeScopeProperties = value; } /// <summary> /// Gets or sets whether to include log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeScopeNested { get => Renderer.IncludeScopeNested; set => Renderer.IncludeScopeNested = value; } /// <summary> /// Gets or sets the separator for <see cref="ScopeContext"/> operation-states-stack. /// </summary> /// <docgen category='Layout Options' order='10' /> public string ScopeNestedSeparator { get => Renderer.ScopeNestedSeparator; set => Renderer.ScopeNestedSeparator = value; } /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeEventProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeAllProperties { get => IncludeEventProperties; set => IncludeEventProperties = value; } /// <summary> /// Gets or sets a value indicating whether to include <see cref="MappedDiagnosticsLogicalContext"/> dictionary contents. /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeMdlc { get => Renderer.IncludeMdlc; set => Renderer.IncludeMdlc = value; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsLogicalContext"/> stack. /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeNdc. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeNdlc { get => Renderer.IncludeNdlc; set => Renderer.IncludeNdlc = value; } /// <summary> /// Gets or sets the stack separator for log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by NdcItemSeparator. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public string NdlcItemSeparator { get => Renderer.NdlcItemSeparator; set => Renderer.NdlcItemSeparator = value; } /// <summary> /// Gets or sets the stack separator for log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Layout Options' order='10' /> public string NdcItemSeparator { get => Renderer.NdcItemSeparator; set => Renderer.NdcItemSeparator = value; } /// <summary> /// Gets or sets the renderer for log4j:event logger-xml-attribute (Default ${logger}) /// </summary> /// <docgen category='Layout Options' order='10' /> public Layout LoggerName { get => Renderer.LoggerName; set => Renderer.LoggerName = value; } /// <summary> /// Gets the collection of parameters. Each parameter contains a mapping /// between NLog layout and a named parameter. /// </summary> /// <docgen category='Layout Options' order='10' /> [ArrayParameter(typeof(NLogViewerParameterInfo), "parameter")] public IList<NLogViewerParameterInfo> Parameters => _log4JLayout.Parameters; /// <summary> /// Gets the layout renderer which produces Log4j-compatible XML events. /// </summary> [NLogConfigurationIgnoreProperty] public Log4JXmlEventLayoutRenderer Renderer => _log4JLayout.Renderer; /// <summary> /// Gets or sets the instance of <see cref="Log4JXmlEventLayout"/> that is used to format log messages. /// </summary> /// <docgen category='Layout Options' order='1' /> public override Layout Layout { get { return _log4JLayout; } set { // Fixed Log4JXmlEventLayout } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Internal { using Xunit; public class StringBuilderPoolTests : NLogTestBase { [Fact] public void StringBuilderPoolMaxCapacityTest() { int poolItemCount = 10; NLog.Internal.StringBuilderPool pool = new NLog.Internal.StringBuilderPool(poolItemCount); string mediumPayload = new string('A', 300000); RecursiveAcquirePoolItems(poolItemCount, pool, mediumPayload, true); // Verify fast-pool + slow-pool must grow RecursiveAcquirePoolItems(poolItemCount, pool, mediumPayload, false); // Verify fast-pool + slow-pool has kept their capacity string largePayload = new string('A', 1000000); RecursiveAcquirePoolItems(poolItemCount, pool, largePayload, true); using (var itemHolder = pool.Acquire()) { Assert.Equal(0, itemHolder.Item.Length); Assert.True(largePayload.Length <= itemHolder.Item.Capacity); // Verify fast-pool has kept its capacity RecursiveAcquirePoolItems(poolItemCount, pool, mediumPayload, true); // Verify slow-pool must grow } } private static void RecursiveAcquirePoolItems(int poolItemCount, NLog.Internal.StringBuilderPool pool, string payload, bool mustGrow) { if (poolItemCount <= 0) return; using (var itemHolder = pool.Acquire()) { Assert.Equal(0, itemHolder.Item.Length); Assert.True(payload.Length > itemHolder.Item.Capacity == mustGrow); itemHolder.Item.Append(payload); RecursiveAcquirePoolItems(poolItemCount - 1, pool, payload, mustGrow); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 namespace NLog.Internal { using System; using System.Collections.Generic; using System.IO; using NLog.Common; /// <summary> /// Watches multiple files at the same time and raises an event whenever /// a single change is detected in any of those files. /// </summary> internal sealed class MultiFileWatcher : IDisposable { private readonly Dictionary<string, FileSystemWatcher> _watcherMap = new Dictionary<string, FileSystemWatcher>(); /// <summary> /// The types of changes to watch for. /// </summary> public NotifyFilters NotifyFilters { get; set; } /// <summary> /// Occurs when a change is detected in one of the monitored files. /// </summary> public event FileSystemEventHandler FileChanged; public MultiFileWatcher() : this(NotifyFilters.LastWrite | NotifyFilters.CreationTime | NotifyFilters.Size | NotifyFilters.Security | NotifyFilters.Attributes) { } public MultiFileWatcher(NotifyFilters notifyFilters) { NotifyFilters = notifyFilters; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { FileChanged = null; // Release event listeners StopWatching(); } /// <summary> /// Stops watching all files. /// </summary> public void StopWatching() { lock (_watcherMap) { foreach (var watcher in _watcherMap) { StopWatching(watcher.Value); } _watcherMap.Clear(); } } /// <summary> /// Stops watching the specified file. /// </summary> /// <param name="fileName"></param> public void StopWatching(string fileName) { lock (_watcherMap) { if (_watcherMap.TryGetValue(fileName, out var watcher)) { StopWatching(watcher); _watcherMap.Remove(fileName); } } } /// <summary> /// Watches the specified files for changes. /// </summary> /// <param name="fileNames">The file names.</param> public void Watch(IEnumerable<string> fileNames) { if (fileNames is null) { return; } foreach (string s in fileNames) { Watch(s); } } public void Watch(string fileName) { try { var directory = Path.GetDirectoryName(fileName); directory = Path.GetFullPath(directory); if (!Directory.Exists(directory)) { InternalLogger.Warn("Cannot watch file '{0}' for non-existing directory: {1}", fileName, directory); return; } var fileFilter = Path.GetFileName(fileName); if (TryAddWatch(fileName, directory, fileFilter)) { InternalLogger.Debug("Watching file-filter '{0}' in directory: {1}", fileFilter, directory); } } catch (System.Security.SecurityException ex) { InternalLogger.Debug(ex, "Cannot watch for file changes: {0}", fileName); } } private bool TryAddWatch(string fileName, string directory, string fileFilter) { lock (_watcherMap) { if (_watcherMap.ContainsKey(fileName)) return false; FileSystemWatcher watcher = null; try { watcher = new FileSystemWatcher { Path = directory, Filter = fileFilter, NotifyFilter = NotifyFilters }; watcher.Created += OnFileChanged; watcher.Changed += OnFileChanged; watcher.Deleted += OnFileChanged; watcher.Renamed += OnFileChanged; watcher.Error += OnWatcherError; watcher.EnableRaisingEvents = true; _watcherMap.Add(fileName, watcher); return true; } catch (Exception ex) { InternalLogger.Error(ex, "Failed to setup FileSystemWatcher for file `{0}` with directory: {1}", fileName, directory); if (ex.MustBeRethrown()) throw; if (watcher != null) { StopWatching(watcher); } return false; } } } private void StopWatching(FileSystemWatcher watcher) { try { InternalLogger.Debug("Stopping file watching for path '{0}' filter '{1}'", watcher.Path, watcher.Filter); watcher.EnableRaisingEvents = false; watcher.Created -= OnFileChanged; watcher.Changed -= OnFileChanged; watcher.Deleted -= OnFileChanged; watcher.Renamed -= OnFileChanged; watcher.Error -= OnWatcherError; watcher.Dispose(); } catch (Exception ex) { InternalLogger.Error(ex, "Failed to stop file watcher for path '{0}' filter '{1}'", watcher.Path, watcher.Filter); if (ex.MustBeRethrown()) throw; } } private void OnWatcherError(object source, ErrorEventArgs e) { var watcherPath = string.Empty; var watcher = source as FileSystemWatcher; if (watcher != null) watcherPath = watcher.Path; var exception = e.GetException(); if (exception != null) InternalLogger.Warn(exception, "Error Watching Path {0}", watcherPath); else InternalLogger.Warn("Error Watching Path {0}", watcherPath); } private void OnFileChanged(object source, FileSystemEventArgs e) { var changed = FileChanged; if (changed != null) { try { changed(source, e); } catch (Exception ex) { #if DEBUG if (ex.MustBeRethrownImmediately()) throw; // Throwing exceptions here might crash the entire application (.NET 2.0 behavior) #endif InternalLogger.Error(ex, "Error Handling File Changed"); } } } } } #endif <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 && !NETSTANDARD1_5 namespace NLog.Internal.Fakeables { using System; using System.Collections.Generic; using System.Reflection; using NLog.Common; /// <summary> /// Adapter for <see cref="AppDomain"/> to <see cref="IAppDomain"/> /// </summary> [Obsolete("For unit testing only. Marked obsolete on NLog 5.0")] internal class AppDomainWrapper : IAppDomain { private readonly AppDomain _currentAppDomain; /// <summary> /// Initializes a new instance of the <see cref="AppDomainWrapper"/> class. /// </summary> /// <param name="appDomain">The <see cref="AppDomain"/> to wrap.</param> public AppDomainWrapper(AppDomain appDomain) { _currentAppDomain = appDomain; try { BaseDirectory = LookupBaseDirectory(appDomain) ?? string.Empty; } catch (Exception ex) { InternalLogger.Warn(ex, "AppDomain.BaseDirectory Failed"); BaseDirectory = string.Empty; } try { FriendlyName = appDomain.FriendlyName; } catch (Exception ex) { InternalLogger.Warn(ex, "AppDomain.FriendlyName Failed"); FriendlyName = GetFriendlyNameFromEntryAssembly() ?? GetFriendlyNameFromProcessName() ?? string.Empty; } try { ConfigurationFile = LookupConfigurationFile(appDomain); } catch (Exception ex) { InternalLogger.Warn(ex, "AppDomain.SetupInformation.ConfigurationFile Failed"); ConfigurationFile = string.Empty; } try { PrivateBinPath = LookupPrivateBinPath(appDomain); } catch (Exception ex) { InternalLogger.Warn(ex, "AppDomain.SetupInformation.PrivateBinPath Failed"); PrivateBinPath = ArrayHelper.Empty<string>(); } Id = appDomain.Id; } private static string LookupBaseDirectory(AppDomain appDomain) { return appDomain.BaseDirectory; } private static string LookupConfigurationFile(AppDomain appDomain) { #if !NETSTANDARD return appDomain.SetupInformation.ConfigurationFile; #else return string.Empty; #endif } private static string[] LookupPrivateBinPath(AppDomain appDomain) { #if !NETSTANDARD string privateBinPath = appDomain.SetupInformation.PrivateBinPath; return string.IsNullOrEmpty(privateBinPath) ? ArrayHelper.Empty<string>() : privateBinPath.SplitAndTrimTokens(';'); #else return ArrayHelper.Empty<string>(); #endif } private static string GetFriendlyNameFromEntryAssembly() { try { string assemblyName = Assembly.GetEntryAssembly()?.GetName()?.Name; return string.IsNullOrEmpty(assemblyName) ? null : assemblyName; } catch { return null; } } private static string GetFriendlyNameFromProcessName() { try { string processName = System.Diagnostics.Process.GetCurrentProcess().ProcessName; return string.IsNullOrEmpty(processName) ? null : processName; } catch { return null; } } /// <summary> /// Creates an AppDomainWrapper for the current <see cref="AppDomain"/> /// </summary> public static AppDomainWrapper CurrentDomain => new AppDomainWrapper(AppDomain.CurrentDomain); /// <summary> /// Gets or sets the base directory that the assembly resolver uses to probe for assemblies. /// </summary> public string BaseDirectory { get; private set; } /// <summary> /// Gets or sets the name of the configuration file for an application domain. /// </summary> public string ConfigurationFile { get; private set; } /// <summary> /// Gets or sets the list of directories under the application base directory that are probed for private assemblies. /// </summary> public IEnumerable<string> PrivateBinPath { get; private set; } /// <summary> /// Gets or set the friendly name. /// </summary> public string FriendlyName { get; private set; } /// <summary> /// Gets an integer that uniquely identifies the application domain within the process. /// </summary> public int Id { get; private set; } /// <summary> /// Gets the assemblies that have been loaded into the execution context of this application domain. /// </summary> /// <returns>A list of assemblies in this application domain.</returns> public IEnumerable<Assembly> GetAssemblies() { if (_currentAppDomain != null) return _currentAppDomain.GetAssemblies(); else return Internal.ArrayHelper.Empty<Assembly>(); } /// <summary> /// Process exit event. /// </summary> public event EventHandler<EventArgs> ProcessExit { add { if (processExitEvent == null && _currentAppDomain != null) _currentAppDomain.ProcessExit += OnProcessExit; processExitEvent += value; } remove { processExitEvent -= value; if (processExitEvent == null && _currentAppDomain != null) _currentAppDomain.ProcessExit -= OnProcessExit; } } private event EventHandler<EventArgs> processExitEvent; /// <summary> /// Domain unloaded event. /// </summary> public event EventHandler<EventArgs> DomainUnload { add { if (domainUnloadEvent == null && _currentAppDomain != null) _currentAppDomain.DomainUnload += OnDomainUnload; domainUnloadEvent += value; } remove { domainUnloadEvent -= value; if (domainUnloadEvent == null && _currentAppDomain != null) _currentAppDomain.DomainUnload -= OnDomainUnload; } } private event EventHandler<EventArgs> domainUnloadEvent; private void OnDomainUnload(object sender, EventArgs e) { var handler = domainUnloadEvent; handler?.Invoke(sender, e); } private void OnProcessExit(object sender, EventArgs eventArgs) { var handler = processExitEvent; handler?.Invoke(sender, eventArgs); } } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Config { using NLog.Conditions; using NLog.Config; using NLog.LayoutRenderers; using NLog.Layouts; using NLog.Targets; using NLog.Targets.Wrappers; using System; using System.Globalization; using System.IO; using System.Text; using Xunit; public class TargetConfigurationTests : NLogTestBase { [Fact] public void SimpleTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='d' type='Debug' layout='${message}' /> </targets> </nlog>"); DebugTarget t = c.FindTargetByName("d") as DebugTarget; Assert.NotNull(t); Assert.Equal("d", t.Name); SimpleLayout l = t.Layout as SimpleLayout; Assert.Equal("${message}", l.Text); Assert.NotNull(t.Layout); Assert.Single(l.Renderers); Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]); } [Fact] public void SimpleElementSyntaxTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target type='Debug'> <name>d</name> <layout>${message}</layout> </target> </targets> </nlog>"); DebugTarget t = c.FindTargetByName("d") as DebugTarget; Assert.NotNull(t); Assert.Equal("d", t.Name); SimpleLayout l = t.Layout as SimpleLayout; Assert.Equal("${message}", l.Text); Assert.NotNull(t.Layout); Assert.Single(l.Renderers); Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]); } [Fact] public void TargetWithLayoutHasUniqueLayout() { var target1 = new StructuredDebugTarget(); var target2 = new StructuredDebugTarget(); var simpleLayout1 = target1.Layout as SimpleLayout; var simpleLayout2 = target2.Layout as SimpleLayout; // Ensure the default Layout for two Targets are not reusing objects // As it would cause havoc with initializing / closing lifetime-events Assert.NotSame(simpleLayout1, simpleLayout2); Assert.Equal(simpleLayout1.Renderers.Count, simpleLayout1.Renderers.Count); for (int i = 0; i < simpleLayout1.Renderers.Count; ++i) { Assert.NotSame(simpleLayout1.Renderers[i], simpleLayout2.Renderers[i]); } } [Fact] public void NestedXmlConfigElementTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <extensions> <add type='" + typeof(StructuredDebugTarget).AssemblyQualifiedName + @"' /> </extensions> <targets> <target type='StructuredDebugTarget'> <name>structuredTgt</name> <layout>${message}</layout> <config platform='any'> <parameter name='param1' /> </config> </target> </targets> </nlog>"); var t = c.FindTargetByName("structuredTgt") as StructuredDebugTarget; Assert.NotNull(t); Assert.Equal("any", t.Config.Platform); Assert.Equal("param1", t.Config.Parameter.Name); } [Fact] public void ArrayParameterTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target type='MethodCall' name='mct'> <parameter name='p1' layout='${message}' /> <parameter name='p2' layout='${level}' /> <parameter name='p3' layout='${logger}' /> </target> </targets> </nlog>"); var t = c.FindTargetByName("mct") as MethodCallTarget; Assert.NotNull(t); Assert.Equal(3, t.Parameters.Count); Assert.Equal("p1", t.Parameters[0].Name); Assert.Equal("${message}", t.Parameters[0].Layout.ToString()); Assert.Equal("p2", t.Parameters[1].Name); Assert.Equal("${level}", t.Parameters[1].Layout.ToString()); Assert.Equal("p3", t.Parameters[2].Name); Assert.Equal("${logger}", t.Parameters[2].Layout.ToString()); } [Fact] public void ArrayElementParameterTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target type='MethodCall' name='mct'> <parameter> <name>p1</name> <layout>${message}</layout> </parameter> <parameter> <name>p2</name> <layout type='CsvLayout'> <column name='x' layout='${message}' /> <column name='y' layout='${level}' /> </layout> </parameter> <parameter> <name>p3</name> <layout>${logger}</layout> </parameter> </target> </targets> </nlog>"); var t = c.FindTargetByName("mct") as MethodCallTarget; Assert.NotNull(t); Assert.Equal(3, t.Parameters.Count); Assert.Equal("p1", t.Parameters[0].Name); Assert.Equal("${message}", t.Parameters[0].Layout.ToString()); Assert.Equal("p2", t.Parameters[1].Name); CsvLayout csvLayout = t.Parameters[1].Layout as CsvLayout; Assert.NotNull(csvLayout); Assert.Equal(2, csvLayout.Columns.Count); Assert.Equal("x", csvLayout.Columns[0].Name); Assert.Equal("y", csvLayout.Columns[1].Name); Assert.Equal("p3", t.Parameters[2].Name); Assert.Equal("${logger}", t.Parameters[2].Layout.ToString()); } [Fact] public void SimpleTest2() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='d' type='Debug' layout='${message} ${level}' /> </targets> </nlog>"); DebugTarget t = c.FindTargetByName("d") as DebugTarget; Assert.NotNull(t); Assert.Equal("d", t.Name); SimpleLayout l = t.Layout as SimpleLayout; Assert.Equal("${message} ${level}", l.Text); Assert.NotNull(l); Assert.Equal(3, l.Renderers.Count); Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]); Assert.IsType<LiteralLayoutRenderer>(l.Renderers[1]); Assert.IsType<LevelLayoutRenderer>(l.Renderers[2]); Assert.Equal(" ", ((LiteralLayoutRenderer)l.Renderers[1]).Text); } [Fact] public void WrapperTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <wrapper-target name='b' type='BufferingWrapper' bufferSize='19'> <wrapper name='a' type='AsyncWrapper'> <target name='c' type='Debug' layout='${message}' /> </wrapper> </wrapper-target> </targets> </nlog>"); Assert.NotNull(c.FindTargetByName("a")); Assert.NotNull(c.FindTargetByName("b")); Assert.NotNull(c.FindTargetByName("c")); Assert.IsType<BufferingTargetWrapper>(c.FindTargetByName("b")); Assert.IsType<AsyncTargetWrapper>(c.FindTargetByName("a")); Assert.IsType<DebugTarget>(c.FindTargetByName("c")); BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper; AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper; DebugTarget dt = c.FindTargetByName("c") as DebugTarget; Assert.Same(atw, btw.WrappedTarget); Assert.Same(dt, atw.WrappedTarget); Assert.Equal(19, btw.BufferSize); } [Fact] public void WrapperRefTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='c' type='Debug' layout='${message}' /> <wrapper name='a' type='AsyncWrapper'> <target-ref name='c' /> </wrapper> <wrapper-target name='b' type='BufferingWrapper' bufferSize='19'> <wrapper-target-ref name='a' /> </wrapper-target> </targets> </nlog>"); Assert.NotNull(c.FindTargetByName("a")); Assert.NotNull(c.FindTargetByName("b")); Assert.NotNull(c.FindTargetByName("c")); Assert.IsType<BufferingTargetWrapper>(c.FindTargetByName("b")); Assert.IsType<AsyncTargetWrapper>(c.FindTargetByName("a")); Assert.IsType<DebugTarget>(c.FindTargetByName("c")); BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper; AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper; DebugTarget dt = c.FindTargetByName("c") as DebugTarget; Assert.Same(atw, btw.WrappedTarget); Assert.Same(dt, atw.WrappedTarget); Assert.Equal(19, btw.BufferSize); } [Fact] public void CompoundTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <compound-target name='rr' type='RoundRobinGroup'> <target name='d1' type='Debug' layout='${message}1' /> <target name='d2' type='Debug' layout='${message}2' /> <target name='d3' type='Debug' layout='${message}3' /> <target name='d4' type='Debug' layout='${message}4' /> </compound-target> </targets> </nlog>"); Assert.NotNull(c.FindTargetByName("rr")); Assert.NotNull(c.FindTargetByName("d1")); Assert.NotNull(c.FindTargetByName("d2")); Assert.NotNull(c.FindTargetByName("d3")); Assert.NotNull(c.FindTargetByName("d4")); Assert.IsType<RoundRobinGroupTarget>(c.FindTargetByName("rr")); Assert.IsType<DebugTarget>(c.FindTargetByName("d1")); Assert.IsType<DebugTarget>(c.FindTargetByName("d2")); Assert.IsType<DebugTarget>(c.FindTargetByName("d3")); Assert.IsType<DebugTarget>(c.FindTargetByName("d4")); RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget; DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget; DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget; DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget; DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget; Assert.Equal(4, rr.Targets.Count); Assert.Same(d1, rr.Targets[0]); Assert.Same(d2, rr.Targets[1]); Assert.Same(d3, rr.Targets[2]); Assert.Same(d4, rr.Targets[3]); Assert.Equal("${message}1", ((SimpleLayout)d1.Layout).Text); Assert.Equal("${message}2", ((SimpleLayout)d2.Layout).Text); Assert.Equal("${message}3", ((SimpleLayout)d3.Layout).Text); Assert.Equal("${message}4", ((SimpleLayout)d4.Layout).Text); } [Fact] public void CompoundRefTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='d1' type='Debug' layout='${message}1' /> <target name='d2' type='Debug' layout='${message}2' /> <target name='d3' type='Debug' layout='${message}3' /> <target name='d4' type='Debug' layout='${message}4' /> <compound-target name='rr' type='RoundRobinGroup'> <target-ref name='d1' /> <target-ref name='d2' /> <target-ref name='d3' /> <target-ref name='d4' /> </compound-target> </targets> </nlog>"); Assert.NotNull(c.FindTargetByName("rr")); Assert.NotNull(c.FindTargetByName("d1")); Assert.NotNull(c.FindTargetByName("d2")); Assert.NotNull(c.FindTargetByName("d3")); Assert.NotNull(c.FindTargetByName("d4")); Assert.IsType<RoundRobinGroupTarget>(c.FindTargetByName("rr")); Assert.IsType<DebugTarget>(c.FindTargetByName("d1")); Assert.IsType<DebugTarget>(c.FindTargetByName("d2")); Assert.IsType<DebugTarget>(c.FindTargetByName("d3")); Assert.IsType<DebugTarget>(c.FindTargetByName("d4")); RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget; DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget; DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget; DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget; DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget; Assert.Equal(4, rr.Targets.Count); Assert.Same(d1, rr.Targets[0]); Assert.Same(d2, rr.Targets[1]); Assert.Same(d3, rr.Targets[2]); Assert.Same(d4, rr.Targets[3]); Assert.Equal("${message}1", ((SimpleLayout)d1.Layout).Text); Assert.Equal("${message}2", ((SimpleLayout)d2.Layout).Text); Assert.Equal("${message}3", ((SimpleLayout)d3.Layout).Text); Assert.Equal("${message}4", ((SimpleLayout)d4.Layout).Text); } [Fact] public void AsyncWrappersTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets async='true'> <target type='Debug' name='d' /> <target type='Debug' name='d2' /> </targets> </nlog>"); var t = c.FindTargetByName("d") as AsyncTargetWrapper; Assert.NotNull(t); Assert.Equal("d", t.Name); var wrappedTarget = t.WrappedTarget as DebugTarget; Assert.NotNull(wrappedTarget); Assert.Equal("d_wrapped", wrappedTarget.Name); t = c.FindTargetByName("d2") as AsyncTargetWrapper; Assert.NotNull(t); Assert.Equal("d2", t.Name); wrappedTarget = t.WrappedTarget as DebugTarget; Assert.NotNull(wrappedTarget); Assert.Equal("d2_wrapped", wrappedTarget.Name); } [Fact] public void UnnamedWrappedTargetTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets async='true'> <target type='AsyncWrapper' name='d'> <target type='Debug' /> </target> </targets> </nlog>"); var t = c.FindTargetByName("d") as AsyncTargetWrapper; Assert.NotNull(t); Assert.Equal("d", t.Name); var wrappedTarget = t.WrappedTarget as DebugTarget; Assert.NotNull(wrappedTarget); Assert.Equal("d_wrapped", wrappedTarget.Name); } [Fact] public void DefaultTargetParametersTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <default-target-parameters type='Debug' layout='x${message}x' /> <target type='Debug' name='d' /> <target type='Debug' name='d2' /> </targets> </nlog>"); var t = c.FindTargetByName("d") as DebugTarget; Assert.NotNull(t); Assert.Equal("x${message}x", t.Layout.ToString()); t = c.FindTargetByName("d2") as DebugTarget; Assert.NotNull(t); Assert.Equal("x${message}x", t.Layout.ToString()); } [Fact] public void DefaultTargetParametersOnWrappedTargetTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <default-target-parameters type='Debug' layout='x${message}x' /> <target type='BufferingWrapper' name='buf1'> <target type='Debug' name='d1' /> </target> </targets> </nlog>"); var wrap = c.FindTargetByName("buf1") as BufferingTargetWrapper; Assert.NotNull(wrap); Assert.NotNull(wrap.WrappedTarget); var t = wrap.WrappedTarget as DebugTarget; Assert.NotNull(t); Assert.Equal("x${message}x", t.Layout.ToString()); } [Fact] public void DefaultWrapperTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <default-wrapper type='BufferingWrapper'> <wrapper type='RetryingWrapper' /> </default-wrapper> <target type='Debug' name='d' layout='${level}' /> <target type='Debug' name='d2' layout='${level}' /> </targets> </nlog>"); var bufferingTargetWrapper = c.FindTargetByName("d") as BufferingTargetWrapper; Assert.NotNull(bufferingTargetWrapper); var retryingTargetWrapper = bufferingTargetWrapper.WrappedTarget as RetryingTargetWrapper; Assert.NotNull(retryingTargetWrapper); Assert.Null(retryingTargetWrapper.Name); var debugTarget = retryingTargetWrapper.WrappedTarget as DebugTarget; Assert.NotNull(debugTarget); Assert.Equal("d_wrapped", debugTarget.Name); Assert.Equal("${level}", debugTarget.Layout.ToString()); var debugTarget2 = c.FindTargetByName<DebugTarget>("d"); Assert.Same(debugTarget, debugTarget2); } [Fact] public void DontThrowExceptionWhenArchiveEverySetByDefaultParameters() { var fileName = Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".log"; try { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml($@" <nlog throwExceptions='true'> <targets> <default-target-parameters type='File' concurrentWrites='true' keepFileOpen='true' maxArchiveFiles='5' archiveNumbering='Rolling' archiveEvery='Day' /> <target fileName='{fileName}' name = 'file' type = 'File' /> </targets> <rules> <logger name='*' writeTo='file'/> </rules> </nlog> ").LogFactory; logFactory.GetLogger("TestLogger").Info("DefaultFileTargetParametersTests.DontThrowExceptionWhenArchiveEverySetByDefaultParameters is true"); Assert.NotNull(logFactory.Configuration); Assert.Single(logFactory.Configuration.AllTargets); } finally { if (File.Exists(fileName)) File.Delete(fileName); } } [Fact] public void DontThrowExceptionsWhenMissingRequiredParameters() { using (new NoThrowNLogExceptions()) { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml($@" <nlog> <targets> <target type='bufferingwrapper' name='mytarget'> <target type='unknowntargettype' name='badtarget' /> </target> </targets> <rules> <logger name='*' writeTo='mytarget'/> </rules> </nlog>").LogFactory; logFactory.GetLogger(nameof(DontThrowExceptionsWhenMissingRequiredParameters)).Info("Test"); Assert.NotNull(logFactory.Configuration); } } [Fact] public void DontThrowExceptionsWhenMissingTargetName() { using (new NoThrowNLogExceptions()) { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target type='bufferingwrapper'> <target type='unknowntargettype' name='badtarget' /> </target> <target type='debug' name='goodtarget' layout='${message}' /> </targets> <rules> <logger name='*' writeTo='goodtarget'/> </rules> </nlog>").LogFactory; logFactory.GetLogger(nameof(DontThrowExceptionsWhenMissingTargetName)).Info("Test"); AssertDebugLastMessage("goodtarget", "Test", logFactory); } } [Fact] public void RequiredDataTypesNullableTest() { var c = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <extensions> <add type='" + typeof(MyRequiredTarget).AssemblyQualifiedName + @"' /> </extensions> <targets> <target type='MyRequiredTarget' name='myTarget' stringProperty='foobar' enumProperty='Value3' /> </targets> </nlog>").LogFactory.Configuration; var myTarget = c.FindTargetByName("myTarget") as MyRequiredTarget; Assert.NotNull(myTarget); var missingStringValue = Assert.Throws<NLogConfigurationException>(() => new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <extensions> <add type='" + typeof(MyRequiredTarget).AssemblyQualifiedName + @"' /> </extensions> <targets> <target type='MyRequiredTarget' name='myTarget' enumProperty='Value3' /> </targets> </nlog>")); Assert.Contains(nameof(MyRequiredTarget.StringProperty), missingStringValue.Message); var missingEnumValue = Assert.Throws<NLogConfigurationException>(() => new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <extensions> <add type='" + typeof(MyRequiredTarget).AssemblyQualifiedName + @"' /> </extensions> <targets> <target type='MyRequiredTarget' name='myTarget' stringProperty='foobar' /> </targets> </nlog>")); Assert.Contains(nameof(MyRequiredTarget.EnumProperty), missingEnumValue.Message); var emptyEnumValue = Assert.Throws<NLogConfigurationException>(() => new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <extensions> <add type='" + typeof(MyRequiredTarget).AssemblyQualifiedName + @"' /> </extensions> <targets> <target type='MyRequiredTarget' name='myTarget' enumProperty='' stringProperty='foobar' /> </targets> </nlog>")); Assert.Contains(nameof(MyRequiredTarget.EnumProperty), emptyEnumValue.Message); } [Fact] public void DataTypesTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <extensions> <add type='" + typeof(MyTarget).AssemblyQualifiedName + @"' /> </extensions> <targets> <target type='MyTarget' name='myTarget' byteProperty='42' int16Property='42' int32Property='42' int64Property='42000000000' stringProperty='foobar' boolProperty='true' doubleProperty='3.14159' floatProperty='3.14159' enumProperty='Value3' flagsEnumProperty='Value1,Value3' encodingProperty='utf-8' cultureProperty='en-US' typeProperty='System.Int32' layoutProperty='${level}' conditionProperty=""starts-with(message, 'x')"" uriProperty='http://nlog-project.org' lineEndingModeProperty='default' /> </targets> </nlog>"); var myTarget = c.FindTargetByName("myTarget") as MyTarget; Assert.NotNull(myTarget); Assert.Equal((byte)42, myTarget.ByteProperty); Assert.Equal((short)42, myTarget.Int16Property); Assert.Equal(42, myTarget.Int32Property); Assert.Equal(42000000000L, myTarget.Int64Property); Assert.Equal("foobar", myTarget.StringProperty); Assert.True(myTarget.BoolProperty); Assert.Equal(3.14159, myTarget.DoubleProperty); Assert.Equal(3.14159f, myTarget.FloatProperty); Assert.Equal(MyEnum.Value3, myTarget.EnumProperty); Assert.Equal(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty); Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty); Assert.Equal("en-US", myTarget.CultureProperty.Name); Assert.Equal(typeof(int), myTarget.TypeProperty); Assert.Equal("${level}", myTarget.LayoutProperty.ToString()); Assert.Equal("starts-with(message, 'x')", myTarget.ConditionProperty.ToString()); Assert.Equal(new Uri("http://nlog-project.org"), myTarget.UriProperty); Assert.Equal(LineEndingMode.Default, myTarget.LineEndingModeProperty); } [Fact] public void NullableDataTypesTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <extensions> <add type='" + typeof(MyNullableTarget).AssemblyQualifiedName + @"' /> </extensions> <targets> <target type='MyNullableTarget' name='myTarget' byteProperty='42' int16Property='42' int32Property='42' int64Property='42000000000' stringProperty='foobar' boolProperty='true' doubleProperty='3.14159' floatProperty='3.14159' enumProperty='Value3' flagsEnumProperty='Value1,Value3' encodingProperty='utf-8' cultureProperty='en-US' typeProperty='System.Int32' layoutProperty='${level}' conditionProperty=""starts-with(message, 'x')"" /> </targets> </nlog>"); var myTarget = c.FindTargetByName("myTarget") as MyNullableTarget; Assert.NotNull(myTarget); Assert.Equal((byte)42, myTarget.ByteProperty); Assert.Equal((short)42, myTarget.Int16Property); Assert.Equal(42, myTarget.Int32Property); Assert.Equal(42000000000L, myTarget.Int64Property); Assert.Equal("foobar", myTarget.StringProperty); Assert.True(myTarget.BoolProperty); Assert.Equal(3.14159, myTarget.DoubleProperty); Assert.Equal(3.14159f, myTarget.FloatProperty); Assert.Equal(MyEnum.Value3, myTarget.EnumProperty); Assert.Equal(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty); Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty); Assert.Equal("en-US", myTarget.CultureProperty.Name); Assert.Equal(typeof(int), myTarget.TypeProperty); Assert.Equal("${level}", myTarget.LayoutProperty.ToString()); Assert.Equal("starts-with(message, 'x')", myTarget.ConditionProperty.ToString()); } [Target("MyTarget")] public class MyTarget : Target { public byte ByteProperty { get; set; } public short Int16Property { get; set; } public int Int32Property { get; set; } public long Int64Property { get; set; } public string StringProperty { get; set; } public bool BoolProperty { get; set; } public double DoubleProperty { get; set; } public float FloatProperty { get; set; } public MyEnum EnumProperty { get; set; } public MyFlagsEnum FlagsEnumProperty { get; set; } public Encoding EncodingProperty { get; set; } public CultureInfo CultureProperty { get; set; } public Type TypeProperty { get; set; } public Layout LayoutProperty { get; set; } public ConditionExpression ConditionProperty { get; set; } public Uri UriProperty { get; set; } public LineEndingMode LineEndingModeProperty { get; set; } public MyTarget() : base() { } public MyTarget(string name) : this() { Name = name; } } [Target("MyNullableTarget")] public class MyNullableTarget : Target { public byte? ByteProperty { get; set; } public short? Int16Property { get; set; } public int? Int32Property { get; set; } public long? Int64Property { get; set; } public string StringProperty { get; set; } public bool? BoolProperty { get; set; } public double? DoubleProperty { get; set; } public float? FloatProperty { get; set; } public MyEnum? EnumProperty { get; set; } public MyFlagsEnum? FlagsEnumProperty { get; set; } public Encoding EncodingProperty { get; set; } public CultureInfo CultureProperty { get; set; } public Type TypeProperty { get; set; } public Layout LayoutProperty { get; set; } public ConditionExpression ConditionProperty { get; set; } public MyNullableTarget() : base() { } public MyNullableTarget(string name) : this() { Name = name; } } [Target("MyRequiredTarget")] public class MyRequiredTarget : Target { [RequiredParameter] public string StringProperty { get; set; } [RequiredParameter] public MyEnum? EnumProperty { get; set; } } public enum MyEnum { Value1, Value2, Value3, } [Flags] public enum MyFlagsEnum { Value1 = 1, Value2 = 2, Value3 = 4, } [Target("StructuredDebugTarget")] public class StructuredDebugTarget : TargetWithLayout { public StructuredDebugTargetConfig Config { get; set; } public StructuredDebugTarget() { Config = new StructuredDebugTargetConfig(); } } public class StructuredDebugTargetConfig { public string Platform { get; set; } public StructuredDebugTargetParameter Parameter { get; set; } public StructuredDebugTargetConfig() { Parameter = new StructuredDebugTargetParameter(); } } public class StructuredDebugTargetParameter { public string Name { get; set; } } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Collections.Generic; using System.Linq; using NLog.Targets; using Xunit; namespace NLog.UnitTests.Targets { public class MethodCallTests : NLogTestBase { private const string CorrectClassName = "NLog.UnitTests.Targets.MethodCallTests, NLog.UnitTests"; #region ToBeCalled Methods #pragma warning disable xUnit1013 //we need public methods here private static MethodCallRecord LastCallTest; public static void StaticAndPublic(string param1, int param2) { LastCallTest = new MethodCallRecord("StaticAndPublic", param1, param2); } public static void StaticAndPublicWrongParameters(string param1, string param2) { LastCallTest = new MethodCallRecord("StaticAndPublic", param1, param2); } public static void StaticAndPublicTooLessParameters(string param1) { LastCallTest = new MethodCallRecord("StaticAndPublicTooLessParameters", param1); } public static void StaticAndPublicTooManyParameters(string param1, int param2, string param3) { LastCallTest = new MethodCallRecord("StaticAndPublicTooManyParameters", param1, param2); } public static void StaticAndPublicOptional(string param1, int param2, string param3 = "fixedValue") { LastCallTest = new MethodCallRecord("StaticAndPublicOptional", param1, param2, param3); } public void NonStaticAndPublic() { LastCallTest = new MethodCallRecord("NonStaticAndPublic"); } public static void StaticAndPrivate() { LastCallTest = new MethodCallRecord("StaticAndPrivate"); } #pragma warning restore xUnit1013 #endregion [Fact] public void TestMethodCall1() { TestMethodCall(new MethodCallRecord("StaticAndPublic", "test1", 2), "StaticAndPublic", CorrectClassName); } [Fact] public void TestMethodCall2() { //Type AssemblyQualifiedName //to find, use typeof(MethodCallTests).AssemblyQualifiedName TestMethodCall(new MethodCallRecord("StaticAndPublic", "test1", 2), "StaticAndPublic", "NLog.UnitTests.Targets.MethodCallTests, NLog.UnitTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b793d3de60bec2b9"); } [Fact] public void PrivateMethodDontThrow() { using (new NoThrowNLogExceptions()) { TestMethodCall(null, "NonStaticAndPublic", CorrectClassName); } } [Fact] public void WrongClassDontThrow() { using (new NoThrowNLogExceptions()) { TestMethodCall(null, "StaticAndPublic", "NLog.UnitTests222.Targets.CallTest, NLog.UnitTests"); } } [Fact] public void WrongMethodDontThrow() { using (new NoThrowNLogExceptions()) { TestMethodCall(null, "WrongStaticAndPublic", CorrectClassName); } } [Fact] public void EmptyClassDontThrow() { using (new NoThrowNLogExceptions()) { TestMethodCall(null, "", ""); } } [Fact] public void WrongParametersDontThrow() { using (new NoThrowNLogExceptions()) { TestMethodCall(null, "StaticAndPublicWrongParameters", CorrectClassName); } } [Fact] public void TooLessParametersDontThrow() { using (new NoThrowNLogExceptions()) { TestMethodCall(null, "StaticAndPublicTooLessParameters", CorrectClassName); } } [Fact] public void TooManyParametersDontThrow() { using (new NoThrowNLogExceptions()) { TestMethodCall(null, "StaticAndPublicTooManyParameters", CorrectClassName); } } [Fact] public void OptionalParameters() { TestMethodCall(new MethodCallRecord("StaticAndPublicOptional", "test1", 2, "fixedValue"), "StaticAndPublicOptional", CorrectClassName); } [Fact] public void FluentDelegateConfiguration() { string expectedMessage = "Hello World"; string actualMessage = string.Empty; var logFactory = new LogFactory().Setup().LoadConfiguration(builder => { var target = new MethodCallTarget("Hello", (logEvent, parameters) => { actualMessage = logEvent.Message; }); builder.ForLogger().WriteTo(target); }).LogFactory; logFactory.GetCurrentClassLogger().Debug(expectedMessage); logFactory.GetCurrentClassLogger().Debug(expectedMessage); // Bonus call to verify compiled expression tree works Assert.Equal(expectedMessage, actualMessage); } private static void TestMethodCall(MethodCallRecord expected, string methodName, string className) { var logFactory = new LogFactory().Setup().LoadConfiguration(builder => { var target = new MethodCallTarget { Name = "t1", ClassName = className, MethodName = methodName }; target.Parameters.Add(new MethodCallParameter("param1", "test1")); target.Parameters.Add(new MethodCallParameter("param2", "2", typeof(int))); builder.ForLogger().WriteTo(target); }).LogFactory; LastCallTest = null; logFactory.GetCurrentClassLogger().Debug("test method 1"); logFactory.GetCurrentClassLogger().Debug("test method 2"); // Bonus call to verify compiled expression tree works Assert.Equal(expected, LastCallTest); } private class MethodCallRecord { /// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> public MethodCallRecord(string method, params object[] parameterValues) { Method = method ?? string.Empty; ParameterValues = parameterValues?.ToList() ?? new List<object>(); } public string Method { get; set; } public List<object> ParameterValues { get; set; } protected bool Equals(MethodCallRecord other) { return string.Equals(Method, other.Method) && ParameterValues.SequenceEqual(other.ParameterValues); } /// <summary> /// Determines whether the specified object is equal to the current object. /// </summary> /// <returns> /// true if the specified object is equal to the current object; otherwise, false. /// </returns> /// <param name="obj">The object to compare with the current object. </param> public override bool Equals(object obj) { return obj is MethodCallRecord other && Equals(other); } /// <summary> /// Serves as the default hash function. /// </summary> /// <returns> /// A hash code for the current object. /// </returns> public override int GetHashCode() { unchecked { return Method.GetHashCode() * 397 ^ ParameterValues.Count.GetHashCode(); } } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using JetBrains.Annotations; using NLog.Internal; namespace NLog.Fluent { /// <summary> /// A fluent class to build log events for NLog. /// </summary> [Obsolete("Obsoleted since it allocates unnecessary. Instead use ILogger.ForLogEvent and LogEventBuilder. Obsoleted in NLog 5.0")] public class LogBuilder { private readonly LogEventInfo _logEvent; private readonly ILogger _logger; /// <summary> /// Initializes a new instance of the <see cref="LogBuilder"/> class. /// </summary> /// <param name="logger">The <see cref="Logger"/> to send the log event.</param> [CLSCompliant(false)] public LogBuilder(ILogger logger) : this(logger, LogLevel.Debug) { } /// <summary> /// Initializes a new instance of the <see cref="LogBuilder"/> class. /// </summary> /// <param name="logger">The <see cref="Logger"/> to send the log event.</param> /// <param name="logLevel">The <see cref="LogLevel"/> for the log event.</param> [CLSCompliant(false)] public LogBuilder(ILogger logger, LogLevel logLevel) { Guard.ThrowIfNull(logger); Guard.ThrowIfNull(logLevel); _logger = logger; _logEvent = new LogEventInfo() { LoggerName = logger.Name, Level = logLevel }; } /// <summary> /// Gets the <see cref="LogEventInfo"/> created by the builder. /// </summary> public LogEventInfo LogEventInfo => _logEvent; /// <summary> /// Sets the <paramref name="exception"/> information of the logging event. /// </summary> /// <param name="exception">The exception information of the logging event.</param> /// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns> public LogBuilder Exception(Exception exception) { _logEvent.Exception = exception; return this; } /// <summary> /// Sets the level of the logging event. /// </summary> /// <param name="logLevel">The level of the logging event.</param> /// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns> public LogBuilder Level(LogLevel logLevel) { Guard.ThrowIfNull(logLevel); _logEvent.Level = logLevel; return this; } /// <summary> /// Sets the logger name of the logging event. /// </summary> /// <param name="loggerName">The logger name of the logging event.</param> /// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns> public LogBuilder LoggerName([Localizable(false)] string loggerName) { _logEvent.LoggerName = loggerName; return this; } /// <summary> /// Sets the log message on the logging event. /// </summary> /// <param name="message">The log message for the logging event.</param> /// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns> public LogBuilder Message([Localizable(false)] string message) { _logEvent.Message = message; return this; } /// <summary> /// Sets the log message and parameters for formatting on the logging event. /// </summary> /// <param name="format">A composite format string.</param> /// <param name="arg0">The object to format.</param> /// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns> [MessageTemplateFormatMethod("format")] public LogBuilder Message([Localizable(false)][StructuredMessageTemplate] string format, object arg0) { _logEvent.Message = format; _logEvent.Parameters = new[] { arg0 }; return this; } /// <summary> /// Sets the log message and parameters for formatting on the logging event. /// </summary> /// <param name="format">A composite format string.</param> /// <param name="arg0">The first object to format.</param> /// <param name="arg1">The second object to format.</param> /// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns> [MessageTemplateFormatMethod("format")] public LogBuilder Message([Localizable(false)][StructuredMessageTemplate] string format, object arg0, object arg1) { _logEvent.Message = format; _logEvent.Parameters = new[] { arg0, arg1 }; return this; } /// <summary> /// Sets the log message and parameters for formatting on the logging event. /// </summary> /// <param name="format">A composite format string.</param> /// <param name="arg0">The first object to format.</param> /// <param name="arg1">The second object to format.</param> /// <param name="arg2">The third object to format.</param> /// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns> [MessageTemplateFormatMethod("format")] public LogBuilder Message([Localizable(false)][StructuredMessageTemplate] string format, object arg0, object arg1, object arg2) { _logEvent.Message = format; _logEvent.Parameters = new[] { arg0, arg1, arg2 }; return this; } /// <summary> /// Sets the log message and parameters for formatting on the logging event. /// </summary> /// <param name="format">A composite format string.</param> /// <param name="arg0">The first object to format.</param> /// <param name="arg1">The second object to format.</param> /// <param name="arg2">The third object to format.</param> /// <param name="arg3">The fourth object to format.</param> /// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns> [MessageTemplateFormatMethod("format")] public LogBuilder Message([Localizable(false)][StructuredMessageTemplate] string format, object arg0, object arg1, object arg2, object arg3) { _logEvent.Message = format; _logEvent.Parameters = new[] { arg0, arg1, arg2, arg3 }; return this; } /// <summary> /// Sets the log message and parameters for formatting on the logging event. /// </summary> /// <param name="format">A composite format string.</param> /// <param name="args">An object array that contains zero or more objects to format.</param> /// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns> [MessageTemplateFormatMethod("format")] public LogBuilder Message([Localizable(false)][StructuredMessageTemplate] string format, params object[] args) { _logEvent.Message = format; _logEvent.Parameters = args; return this; } /// <summary> /// Sets the log message and parameters for formatting on the logging event. /// </summary> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <param name="format">A composite format string.</param> /// <param name="args">An object array that contains zero or more objects to format.</param> /// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns> [MessageTemplateFormatMethod("format")] public LogBuilder Message(IFormatProvider provider, [Localizable(false)][StructuredMessageTemplate] string format, params object[] args) { _logEvent.FormatProvider = provider; _logEvent.Message = format; _logEvent.Parameters = args; return this; } /// <summary> /// Sets a per-event context property on the logging event. /// </summary> /// <param name="name">The name of the context property.</param> /// <param name="value">The value of the context property.</param> /// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns> public LogBuilder Property(object name, object value) { Guard.ThrowIfNull(name); _logEvent.Properties[name] = value; return this; } /// <summary> /// Sets multiple per-event context properties on the logging event. /// </summary> /// <param name="properties">The properties to set.</param> /// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns> public LogBuilder Properties(IDictionary properties) { Guard.ThrowIfNull(properties); foreach (var key in properties.Keys) { _logEvent.Properties[key] = properties[key]; } return this; } /// <summary> /// Sets the timestamp of the logging event. /// </summary> /// <param name="timeStamp">The timestamp of the logging event.</param> /// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns> public LogBuilder TimeStamp(DateTime timeStamp) { _logEvent.TimeStamp = timeStamp; return this; } /// <summary> /// Sets the stack trace for the event info. /// </summary> /// <param name="stackTrace">The stack trace.</param> /// <param name="userStackFrame">Index of the first user stack frame within the stack trace.</param> /// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns> public LogBuilder StackTrace(StackTrace stackTrace, int userStackFrame) { _logEvent.SetStackTrace(stackTrace, userStackFrame); return this; } /// <summary> /// Writes the log event to the underlying logger. /// </summary> /// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param> /// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param> /// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param> #if !NET35 && !NET40 public void Write( [CallerMemberName]string callerMemberName = null, [CallerFilePath]string callerFilePath = null, [CallerLineNumber]int callerLineNumber = 0) { if (!_logger.IsEnabled(_logEvent.Level)) return; SetCallerInfo(callerMemberName, callerFilePath, callerLineNumber); _logger.Log(_logEvent); } #else public void Write( string callerMemberName = null, string callerFilePath = null, int callerLineNumber = 0) { _logger.Log(_logEvent); } #endif /// <summary> /// Writes the log event to the underlying logger if the condition delegate is true. /// </summary> /// <param name="condition">If condition is true, write log event; otherwise ignore event.</param> /// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param> /// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param> /// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param> #if !NET35 && !NET40 public void WriteIf( Func<bool> condition, [CallerMemberName]string callerMemberName = null, [CallerFilePath]string callerFilePath = null, [CallerLineNumber]int callerLineNumber = 0) { if (condition is null || !condition() || !_logger.IsEnabled(_logEvent.Level)) return; SetCallerInfo(callerMemberName, callerFilePath, callerLineNumber); _logger.Log(_logEvent); } #else public void WriteIf( Func<bool> condition, string callerMemberName = null, string callerFilePath = null, int callerLineNumber = 0) { if (condition is null || !condition() || !_logger.IsEnabled(_logEvent.Level)) return; _logger.Log(_logEvent); } #endif /// <summary> /// Writes the log event to the underlying logger if the condition is true. /// </summary> /// <param name="condition">If condition is true, write log event; otherwise ignore event.</param> /// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param> /// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param> /// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param> #if !NET35 && !NET40 public void WriteIf( bool condition, [CallerMemberName]string callerMemberName = null, [CallerFilePath]string callerFilePath = null, [CallerLineNumber]int callerLineNumber = 0) { if (!condition || !_logger.IsEnabled(_logEvent.Level)) return; SetCallerInfo(callerMemberName, callerFilePath, callerLineNumber); _logger.Log(_logEvent); } #else public void WriteIf( bool condition, string callerMemberName = null, string callerFilePath = null, int callerLineNumber = 0) { if (!condition || !_logger.IsEnabled(_logEvent.Level)) return; _logger.Log(_logEvent); } #endif private void SetCallerInfo(string callerMethodName, string callerFilePath, int callerLineNumber) { if (callerMethodName != null || callerFilePath != null || callerLineNumber != 0) _logEvent.SetCallerInfo(null, callerMethodName, callerFilePath, callerLineNumber); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers.Wrappers { using System; using System.Text; using NLog.Config; /// <summary> /// Applies padding to another layout output. /// </summary> [LayoutRenderer("pad")] [AmbientProperty(nameof(Padding))] [AmbientProperty(nameof(PadCharacter))] [AmbientProperty(nameof(FixedLength))] [AmbientProperty(nameof(AlignmentOnTruncation))] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class PaddingLayoutRendererWrapper : WrapperLayoutRendererBase { /// <summary> /// Gets or sets the number of characters to pad the output to. /// </summary> /// <remarks> /// Positive padding values cause left padding, negative values /// cause right padding to the desired width. /// </remarks> /// <docgen category='Layout Options' order='10' /> public int Padding { get; set; } /// <summary> /// Gets or sets the padding character. /// </summary> /// <docgen category='Layout Options' order='10' /> public char PadCharacter { get; set; } = ' '; /// <summary> /// Gets or sets a value indicating whether to trim the /// rendered text to the absolute value of the padding length. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool FixedLength { get; set; } /// <summary> /// Gets or sets a value indicating whether a value that has /// been truncated (when <see cref="FixedLength" /> is true) /// will be left-aligned (characters removed from the right) /// or right-aligned (characters removed from the left). The /// default is left alignment. /// </summary> /// <docgen category='Layout Options' order='10' /> public PaddingHorizontalAlignment AlignmentOnTruncation { get; set; } = PaddingHorizontalAlignment.Left; /// <inheritdoc/> protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { Inner.Render(logEvent, builder); if (Padding != 0) { int absolutePadding = Padding; if (absolutePadding < 0) { absolutePadding = -absolutePadding; } var deltaLength = AppendPadding(builder, orgLength, absolutePadding); if (FixedLength && deltaLength > absolutePadding) { if (AlignmentOnTruncation == PaddingHorizontalAlignment.Left) { // Keep left side builder.Length = orgLength + absolutePadding; } else { builder.Remove(orgLength, deltaLength - absolutePadding); } } } } private int AppendPadding(StringBuilder builder, int orgLength, int absolutePadding) { int deltaLength = builder.Length - orgLength; if (Padding > 0) { // Pad Left if (deltaLength < 10 || deltaLength >= absolutePadding) { for (int i = deltaLength; i < absolutePadding; ++i) { builder.Append(PadCharacter); for (int j = builder.Length - 1; j > orgLength; --j) { builder[j] = builder[j - 1]; } builder[orgLength] = PadCharacter; ++deltaLength; } } else { var innerResult = builder.ToString(orgLength, deltaLength); builder.Length = orgLength; for (int i = deltaLength; i < absolutePadding; ++i) { builder.Append(PadCharacter); ++deltaLength; } builder.Append(innerResult); } } else { // Pad Right for (int i = deltaLength; i < absolutePadding; ++i) { builder.Append(PadCharacter); ++deltaLength; } } return deltaLength; } /// <inheritdoc/> protected override string Transform(string text) { throw new NotSupportedException(); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Filters { using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using NLog.Internal; /// <summary> /// Matches when the result of the calculated layout has been repeated a moment ago /// </summary> [Filter("whenRepeated")] public class WhenRepeatedFilter : LayoutBasedFilter { private const int MaxInitialRenderBufferLength = 16384; /// <summary> /// How long before a filter expires, and logging is accepted again /// </summary> /// <docgen category='Filtering Options' order='10' /> public int TimeoutSeconds { get; set; } = 10; /// <summary> /// Max length of filter values, will truncate if above limit /// </summary> /// <docgen category='Filtering Options' order='10' /> public int MaxLength { get; set; } = 1000; /// <summary> /// Applies the configured action to the initial logevent that starts the timeout period. /// Used to configure that it should ignore all events until timeout. /// </summary> /// <docgen category='Filtering Options' order='10' /> public bool IncludeFirst { get; set; } /// <summary> /// Max number of unique filter values to expect simultaneously /// </summary> /// <docgen category='Filtering Options' order='100' /> public int MaxFilterCacheSize { get; set; } = 50000; /// <summary> /// Default number of unique filter values to expect, will automatically increase if needed /// </summary> /// <docgen category='Filtering Options' order='100' /> public int DefaultFilterCacheSize { get; set; } = 1000; /// <summary> /// Insert FilterCount value into <see cref="LogEventInfo.Properties"/> when an event is no longer filtered /// </summary> /// <docgen category='Filtering Options' order='10' /> public string FilterCountPropertyName { get; set; } /// <summary> /// Append FilterCount to the <see cref="LogEventInfo.Message"/> when an event is no longer filtered /// </summary> /// <docgen category='Filtering Options' order='10' /> public string FilterCountMessageAppendFormat { get; set; } /// <summary> /// Reuse internal buffers, and doesn't have to constantly allocate new buffers /// </summary> /// <docgen category='Filtering Options' order='100' /> [Obsolete("No longer used, and always returns true. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool OptimizeBufferReuse { get => _optimizeBufferReuse ?? true; set => _optimizeBufferReuse = value ? true : (bool?)null; } private bool? _optimizeBufferReuse; /// <summary> /// Default buffer size for the internal buffers /// </summary> /// <docgen category='Filtering Options' order='100' /> public int OptimizeBufferDefaultLength { get; set; } = 1000; internal readonly ReusableBuilderCreator ReusableLayoutBuilder = new ReusableBuilderCreator(); private readonly Dictionary<FilterInfoKey, FilterInfo> _repeatFilter = new Dictionary<FilterInfoKey, FilterInfo>(1000); private readonly Stack<KeyValuePair<FilterInfoKey, FilterInfo>> _objectPool = new Stack<KeyValuePair<FilterInfoKey, FilterInfo>>(1000); /// <summary> /// Checks whether log event should be logged or not. In case the LogEvent has just been repeated. /// </summary> /// <param name="logEvent">Log event.</param> /// <returns> /// <see cref="FilterResult.Ignore"/> - if the log event should be ignored<br/> /// <see cref="FilterResult.Neutral"/> - if the filter doesn't want to decide<br/> /// <see cref="FilterResult.Log"/> - if the log event should be logged<br/> /// .</returns> protected override FilterResult Check(LogEventInfo logEvent) { FilterResult filterResult = FilterResult.Neutral; bool obsoleteFilter = false; lock (_repeatFilter) { using (var targetBuilder = ReusableLayoutBuilder.Allocate()) { if (targetBuilder.Result.Capacity != OptimizeBufferDefaultLength) { // StringBuilder.Equals only works when StringBuilder.Capacity is the same if (OptimizeBufferDefaultLength < MaxInitialRenderBufferLength) { OptimizeBufferDefaultLength = MaxLength; while (OptimizeBufferDefaultLength < targetBuilder.Result.Capacity && OptimizeBufferDefaultLength < MaxInitialRenderBufferLength) { OptimizeBufferDefaultLength *= 2; } } targetBuilder.Result.Capacity = OptimizeBufferDefaultLength; } FilterInfoKey filterInfoKey = RenderFilterInfoKey(logEvent, targetBuilder.Result); FilterInfo filterInfo; if (!_repeatFilter.TryGetValue(filterInfoKey, out filterInfo)) { filterInfo = CreateFilterInfo(logEvent); if (filterInfo.StringBuffer != null) { filterInfo.StringBuffer.ClearBuilder(); int length = Math.Min(targetBuilder.Result.Length, MaxLength); for (int i = 0; i < length; ++i) filterInfo.StringBuffer.Append(targetBuilder.Result[i]); } filterInfo.Refresh(logEvent.Level, logEvent.TimeStamp, 0); _repeatFilter.Add(new FilterInfoKey(filterInfo.StringBuffer, filterInfoKey.StringValue, filterInfoKey.StringHashCode), filterInfo); obsoleteFilter = true; } else { if (IncludeFirst) { obsoleteFilter = filterInfo.IsObsolete(logEvent.TimeStamp, TimeoutSeconds); } filterResult = RefreshFilterInfo(logEvent, filterInfo); } } } // Ignore the first log-event, and wait until next timeout expiry if (IncludeFirst && obsoleteFilter) { filterResult = Action; } return filterResult; } /// <summary> /// Uses object pooling, and prunes stale filter items when the pool runs dry /// </summary> private FilterInfo CreateFilterInfo(LogEventInfo logEvent) { FilterInfo reusableObject; if (_objectPool.Count == 0 && _repeatFilter.Count > DefaultFilterCacheSize) { int aggressiveTimeoutSeconds = _repeatFilter.Count > MaxFilterCacheSize ? TimeoutSeconds * 2 / 3 : TimeoutSeconds; PruneFilterCache(logEvent, Math.Max(1, aggressiveTimeoutSeconds)); if (_repeatFilter.Count > MaxFilterCacheSize) { PruneFilterCache(logEvent, Math.Max(1, TimeoutSeconds / 2)); } } if (_objectPool.Count == 0) { reusableObject = new FilterInfo(new StringBuilder(OptimizeBufferDefaultLength)); } else { reusableObject = _objectPool.Pop().Value; // StringBuilder.Equals only works when StringBuilder.Capacity is the same if (reusableObject.StringBuffer != null && reusableObject.StringBuffer.Capacity != OptimizeBufferDefaultLength) { reusableObject.StringBuffer.Capacity = OptimizeBufferDefaultLength; } } return reusableObject; } /// <summary> /// Remove stale filter-value from the cache, and fill them into the pool for reuse /// </summary> private void PruneFilterCache(LogEventInfo logEvent, int aggressiveTimeoutSeconds) { foreach (var filterPair in _repeatFilter) { if (filterPair.Value.IsObsolete(logEvent.TimeStamp, aggressiveTimeoutSeconds)) { _objectPool.Push(filterPair); } } foreach (var filterPair in _objectPool) { _repeatFilter.Remove(filterPair.Key); } if (_repeatFilter.Count * 2 > DefaultFilterCacheSize && DefaultFilterCacheSize < MaxFilterCacheSize) { DefaultFilterCacheSize *= 2; } while (_objectPool.Count != 0 && _objectPool.Count > DefaultFilterCacheSize) { _objectPool.Pop(); } } /// <summary> /// Renders the Log Event into a filter value, that is used for checking if just repeated /// </summary> private FilterInfoKey RenderFilterInfoKey(LogEventInfo logEvent, StringBuilder targetBuilder) { if (targetBuilder != null) { Layout.Render(logEvent, targetBuilder); if (targetBuilder.Length > MaxLength) targetBuilder.Length = MaxLength; return new FilterInfoKey(targetBuilder, null); } string value = Layout.Render(logEvent); if (value.Length > MaxLength) value = value.Substring(0, MaxLength); return new FilterInfoKey(null, value); } /// <summary> /// Repeated LogEvent detected. Checks if it should activate filter-action /// </summary> private FilterResult RefreshFilterInfo(LogEventInfo logEvent, FilterInfo filterInfo) { if (filterInfo.HasExpired(logEvent.TimeStamp, TimeoutSeconds) || logEvent.Level.Ordinal > filterInfo.LogLevel.Ordinal) { int filterCount = filterInfo.FilterCount; if (filterCount > 0 && filterInfo.IsObsolete(logEvent.TimeStamp, TimeoutSeconds)) { filterCount = 0; } filterInfo.Refresh(logEvent.Level, logEvent.TimeStamp, 0); if (filterCount > 0) { if (!string.IsNullOrEmpty(FilterCountPropertyName)) { if (!logEvent.Properties.TryGetValue(FilterCountPropertyName, out var otherFilterCount)) { logEvent.Properties[FilterCountPropertyName] = filterCount; } else if (otherFilterCount is int i) { filterCount = Math.Max(i, filterCount); logEvent.Properties[FilterCountPropertyName] = filterCount; } } if (!string.IsNullOrEmpty(FilterCountMessageAppendFormat) && logEvent.Message != null) { logEvent.Message += string.Format(FilterCountMessageAppendFormat, filterCount.ToString(System.Globalization.CultureInfo.InvariantCulture)); } } return FilterResult.Neutral; } filterInfo.Refresh(logEvent.Level, logEvent.TimeStamp, filterInfo.FilterCount + 1); return Action; } /// <summary> /// Filter Value State (mutable) /// </summary> private sealed class FilterInfo { public FilterInfo(StringBuilder stringBuilder) { StringBuffer = stringBuilder; } public void Refresh(LogLevel logLevel, DateTime logTimeStamp, int filterCount) { if (filterCount == 0) { LastLogTime = logTimeStamp; LogLevel = logLevel; } else if (LogLevel is null || logLevel.Ordinal > LogLevel.Ordinal) { LogLevel = logLevel; } LastFilterTime = logTimeStamp; FilterCount = filterCount; } public bool IsObsolete(DateTime logEventTime, int timeoutSeconds) { if (FilterCount == 0) { return HasExpired(logEventTime, timeoutSeconds); } return (logEventTime - LastFilterTime).TotalSeconds > timeoutSeconds && HasExpired(logEventTime, timeoutSeconds * 2); } public bool HasExpired(DateTime logEventTime, int timeoutSeconds) { return (logEventTime - LastLogTime).TotalSeconds > timeoutSeconds; } public StringBuilder StringBuffer { get; } public LogLevel LogLevel { get; private set; } private DateTime LastLogTime { get; set; } private DateTime LastFilterTime { get; set; } public int FilterCount { get; private set; } } /// <summary> /// Filter Lookup Key (immutable) /// </summary> private struct FilterInfoKey : IEquatable<FilterInfoKey> { private readonly StringBuilder _stringBuffer; public readonly string StringValue; public readonly int StringHashCode; public FilterInfoKey(StringBuilder stringBuffer, string stringValue, int? stringHashCode = null) { _stringBuffer = stringBuffer; StringValue = stringValue; if (stringHashCode.HasValue) { StringHashCode = stringHashCode.Value; } else if (stringBuffer != null) { int hashCode = stringBuffer.Length.GetHashCode(); int hashCodeCount = Math.Min(stringBuffer.Length, 100); for (int i = 0; i < hashCodeCount; ++i) hashCode = hashCode ^ stringBuffer[i].GetHashCode(); StringHashCode = hashCode; } else { StringHashCode = StringComparer.Ordinal.GetHashCode(StringValue); } } public override int GetHashCode() { return StringHashCode; } public bool Equals(FilterInfoKey other) { if (StringValue != null) { return string.Equals(StringValue, other.StringValue, StringComparison.Ordinal); } if (_stringBuffer != null && other._stringBuffer != null) { // StringBuilder.Equals only works when StringBuilder.Capacity is the same if (_stringBuffer.Capacity != other._stringBuffer.Capacity) { return _stringBuffer.EqualTo(other._stringBuffer); } return _stringBuffer.Equals(other._stringBuffer); } return ReferenceEquals(_stringBuffer, other._stringBuffer) && ReferenceEquals(StringValue, other.StringValue); } public override bool Equals(object obj) { return obj is FilterInfoKey key && Equals(key); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Xml; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; /// <summary> /// Calls the specified web service on each log message. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/WebService-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/WebService-target">Documentation on NLog Wiki</seealso> /// <remarks> /// The web service must implement a method that accepts a number of string parameters. /// </remarks> /// <example> /// <p> /// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/WebService/NLog.config" /> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/WebService/Simple/Example.cs" /> /// <p>The example web service that works with this example is shown below</p> /// <code lang="C#" source="examples/targets/Configuration API/WebService/Simple/WebService1/Service1.asmx.cs" /> /// </example> [Target("WebService")] public sealed class WebServiceTarget : MethodCallTargetBase { private const string SoapEnvelopeNamespaceUri = "http://schemas.xmlsoap.org/soap/envelope/"; private const string Soap12EnvelopeNamespaceUri = "http://www.w3.org/2003/05/soap-envelope"; /// <summary> /// dictionary that maps a concrete <see cref="HttpPostFormatterBase"/> implementation /// to a specific <see cref="WebServiceProtocol"/>-value. /// </summary> private static readonly Dictionary<WebServiceProtocol, Func<WebServiceTarget, HttpPostFormatterBase>> _postFormatterFactories = new Dictionary<WebServiceProtocol, Func<WebServiceTarget, HttpPostFormatterBase>>() { { WebServiceProtocol.Soap11, t => new HttpPostSoap11Formatter(t)}, { WebServiceProtocol.Soap12, t => new HttpPostSoap12Formatter(t)}, { WebServiceProtocol.HttpPost, t => new HttpPostFormEncodedFormatter(t)}, { WebServiceProtocol.JsonPost, t => new HttpPostJsonFormatter(t)}, { WebServiceProtocol.XmlPost, t => new HttpPostXmlDocumentFormatter(t)}, }; /// <summary> /// Initializes a new instance of the <see cref="WebServiceTarget" /> class. /// </summary> public WebServiceTarget() { Protocol = WebServiceProtocol.Soap11; //default NO utf-8 bom const bool writeBOM = false; Encoding = new UTF8Encoding(writeBOM); IncludeBOM = writeBOM; #if NETSTANDARD1_3 || NETSTANDARD1_5 // NetCore1 throws PlatformNotSupportedException on WebRequest.GetSystemWebProxy, when using DefaultWebProxy // Net5 (or newer) will turn off Http-connection-pooling if not using DefaultWebProxy ProxyType = WebServiceProxyType.NoProxy; #endif } /// <summary> /// Initializes a new instance of the <see cref="WebServiceTarget" /> class. /// </summary> /// <param name="name">Name of the target</param> public WebServiceTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets the web service URL. /// </summary> /// <docgen category='Web Service Options' order='10' /> [RequiredParameter] public Layout<Uri> Url { get; set; } /// <summary> /// Gets or sets the value of the User-agent HTTP header. /// </summary> /// <docgen category='Web Service Options' order='10' /> public Layout UserAgent { get; set; } /// <summary> /// Gets or sets the Web service method name. Only used with Soap. /// </summary> /// <docgen category='Web Service Options' order='10' /> public string MethodName { get; set; } /// <summary> /// Gets or sets the Web service namespace. Only used with Soap. /// </summary> /// <docgen category='Web Service Options' order='10' /> public string Namespace { get; set; } /// <summary> /// Gets or sets the protocol to be used when calling web service. /// </summary> /// <docgen category='Web Service Options' order='10' /> public WebServiceProtocol Protocol { get => _activeProtocol.Key; set => _activeProtocol = new KeyValuePair<WebServiceProtocol, HttpPostFormatterBase>(value, null); } private KeyValuePair<WebServiceProtocol, HttpPostFormatterBase> _activeProtocol = new KeyValuePair<WebServiceProtocol, HttpPostFormatterBase>(WebServiceProtocol.Soap11, null); /// <summary> /// Gets or sets the proxy configuration when calling web service /// </summary> /// <remarks> /// Changing ProxyType on Net5 (or newer) will turn off Http-connection-pooling /// </remarks> /// <docgen category='Web Service Options' order='10' /> public WebServiceProxyType ProxyType { get => _activeProxy.Key; set => _activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(value, null); } private KeyValuePair<WebServiceProxyType, IWebProxy> _activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(WebServiceProxyType.DefaultWebProxy, null); /// <summary> /// Gets or sets the custom proxy address, include port separated by a colon /// </summary> /// <docgen category='Web Service Options' order='10' /> public Layout ProxyAddress { get; set; } /// <summary> /// Should we include the BOM (Byte-order-mark) for UTF? Influences the <see cref="Encoding"/> property. /// /// This will only work for UTF-8. /// </summary> /// <docgen category='Web Service Options' order='10' /> public bool? IncludeBOM { get; set; } /// <summary> /// Gets or sets the encoding. /// </summary> /// <docgen category='Web Service Options' order='10' /> public Encoding Encoding { get; set; } /// <summary> /// Gets or sets a value whether escaping be done according to Rfc3986 (Supports Internationalized Resource Identifiers - IRIs) /// </summary> /// <value>A value of <c>true</c> if Rfc3986; otherwise, <c>false</c> for legacy Rfc2396.</value> /// <docgen category='Web Service Options' order='100' /> public bool EscapeDataRfc3986 { get; set; } /// <summary> /// Gets or sets a value whether escaping be done according to the old NLog style (Very non-standard) /// </summary> /// <value>A value of <c>true</c> if legacy encoding; otherwise, <c>false</c> for standard UTF8 encoding.</value> /// <docgen category='Web Service Options' order='100' /> public bool EscapeDataNLogLegacy { get; set; } /// <summary> /// Gets or sets the name of the root XML element, /// if POST of XML document chosen. /// If so, this property must not be <c>null</c>. /// (see <see cref="Protocol"/> and <see cref="WebServiceProtocol.XmlPost"/>). /// </summary> /// <docgen category='Web Service Options' order='100' /> public string XmlRoot { get; set; } /// <summary> /// Gets or sets the (optional) root namespace of the XML document, /// if POST of XML document chosen. /// (see <see cref="Protocol"/> and <see cref="WebServiceProtocol.XmlPost"/>). /// </summary> /// <docgen category='Web Service Options' order='100' /> public string XmlRootNamespace { get; set; } /// <summary> /// Gets the array of parameters to be passed. /// </summary> /// <docgen category='Web Service Options' order='10' /> [ArrayParameter(typeof(MethodCallParameter), "header")] public IList<MethodCallParameter> Headers { get; } = new List<MethodCallParameter>(); /// <summary> /// Indicates whether to pre-authenticate the HttpWebRequest (Requires 'Authorization' in <see cref="Headers"/> parameters) /// </summary> /// <docgen category='Web Service Options' order='100' /> public bool PreAuthenticate { get; set; } private readonly AsyncOperationCounter _pendingManualFlushList = new AsyncOperationCounter(); /// <summary> /// Calls the target method. Must be implemented in concrete classes. /// </summary> /// <param name="parameters">Method call parameters.</param> protected override void DoInvoke(object[] parameters) { // method is not used, instead asynchronous overload will be used throw new NotImplementedException(); } /// <summary> /// Calls the target DoInvoke method, and handles AsyncContinuation callback /// </summary> /// <param name="parameters">Method call parameters.</param> /// <param name="continuation">The continuation.</param> protected override void DoInvoke(object[] parameters, AsyncContinuation continuation) { var url = BuildWebServiceUrl(LogEventInfo.CreateNullEvent(), parameters); var webRequest = CreateHttpWebRequest(url); DoInvoke(parameters, webRequest, continuation); } /// <summary> /// Invokes the web service method. /// </summary> /// <param name="parameters">Parameters to be passed.</param> /// <param name="logEvent">The logging event.</param> protected override void DoInvoke(object[] parameters, AsyncLogEventInfo logEvent) { Uri url = null; HttpWebRequest webRequest = null; try { url = BuildWebServiceUrl(logEvent.LogEvent, parameters); if (url == null) { InternalLogger.Error("{0}: Error creating request with invalid url={1}", this, Url); logEvent.Continuation(new ArgumentException("Invalid Url for WebRequest")); return; } webRequest = CreateHttpWebRequest(url); if (Headers?.Count > 0) { for (int i = 0; i < Headers.Count; i++) { string headerValue = RenderLogEvent(Headers[i].Layout, logEvent.LogEvent); if (headerValue is null) continue; webRequest.Headers[Headers[i].Name] = headerValue; } } #if !NETSTANDARD1_3 && !NETSTANDARD1_5 var userAgent = RenderLogEvent(UserAgent, logEvent.LogEvent); if (!string.IsNullOrEmpty(userAgent)) { webRequest.UserAgent = userAgent; } #endif } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Error creating request for url={1}", this, url); throw; } DoInvoke(parameters, webRequest, logEvent.Continuation); } private HttpWebRequest CreateHttpWebRequest(Uri url) { var webRequest = (HttpWebRequest)WebRequest.Create(url); switch (ProxyType) { case WebServiceProxyType.DefaultWebProxy: break; #if !NETSTANDARD1_3 && !NETSTANDARD1_5 case WebServiceProxyType.AutoProxy: if (_activeProxy.Value is null) { IWebProxy proxy = WebRequest.GetSystemWebProxy(); proxy.Credentials = CredentialCache.DefaultCredentials; _activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(ProxyType, proxy); } webRequest.Proxy = _activeProxy.Value; break; case WebServiceProxyType.ProxyAddress: if (ProxyAddress != null) { if (_activeProxy.Value is null) { IWebProxy proxy = new WebProxy(RenderLogEvent(ProxyAddress, LogEventInfo.CreateNullEvent()), true); _activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(ProxyType, proxy); } webRequest.Proxy = _activeProxy.Value; } break; #endif default: webRequest.Proxy = null; break; } #if !NETSTANDARD1_3 && !NETSTANDARD1_5 if (PreAuthenticate || ProxyType == WebServiceProxyType.AutoProxy) { webRequest.PreAuthenticate = true; } #endif return webRequest; } private void DoInvoke(object[] parameters, HttpWebRequest webRequest, AsyncContinuation continuation) { Func<HttpWebRequest, AsyncCallback, IAsyncResult> beginGetRequest = (request, result) => request.BeginGetRequestStream(result, null); Func<HttpWebRequest, IAsyncResult, Stream> getRequestStream = (request, result) => request.EndGetRequestStream(result); DoInvoke(parameters, continuation, webRequest, beginGetRequest, getRequestStream); } internal void DoInvoke(object[] parameters, AsyncContinuation continuation, HttpWebRequest webRequest, Func<HttpWebRequest, AsyncCallback, IAsyncResult> beginGetRequest, Func<HttpWebRequest, IAsyncResult, Stream> getRequestStream) { MemoryStream postPayload = null; if (Protocol == WebServiceProtocol.HttpGet) { webRequest.Method = "GET"; } else { if (_activeProtocol.Value is null) _activeProtocol = new KeyValuePair<WebServiceProtocol, HttpPostFormatterBase>(Protocol, _postFormatterFactories[Protocol](this)); postPayload = _activeProtocol.Value.PrepareRequest(webRequest, parameters); } _pendingManualFlushList.BeginOperation(); try { if (postPayload?.Length > 0) { PostPayload(continuation, webRequest, beginGetRequest, getRequestStream, postPayload); } else { WaitForReponse(continuation, webRequest); } } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Error starting request for url={1}", this, webRequest.RequestUri); if (ExceptionMustBeRethrown(ex)) { throw; } DoInvokeCompleted(continuation, ex); } } private void WaitForReponse(AsyncContinuation continuation, HttpWebRequest webRequest) { webRequest.BeginGetResponse( r => { try { using (var response = webRequest.EndGetResponse(r)) { // Request successfully initialized } DoInvokeCompleted(continuation, null); } catch (Exception ex) { #if DEBUG if (ex.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } #endif InternalLogger.Error(ex, "{0}: Error receiving response for url={1}", this, webRequest.RequestUri); DoInvokeCompleted(continuation, ex); } }, null); } private void PostPayload(AsyncContinuation continuation, HttpWebRequest webRequest, Func<HttpWebRequest, AsyncCallback, IAsyncResult> beginGetRequest, Func<HttpWebRequest, IAsyncResult, Stream> getRequestStream, MemoryStream postPayload) { beginGetRequest(webRequest, result => { try { using (Stream stream = getRequestStream(webRequest, result)) { WriteStreamAndFixPreamble(postPayload, stream, IncludeBOM, Encoding); postPayload.Dispose(); } WaitForReponse(continuation, webRequest); } catch (Exception ex) { #if DEBUG if (ex.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } #endif InternalLogger.Error(ex, "{0}: Error sending payload for url={1}", this, webRequest.RequestUri); postPayload.Dispose(); DoInvokeCompleted(continuation, ex); } }); } private void DoInvokeCompleted(AsyncContinuation continuation, Exception ex) { _pendingManualFlushList.CompleteOperation(ex); continuation(ex); } /// <inheritdoc/> protected override void FlushAsync(AsyncContinuation asyncContinuation) { _pendingManualFlushList.RegisterCompletionNotification(asyncContinuation).Invoke(null); } /// <inheritdoc/> protected override void CloseTarget() { _pendingManualFlushList.Clear(); // Maybe consider to wait a short while if pending requests? base.CloseTarget(); } /// <summary> /// Builds the URL to use when calling the web service for a message, depending on the WebServiceProtocol. /// </summary> private Uri BuildWebServiceUrl(LogEventInfo logEvent, object[] parameterValues) { var uri = RenderLogEvent(Url, logEvent); if (Protocol != WebServiceProtocol.HttpGet) { return uri; } //if the protocol is HttpGet, we need to add the parameters to the query string of the url string queryParameters; using (var targetBuilder = ReusableLayoutBuilder.Allocate()) { StringBuilder sb = targetBuilder.Result ?? new StringBuilder(); UrlHelper.EscapeEncodingOptions encodingOptions = UrlHelper.GetUriStringEncodingFlags(EscapeDataNLogLegacy, false, EscapeDataRfc3986); BuildWebServiceQueryParameters(parameterValues, sb, encodingOptions); queryParameters = sb.ToString(); } var builder = new UriBuilder(uri); //append our query string to the URL following //the recommendations at https://msdn.microsoft.com/en-us/library/system.uribuilder.query.aspx if (builder.Query?.Length > 1) { builder.Query = string.Concat(builder.Query.Substring(1), "&", queryParameters); } else { builder.Query = queryParameters; } return builder.Uri; } private void BuildWebServiceQueryParameters(object[] parameterValues, StringBuilder sb, UrlHelper.EscapeEncodingOptions encodingOptions) { string separator = string.Empty; for (int i = 0; i < Parameters.Count; i++) { sb.Append(separator); sb.Append(Parameters[i].Name); sb.Append('='); string parameterValue = XmlHelper.XmlConvertToString(parameterValues[i]); if (!string.IsNullOrEmpty(parameterValue)) { UrlHelper.EscapeDataEncode(parameterValue, sb, encodingOptions); } separator = "&"; } } /// <summary> /// Write from input to output. Fix the UTF-8 bom /// </summary> private static void WriteStreamAndFixPreamble(MemoryStream postPayload, Stream output, bool? writeUtf8BOM, Encoding encoding) { //only when utf-8 encoding is used, the Encoding preamble is optional var nothingToDo = writeUtf8BOM is null || !(encoding is UTF8Encoding); const int preambleSize = 3; if (!nothingToDo) { //it's UTF-8 var hasBomInEncoding = encoding.GetPreamble().Length == preambleSize; //BOM already in Encoding. nothingToDo = writeUtf8BOM.Value && hasBomInEncoding; //Bom already not in Encoding nothingToDo = nothingToDo || !writeUtf8BOM.Value && !hasBomInEncoding; } var byteArray = postPayload.GetBuffer(); int offset = nothingToDo ? 0 : preambleSize; output.Write(byteArray, offset, (int)postPayload.Length - offset); } /// <summary> /// base class for POST formatters, that /// implement former <c>PrepareRequest()</c> method, /// that creates the content for /// the requested kind of HTTP request /// </summary> private abstract class HttpPostFormatterBase { protected HttpPostFormatterBase(WebServiceTarget target) { Target = target; } protected string ContentType => _contentType ?? (_contentType = GetContentType(Target)); private string _contentType; protected WebServiceTarget Target { get; } protected virtual string GetContentType(WebServiceTarget target) { return string.Concat("charset=", target.Encoding.WebName); } public MemoryStream PrepareRequest(HttpWebRequest request, object[] parameterValues) { InitRequest(request); var ms = new MemoryStream(); WriteContent(ms, parameterValues); return ms; } protected virtual void InitRequest(HttpWebRequest request) { request.Method = "POST"; request.ContentType = ContentType; } protected abstract void WriteContent(MemoryStream ms, object[] parameterValues); } private sealed class HttpPostFormEncodedFormatter : HttpPostTextFormatterBase { readonly UrlHelper.EscapeEncodingOptions _encodingOptions; public HttpPostFormEncodedFormatter(WebServiceTarget target) : base(target) { _encodingOptions = UrlHelper.GetUriStringEncodingFlags(target.EscapeDataNLogLegacy, true, target.EscapeDataRfc3986); } protected override string GetContentType(WebServiceTarget target) { return string.Concat("application/x-www-form-urlencoded", "; ", base.GetContentType(target)); } protected override void WriteStringContent(StringBuilder builder, object[] parameterValues) { Target.BuildWebServiceQueryParameters(parameterValues, builder, _encodingOptions); } } private sealed class HttpPostJsonFormatter : HttpPostTextFormatterBase { private readonly IJsonConverter _jsonConverter; public HttpPostJsonFormatter(WebServiceTarget target) : base(target) { _jsonConverter = target.ResolveService<IJsonConverter>(); } protected override string GetContentType(WebServiceTarget target) { return string.Concat("application/json", "; ", base.GetContentType(target)); } protected override void WriteStringContent(StringBuilder builder, object[] parameterValues) { if (Target.Parameters.Count == 1 && string.IsNullOrEmpty(Target.Parameters[0].Name) && parameterValues[0] is string s) { // JsonPost with single nameless parameter means complex JsonLayout builder.Append(s); } else { builder.Append('{'); string separator = string.Empty; for (int i = 0; i < Target.Parameters.Count; ++i) { var parameter = Target.Parameters[i]; builder.Append(separator); builder.Append('"'); builder.Append(parameter.Name); builder.Append("\":"); _jsonConverter.SerializeObject(parameterValues[i], builder); separator = ","; } builder.Append('}'); } } } private sealed class HttpPostSoap11Formatter : HttpPostSoapFormatterBase { private readonly string _defaultSoapAction; public HttpPostSoap11Formatter(WebServiceTarget target) : base(target) { _defaultSoapAction = GetDefaultSoapAction(target); } protected override string SoapEnvelopeNamespace => SoapEnvelopeNamespaceUri; protected override string SoapName => "soap"; protected override string GetContentType(WebServiceTarget target) { return string.Concat("text/xml", "; ", base.GetContentType(target)); } protected override void InitRequest(HttpWebRequest request) { base.InitRequest(request); if (Target.Headers?.Count == 0 || string.IsNullOrEmpty(request.Headers["SOAPAction"])) request.Headers["SOAPAction"] = _defaultSoapAction; } } private sealed class HttpPostSoap12Formatter : HttpPostSoapFormatterBase { public HttpPostSoap12Formatter(WebServiceTarget target) : base(target) { } protected override string SoapEnvelopeNamespace => Soap12EnvelopeNamespaceUri; protected override string SoapName => "soap12"; protected override string GetContentType(WebServiceTarget target) { return GetContentTypeSoap12(target, GetDefaultSoapAction(target)); } protected override void InitRequest(HttpWebRequest request) { base.InitRequest(request); string nonDefaultSoapAction = Target.Headers?.Count > 0 ? request.Headers["SOAPAction"] : string.Empty; if (!string.IsNullOrEmpty(nonDefaultSoapAction)) request.ContentType = GetContentTypeSoap12(Target, nonDefaultSoapAction); } private string GetContentTypeSoap12(WebServiceTarget target, string soapAction) { return string.Concat("application/soap+xml", "; ", base.GetContentType(target), "; action=\"", soapAction, "\""); } } private abstract class HttpPostSoapFormatterBase : HttpPostXmlFormatterBase { private readonly XmlWriterSettings _xmlWriterSettings; protected HttpPostSoapFormatterBase(WebServiceTarget target) : base(target) { _xmlWriterSettings = new XmlWriterSettings { Encoding = target.Encoding }; } protected abstract string SoapEnvelopeNamespace { get; } protected abstract string SoapName { get; } protected override void WriteContent(MemoryStream ms, object[] parameterValues) { using (var xtw = XmlWriter.Create(ms, _xmlWriterSettings)) { xtw.WriteStartElement(SoapName, "Envelope", SoapEnvelopeNamespace); xtw.WriteStartElement("Body", SoapEnvelopeNamespace); xtw.WriteStartElement(Target.MethodName, Target.Namespace); WriteAllParametersToCurrenElement(xtw, parameterValues); xtw.WriteEndElement(); // method name xtw.WriteEndElement(); // Body xtw.WriteEndElement(); // soap:Envelope xtw.Flush(); } } protected static string GetDefaultSoapAction(WebServiceTarget target) { return target.Namespace.EndsWith("/", StringComparison.Ordinal) ? string.Concat(target.Namespace, target.MethodName) : string.Concat(target.Namespace, "/", target.MethodName); } } private abstract class HttpPostTextFormatterBase : HttpPostFormatterBase { readonly ReusableBuilderCreator _reusableStringBuilder = new ReusableBuilderCreator(); readonly ReusableBufferCreator _reusableEncodingBuffer = new ReusableBufferCreator(1024); readonly byte[] _encodingPreamble; protected HttpPostTextFormatterBase(WebServiceTarget target) : base(target) { _encodingPreamble = target.Encoding.GetPreamble(); } protected override void WriteContent(MemoryStream ms, object[] parameterValues) { lock (_reusableStringBuilder) { using (var targetBuilder = _reusableStringBuilder.Allocate()) { WriteStringContent(targetBuilder.Result, parameterValues); using (var transformBuffer = _reusableEncodingBuffer.Allocate()) { if (_encodingPreamble.Length > 0) ms.Write(_encodingPreamble, 0, _encodingPreamble.Length); targetBuilder.Result.CopyToStream(ms, Target.Encoding, transformBuffer.Result); } } } } protected abstract void WriteStringContent(StringBuilder builder, object[] parameterValues); } private sealed class HttpPostXmlDocumentFormatter : HttpPostXmlFormatterBase { private readonly XmlWriterSettings _xmlWriterSettings; public HttpPostXmlDocumentFormatter(WebServiceTarget target) : base(target) { if (string.IsNullOrEmpty(target.XmlRoot)) throw new InvalidOperationException("WebServiceProtocol.Xml requires WebServiceTarget.XmlRoot to be set."); _xmlWriterSettings = new XmlWriterSettings { Encoding = target.Encoding, OmitXmlDeclaration = true, Indent = false }; } protected override string GetContentType(WebServiceTarget target) { return string.Concat("application/xml", "; ", base.GetContentType(target)); } protected override void WriteContent(MemoryStream ms, object[] parameterValues) { using (var xtw = XmlWriter.Create(ms, _xmlWriterSettings)) { xtw.WriteStartElement(Target.XmlRoot, Target.XmlRootNamespace); WriteAllParametersToCurrenElement(xtw, parameterValues); xtw.WriteEndElement(); xtw.Flush(); } } } private abstract class HttpPostXmlFormatterBase : HttpPostFormatterBase { protected HttpPostXmlFormatterBase(WebServiceTarget target) : base(target) { } protected void WriteAllParametersToCurrenElement(XmlWriter currentXmlWriter, object[] parameterValues) { for (int i = 0; i < Target.Parameters.Count; i++) { currentXmlWriter.WriteStartElement(Target.Parameters[i].Name); currentXmlWriter.WriteValue(parameterValues[i]); currentXmlWriter.WriteEndElement(); } } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests { using System; using System.Collections.Generic; using Xunit; public class LogLevelTests : NLogTestBase { [Fact] [Trait("Component", "Core")] public void OrdinalTest() { Assert.True(LogLevel.Trace < LogLevel.Debug); Assert.True(LogLevel.Debug < LogLevel.Info); Assert.True(LogLevel.Info < LogLevel.Warn); Assert.True(LogLevel.Warn < LogLevel.Error); Assert.True(LogLevel.Error < LogLevel.Fatal); Assert.True(LogLevel.Fatal < LogLevel.Off); Assert.False(LogLevel.Trace > LogLevel.Debug); Assert.False(LogLevel.Debug > LogLevel.Info); Assert.False(LogLevel.Info > LogLevel.Warn); Assert.False(LogLevel.Warn > LogLevel.Error); Assert.False(LogLevel.Error > LogLevel.Fatal); Assert.False(LogLevel.Fatal > LogLevel.Off); Assert.True(LogLevel.Trace <= LogLevel.Debug); Assert.True(LogLevel.Debug <= LogLevel.Info); Assert.True(LogLevel.Info <= LogLevel.Warn); Assert.True(LogLevel.Warn <= LogLevel.Error); Assert.True(LogLevel.Error <= LogLevel.Fatal); Assert.True(LogLevel.Fatal <= LogLevel.Off); Assert.False(LogLevel.Trace >= LogLevel.Debug); Assert.False(LogLevel.Debug >= LogLevel.Info); Assert.False(LogLevel.Info >= LogLevel.Warn); Assert.False(LogLevel.Warn >= LogLevel.Error); Assert.False(LogLevel.Error >= LogLevel.Fatal); Assert.False(LogLevel.Fatal >= LogLevel.Off); } [Fact] [Trait("Component", "Core")] public void LogLevelEqualityTest() { LogLevel levelTrace = LogLevel.Trace; LogLevel levelInfo = LogLevel.Info; Assert.True(LogLevel.Trace == levelTrace); Assert.True(LogLevel.Info == levelInfo); Assert.False(LogLevel.Trace == levelInfo); Assert.False(LogLevel.Trace != levelTrace); Assert.False(LogLevel.Info != levelInfo); Assert.True(LogLevel.Trace != levelInfo); } [Fact] [Trait("Component", "Core")] public void LogLevelFromOrdinal_InputInRange_ExpectValidLevel() { Assert.Same(LogLevel.Trace, LogLevel.FromOrdinal(0)); Assert.Same(LogLevel.Debug, LogLevel.FromOrdinal(1)); Assert.Same(LogLevel.Info, LogLevel.FromOrdinal(2)); Assert.Same(LogLevel.Warn, LogLevel.FromOrdinal(3)); Assert.Same(LogLevel.Error, LogLevel.FromOrdinal(4)); Assert.Same(LogLevel.Fatal, LogLevel.FromOrdinal(5)); Assert.Same(LogLevel.Off, LogLevel.FromOrdinal(6)); } [Fact] [Trait("Component", "Core")] public void LogLevelFromOrdinal_InputOutOfRange_ExpectException() { Assert.Throws<ArgumentException>(() => LogLevel.FromOrdinal(100)); // Boundary conditions. Assert.Throws<ArgumentException>(() => LogLevel.FromOrdinal(-1)); Assert.Throws<ArgumentException>(() => LogLevel.FromOrdinal(7)); } [Fact] [Trait("Component", "Core")] public void FromStringTest() { Assert.Same(LogLevel.Trace, LogLevel.FromString("trace")); Assert.Same(LogLevel.Debug, LogLevel.FromString("debug")); Assert.Same(LogLevel.Info, LogLevel.FromString("info")); Assert.Same(LogLevel.Warn, LogLevel.FromString("warn")); Assert.Same(LogLevel.Error, LogLevel.FromString("error")); Assert.Same(LogLevel.Fatal, LogLevel.FromString("fatal")); Assert.Same(LogLevel.Off, LogLevel.FromString("off")); Assert.Same(LogLevel.Trace, LogLevel.FromString("Trace")); Assert.Same(LogLevel.Debug, LogLevel.FromString("Debug")); Assert.Same(LogLevel.Info, LogLevel.FromString("Info")); Assert.Same(LogLevel.Warn, LogLevel.FromString("Warn")); Assert.Same(LogLevel.Error, LogLevel.FromString("Error")); Assert.Same(LogLevel.Fatal, LogLevel.FromString("Fatal")); Assert.Same(LogLevel.Off, LogLevel.FromString("Off")); Assert.Same(LogLevel.Trace, LogLevel.FromString("TracE")); Assert.Same(LogLevel.Debug, LogLevel.FromString("DebuG")); Assert.Same(LogLevel.Info, LogLevel.FromString("InfO")); Assert.Same(LogLevel.Warn, LogLevel.FromString("WarN")); Assert.Same(LogLevel.Error, LogLevel.FromString("ErroR")); Assert.Same(LogLevel.Fatal, LogLevel.FromString("FataL")); Assert.Same(LogLevel.Trace, LogLevel.FromString("TRACE")); Assert.Same(LogLevel.Debug, LogLevel.FromString("DEBUG")); Assert.Same(LogLevel.Info, LogLevel.FromString("INFO")); Assert.Same(LogLevel.Warn, LogLevel.FromString("WARN")); Assert.Same(LogLevel.Error, LogLevel.FromString("ERROR")); Assert.Same(LogLevel.Fatal, LogLevel.FromString("FATAL")); Assert.Same(LogLevel.Off, LogLevel.FromString("NoNe")); Assert.Same(LogLevel.Info, LogLevel.FromString("iNformaTION")); Assert.Same(LogLevel.Warn, LogLevel.FromString("WarNING")); } [Fact] [Trait("Component", "Core")] public void FromStringFailingTest() { Assert.Throws<ArgumentException>(() => LogLevel.FromString("zzz")); Assert.Throws<ArgumentException>(() => LogLevel.FromString(string.Empty)); Assert.Throws<ArgumentNullException>(() => LogLevel.FromString(null)); } [Fact] [Trait("Component", "Core")] public void LogLevelNullComparison() { LogLevel level = LogLevel.Info; Assert.False(level is null); Assert.True(level != null); Assert.False(null == level); Assert.True(null != level); level = null; Assert.True(level is null); Assert.False(level != null); Assert.True(null == level); Assert.False(null != level); } [Fact] [Trait("Component", "Core")] public void ToStringTest() { Assert.Equal("Trace", LogLevel.Trace.ToString()); Assert.Equal("Debug", LogLevel.Debug.ToString()); Assert.Equal("Info", LogLevel.Info.ToString()); Assert.Equal("Warn", LogLevel.Warn.ToString()); Assert.Equal("Error", LogLevel.Error.ToString()); Assert.Equal("Fatal", LogLevel.Fatal.ToString()); } [Fact] [Trait("Component", "Core")] public void LogLevelCompareTo_ValidLevels_ExpectIntValues() { LogLevel levelTrace = LogLevel.Trace; LogLevel levelDebug = LogLevel.Debug; LogLevel levelInfo = LogLevel.Info; LogLevel levelWarn = LogLevel.Warn; LogLevel levelError = LogLevel.Error; LogLevel levelFatal = LogLevel.Fatal; LogLevel levelOff = LogLevel.Off; LogLevel levelMin = LogLevel.MinLevel; LogLevel levelMax = LogLevel.MaxLevel; Assert.Equal(-1, LogLevel.Trace.CompareTo(levelDebug)); Assert.Equal(-1, LogLevel.Debug.CompareTo(levelInfo)); Assert.Equal(-1, LogLevel.Info.CompareTo(levelWarn)); Assert.Equal(-1, LogLevel.Warn.CompareTo(levelError)); Assert.Equal(-1, LogLevel.Error.CompareTo(levelFatal)); Assert.Equal(-1, LogLevel.Fatal.CompareTo(levelOff)); Assert.Equal(1, LogLevel.Debug.CompareTo(levelTrace)); Assert.Equal(1, LogLevel.Info.CompareTo(levelDebug)); Assert.Equal(1, LogLevel.Warn.CompareTo(levelInfo)); Assert.Equal(1, LogLevel.Error.CompareTo(levelWarn)); Assert.Equal(1, LogLevel.Fatal.CompareTo(levelError)); Assert.Equal(1, LogLevel.Off.CompareTo(levelFatal)); Assert.Equal(0, LogLevel.Debug.CompareTo(levelDebug)); Assert.Equal(0, LogLevel.Info.CompareTo(levelInfo)); Assert.Equal(0, LogLevel.Warn.CompareTo(levelWarn)); Assert.Equal(0, LogLevel.Error.CompareTo(levelError)); Assert.Equal(0, LogLevel.Fatal.CompareTo(levelFatal)); Assert.Equal(0, LogLevel.Off.CompareTo(levelOff)); Assert.Equal(0, LogLevel.Trace.CompareTo(levelMin)); Assert.Equal(1, LogLevel.Debug.CompareTo(levelMin)); Assert.Equal(2, LogLevel.Info.CompareTo(levelMin)); Assert.Equal(3, LogLevel.Warn.CompareTo(levelMin)); Assert.Equal(4, LogLevel.Error.CompareTo(levelMin)); Assert.Equal(5, LogLevel.Fatal.CompareTo(levelMin)); Assert.Equal(6, LogLevel.Off.CompareTo(levelMin)); Assert.Equal(-5, LogLevel.Trace.CompareTo(levelMax)); Assert.Equal(-4, LogLevel.Debug.CompareTo(levelMax)); Assert.Equal(-3, LogLevel.Info.CompareTo(levelMax)); Assert.Equal(-2, LogLevel.Warn.CompareTo(levelMax)); Assert.Equal(-1, LogLevel.Error.CompareTo(levelMax)); Assert.Equal(0, LogLevel.Fatal.CompareTo(levelMax)); Assert.Equal(1, LogLevel.Off.CompareTo(levelMax)); } [Fact] [Trait("Component", "Core")] public void LogLevelCompareTo_Null_ExpectLevelOff() { Assert.True(LogLevel.MinLevel.CompareTo(null) < 0); Assert.True(LogLevel.MaxLevel.CompareTo(null) < 0); Assert.Equal(0, LogLevel.Off.CompareTo(null)); } [Fact] [Trait("Component", "Core")] public void LogLevel_MinMaxLevels_ExpectConstantValues() { Assert.Same(LogLevel.Trace, LogLevel.MinLevel); Assert.Same(LogLevel.Fatal, LogLevel.MaxLevel); } [Fact] [Trait("Component", "Core")] public void LogLevelGetHashCode() { Assert.Equal(0, LogLevel.Trace.GetHashCode()); Assert.Equal(1, LogLevel.Debug.GetHashCode()); Assert.Equal(2, LogLevel.Info.GetHashCode()); Assert.Equal(3, LogLevel.Warn.GetHashCode()); Assert.Equal(4, LogLevel.Error.GetHashCode()); Assert.Equal(5, LogLevel.Fatal.GetHashCode()); Assert.Equal(6, LogLevel.Off.GetHashCode()); } [Fact] [Trait("Component", "Core")] public void LogLevelEquals_Null_ExpectFalse() { Assert.False(LogLevel.Debug.Equals(null)); LogLevel logLevel = null; Assert.False(LogLevel.Debug.Equals(logLevel)); Object obj = logLevel; Assert.False(LogLevel.Debug.Equals(obj)); } [Fact] public void LogLevelEqual_TypeOfObject() { // Objects of any other type should always return false. Assert.False(LogLevel.Debug.Equals((int) 1)); Assert.False(LogLevel.Debug.Equals((string)"Debug")); // Valid LogLevel objects boxed as Object type. Object levelTrace = LogLevel.Trace; Object levelDebug = LogLevel.Debug; Object levelInfo = LogLevel.Info; Object levelWarn = LogLevel.Warn; Object levelError = LogLevel.Error; Object levelFatal = LogLevel.Fatal; Object levelOff = LogLevel.Off; Assert.False(LogLevel.Warn.Equals(levelTrace)); Assert.False(LogLevel.Warn.Equals(levelDebug)); Assert.False(LogLevel.Warn.Equals(levelInfo)); Assert.True(LogLevel.Warn.Equals(levelWarn)); Assert.False(LogLevel.Warn.Equals(levelError)); Assert.False(LogLevel.Warn.Equals(levelFatal)); Assert.False(LogLevel.Warn.Equals(levelOff)); } [Fact] public void LogLevelEqual_TypeOfLogLevel() { Assert.False(LogLevel.Warn.Equals(LogLevel.Trace)); Assert.False(LogLevel.Warn.Equals(LogLevel.Debug)); Assert.False(LogLevel.Warn.Equals(LogLevel.Info)); Assert.True(LogLevel.Warn.Equals(LogLevel.Warn)); Assert.False(LogLevel.Warn.Equals(LogLevel.Error)); Assert.False(LogLevel.Warn.Equals(LogLevel.Fatal)); Assert.False(LogLevel.Warn.Equals(LogLevel.Off)); } [Fact] public void LogLevel_GetAllLevels() { Assert.Equal( new List<LogLevel>() { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal, LogLevel.Off }, LogLevel.AllLevels); } [Fact] public void LogLevel_SetAllLevels() { Assert.Throws<NotSupportedException>(() => ((ICollection<LogLevel>) LogLevel.AllLevels).Add(LogLevel.Fatal)); } [Fact] public void LogLevel_GetAllLoggingLevels() { Assert.Equal( new List<LogLevel>() { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal }, LogLevel.AllLoggingLevels); } [Fact] public void LogLevel_SetAllLoggingLevels() { Assert.Throws<NotSupportedException>(() => ((ICollection<LogLevel>)LogLevel.AllLoggingLevels).Add(LogLevel.Fatal)); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Contexts { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using Xunit; [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public class NestedDiagnosticsContextTests { [Fact] public void NDCTest1() { List<Exception> exceptions = new List<Exception>(); ManualResetEvent mre = new ManualResetEvent(false); int counter = 100; int remaining = counter; for (int i = 0; i < counter; ++i) { ThreadPool.QueueUserWorkItem( s => { try { NestedDiagnosticsContext.Clear(); Assert.Equal(string.Empty, NestedDiagnosticsContext.TopMessage); Assert.Equal(string.Empty, NestedDiagnosticsContext.Pop()); AssertContents(NestedDiagnosticsContext.GetAllMessages()); using (NestedDiagnosticsContext.Push("foo")) { Assert.Equal("foo", NestedDiagnosticsContext.TopMessage); AssertContents(NestedDiagnosticsContext.GetAllMessages(), "foo"); using (NestedDiagnosticsContext.Push("bar")) { AssertContents(NestedDiagnosticsContext.GetAllMessages(), "bar", "foo"); Assert.Equal("bar", NestedDiagnosticsContext.TopMessage); NestedDiagnosticsContext.Push("baz"); AssertContents(NestedDiagnosticsContext.GetAllMessages(), "baz", "bar", "foo"); Assert.Equal("baz", NestedDiagnosticsContext.TopMessage); Assert.Equal("baz", NestedDiagnosticsContext.Pop()); AssertContents(NestedDiagnosticsContext.GetAllMessages(), "bar", "foo"); Assert.Equal("bar", NestedDiagnosticsContext.TopMessage); } AssertContents(NestedDiagnosticsContext.GetAllMessages(), "foo"); Assert.Equal("foo", NestedDiagnosticsContext.TopMessage); } AssertContents(NestedDiagnosticsContext.GetAllMessages()); Assert.Equal(string.Empty, NestedDiagnosticsContext.Pop()); } catch (Exception ex) { lock (exceptions) { exceptions.Add(ex); } } finally { if (Interlocked.Decrement(ref remaining) == 0) { mre.Set(); } } }); } mre.WaitOne(); StringBuilder exceptionsMessage = new StringBuilder(); foreach (var ex in exceptions) { if (exceptionsMessage.Length > 0) { exceptionsMessage.Append("\r\n"); } exceptionsMessage.Append(ex.ToString()); } Assert.True(exceptions.Count == 0, exceptionsMessage.ToString()); } [Fact] public void NDCTest2_object() { List<Exception> exceptions = new List<Exception>(); ManualResetEvent mre = new ManualResetEvent(false); int counter = 100; int remaining = counter; for (int i = 0; i < counter; ++i) { ThreadPool.QueueUserWorkItem( s => { try { NestedDiagnosticsContext.Clear(); Assert.Null(NestedDiagnosticsContext.TopObject); Assert.Null(NestedDiagnosticsContext.PopObject()); AssertContents(NestedDiagnosticsContext.GetAllMessages()); using (NestedDiagnosticsContext.Push("foo")) { Assert.Equal("foo", NestedDiagnosticsContext.TopObject); AssertContents(NestedDiagnosticsContext.GetAllObjects(), "foo"); using (NestedDiagnosticsContext.Push("bar")) { AssertContents(NestedDiagnosticsContext.GetAllObjects(), "bar", "foo"); Assert.Equal("bar", NestedDiagnosticsContext.TopObject); NestedDiagnosticsContext.Push("baz"); AssertContents(NestedDiagnosticsContext.GetAllObjects(), "baz", "bar", "foo"); Assert.Equal("baz", NestedDiagnosticsContext.TopObject); Assert.Equal("baz", NestedDiagnosticsContext.PopObject()); AssertContents(NestedDiagnosticsContext.GetAllObjects(), "bar", "foo"); Assert.Equal("bar", NestedDiagnosticsContext.TopObject); } AssertContents(NestedDiagnosticsContext.GetAllObjects(), "foo"); Assert.Equal("foo", NestedDiagnosticsContext.TopObject); } AssertContents(NestedDiagnosticsContext.GetAllMessages()); Assert.Null(NestedDiagnosticsContext.PopObject()); } catch (Exception ex) { lock (exceptions) { exceptions.Add(ex); } } finally { if (Interlocked.Decrement(ref remaining) == 0) { mre.Set(); } } }); } mre.WaitOne(); StringBuilder exceptionsMessage = new StringBuilder(); foreach (var ex in exceptions) { if (exceptionsMessage.Length > 0) { exceptionsMessage.Append("\r\n"); } exceptionsMessage.Append(ex.ToString()); } Assert.True(exceptions.Count == 0, exceptionsMessage.ToString()); } private static void AssertContents(object[] actual, params string[] expected) { Assert.Equal(expected.Length, actual.Length); for (int i = 0; i < expected.Length; ++i) { Assert.Equal(expected[i], actual[i]); } } private static void AssertContents(string[] actual, params string[] expected) { Assert.Equal(expected.Length, actual.Length); for (int i = 0; i < expected.Length; ++i) { Assert.Equal(expected[i], actual[i]); } } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.IO; using System.IO.Compression; using System.Runtime.CompilerServices; using System.Text; using NLog.Common; using NLog.Layouts; using NLog.Targets; using Xunit; #if !NETSTANDARD using Ionic.Zip; #endif public abstract class NLogTestBase { protected NLogTestBase() { //reset before every test LogManager.ThrowExceptions = false; // Ignore any errors triggered by closing existing config LogManager.Configuration = null; // Will close any existing config #pragma warning disable CS0618 // Type or member is obsolete LogManager.LogFactory.ResetCandidateConfigFilePath(); #pragma warning restore CS0618 // Type or member is obsolete InternalLogger.Reset(); InternalLogger.LogLevel = LogLevel.Off; LogManager.ThrowExceptions = true; // Ensure exceptions are thrown by default during unit-testing LogManager.ThrowConfigExceptions = null; System.Diagnostics.Trace.Listeners.Clear(); #if !NETSTANDARD System.Diagnostics.Debug.Listeners.Clear(); #endif } protected static void AssertDebugCounter(string targetName, int val) { Assert.Equal(val, GetDebugTarget(targetName).Counter); } protected static void AssertDebugLastMessage(string targetName, string msg) { Assert.Equal(msg, GetDebugLastMessage(targetName)); } protected static void AssertDebugLastMessage(string targetName, string msg, LogFactory logFactory) { Assert.Equal(msg, GetDebugLastMessage(targetName, logFactory)); } protected static void AssertDebugLastMessageContains(string targetName, string msg) { string debugLastMessage = GetDebugLastMessage(targetName); Assert.True(debugLastMessage.Contains(msg), $"Expected to find '{msg}' in last message value on '{targetName}', but found '{debugLastMessage}'"); } protected static string GetDebugLastMessage(string targetName) { return GetDebugLastMessage(targetName, LogManager.LogFactory); } protected static string GetDebugLastMessage(string targetName, LogFactory logFactory) { return GetDebugTarget(targetName, logFactory).LastMessage; } public static DebugTarget GetDebugTarget(string targetName) { return GetDebugTarget(targetName, LogManager.LogFactory); } protected static DebugTarget GetDebugTarget(string targetName, LogFactory logFactory) { return LogFactoryTestExtensions.GetDebugTarget(targetName, logFactory.Configuration); } protected static void AssertFileContentsStartsWith(string fileName, string contents, Encoding encoding) { FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); byte[] buf = File.ReadAllBytes(fileName); Assert.True(encodedBuf.Length <= buf.Length, $"File:{fileName} encodedBytes:{encodedBuf.Length} does not match file.content:{buf.Length}, file.length = {fi.Length}"); for (int i = 0; i < encodedBuf.Length; ++i) { if (encodedBuf[i] != buf[i]) Assert.True(encodedBuf[i] == buf[i], $"File:{fileName} content mismatch {(int)encodedBuf[i]} <> {(int)buf[i]} at index {i}"); } } protected static void AssertFileContentsEndsWith(string fileName, string contents, Encoding encoding) { if (!File.Exists(fileName)) Assert.True(false, "File '" + fileName + "' doesn't exist."); string fileText = File.ReadAllText(fileName, encoding); Assert.True(fileText.Length >= contents.Length); Assert.Equal(contents, fileText.Substring(fileText.Length - contents.Length)); } protected sealed class CustomFileCompressor : IArchiveFileCompressor { public void CompressFile(string fileName, string archiveFileName) { string entryName = Path.GetFileNameWithoutExtension(archiveFileName) + Path.GetExtension(fileName); CompressFile(fileName, archiveFileName, entryName); } public void CompressFile(string fileName, string archiveFileName, string entryName) { #if !NETSTANDARD using (var zip = new Ionic.Zip.ZipFile()) { ZipEntry entry = zip.AddFile(fileName); entry.FileName = entryName; zip.Save(archiveFileName); } #endif } } #if NET35 || NET40 protected static void AssertZipFileContents(string fileName, string expectedEntryName, string contents, Encoding encoding) { if (!File.Exists(fileName)) Assert.True(false, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); using (var zip = new Ionic.Zip.ZipFile(fileName)) { Assert.Equal(1, zip.Count); Assert.Equal(encodedBuf.Length, zip[0].UncompressedSize); byte[] buf = new byte[zip[0].UncompressedSize]; using (var fs = zip[0].OpenReader()) { fs.Read(buf, 0, buf.Length); } for (int i = 0; i < buf.Length; ++i) { Assert.Equal(encodedBuf[i], buf[i]); } } } #else protected static void AssertZipFileContents(string fileName, string expectedEntryName, string contents, Encoding encoding) { FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var zip = new ZipArchive(stream, ZipArchiveMode.Read)) { Assert.Single(zip.Entries); Assert.Equal(expectedEntryName, zip.Entries[0].Name); Assert.Equal(encodedBuf.Length, zip.Entries[0].Length); byte[] buf = new byte[(int)zip.Entries[0].Length]; using (var fs = zip.Entries[0].Open()) { fs.Read(buf, 0, buf.Length); } for (int i = 0; i < buf.Length; ++i) { Assert.Equal(encodedBuf[i], buf[i]); } } } #endif protected static void AssertFileContents(string fileName, string expectedEntryName, string contents, Encoding encoding) { AssertFileContents(fileName, contents, encoding, false); } protected static void AssertFileContents(string fileName, string contents, Encoding encoding) { AssertFileContents(fileName, contents, encoding, false); } protected static void AssertFileContents(string fileName, string contents, Encoding encoding, bool addBom) { FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); //add bom if needed if (addBom) { var preamble = encoding.GetPreamble(); if (preamble.Length > 0) { //insert before encodedBuf = preamble.Concat(encodedBuf).ToArray(); } } byte[] buf; using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) { int index = 0; int count = (int)fs.Length; buf = new byte[count]; while (count > 0) { int n = fs.Read(buf, index, count); if (n == 0) break; index += n; count -= n; } } Assert.True(encodedBuf.Length == buf.Length, $"File:{fileName} encodedBytes:{encodedBuf.Length} does not match file.content:{buf.Length}, file.length = {fi.Length}"); for (int i = 0; i < buf.Length; ++i) { if (encodedBuf[i] != buf[i]) Assert.True(encodedBuf[i] == buf[i], $"File:{fileName} content mismatch {(int)encodedBuf[i]} <> {(int)buf[i]} at index {i}"); } } protected static void AssertFileContains(string fileName, string contentToCheck, Encoding encoding) { if (contentToCheck.Contains(Environment.NewLine)) Assert.True(false, "Please use only single line string to check."); FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); using (TextReader fs = new StreamReader(fileName, encoding)) { string line; while ((line = fs.ReadLine()) != null) { if (line.Contains(contentToCheck)) return; } } Assert.True(false, "File doesn't contains '" + contentToCheck + "'"); } protected static void AssertFileNotContains(string fileName, string contentToCheck, Encoding encoding) { if (contentToCheck.Contains(Environment.NewLine)) Assert.True(false, "Please use only single line string to check."); FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); using (TextReader fs = new StreamReader(fileName, encoding)) { string line; while ((line = fs.ReadLine()) != null) { if (line.Contains(contentToCheck)) Assert.False(true, "File contains '" + contentToCheck + "'"); } } } protected static string StringRepeat(int times, string s) { StringBuilder sb = new StringBuilder(s.Length * times); for (int i = 0; i < times; ++i) sb.Append(s); return sb.ToString(); } /// <summary> /// Render layout <paramref name="layout"/> with dummy <see cref="LogEventInfo" />and compare result with <paramref name="expected"/>. /// </summary> protected static void AssertLayoutRendererOutput(Layout layout, string expected) { var logEventInfo = LogEventInfo.Create(LogLevel.Info, "loggername", "message"); AssertLayoutRendererOutput(layout, logEventInfo, expected); } /// <summary> /// Render layout <paramref name="layout"/> with <paramref name="logEventInfo"/> and compare result with <paramref name="expected"/>. /// </summary> protected static void AssertLayoutRendererOutput(Layout layout, LogEventInfo logEventInfo, string expected) { layout.Initialize(null); string actual = layout.Render(logEventInfo); layout.Close(); Assert.Equal(expected, actual); } #if !NET35 && !NET40 /// <summary> /// Get line number of previous line. /// </summary> protected int GetPrevLineNumber([CallerLineNumber] int callingFileLineNumber = 0) { return callingFileLineNumber - 1; } #else /// <summary> /// Get line number of previous line. /// </summary> protected int GetPrevLineNumber() { //fixed value set with #line 100000 return 100001; } #endif protected static string RunAndCaptureInternalLog(SyncAction action, LogLevel internalLogLevel) { var stringWriter = new Logger(); var orgWriter = InternalLogger.LogWriter; var orgTimestamp = InternalLogger.IncludeTimestamp; var orgLevel = InternalLogger.LogLevel; try { InternalLogger.LogWriter = stringWriter; InternalLogger.IncludeTimestamp = false; InternalLogger.LogLevel = internalLogLevel; action(); } finally { InternalLogger.LogWriter = orgWriter; InternalLogger.IncludeTimestamp = orgTimestamp; InternalLogger.LogLevel = orgLevel; } return stringWriter.ToString(); } /// <summary> /// To handle unstable integration tests, retry if failed /// </summary> /// <param name="tries"></param> /// <param name="action"></param> protected static void RetryingIntegrationTest(int tries, Action action) { int tried = 0; while (tried < tries) { try { tried++; action(); return; //success } catch (Exception) { if (tried >= tries) { throw; } } } } /// <summary> /// This class has to be used when outputting from the InternalLogger.LogWriter. /// Just creating a string writer will cause issues, since string writer is not thread safe. /// This can cause issues when calling the ToString() on the text writer, since the underlying stringbuilder /// of the textwriter, has char arrays that gets fucked up by the multiple threads. /// this is a simple wrapper that just locks access to the writer so only one thread can access /// it at a time. /// </summary> private sealed class Logger : TextWriter { private readonly StringWriter writer = new StringWriter(); public override Encoding Encoding => writer.Encoding; #if NETSTANDARD1_5 public override void Write(char value) { lock (this.writer) { this.writer.Write(value); } } #endif public override void Write(string value) { lock (writer) { writer.Write(value); } } public override void WriteLine(string value) { lock (writer) { writer.WriteLine(value); } } public override string ToString() { lock (writer) { return writer.ToString(); } } } /// <summary> /// Creates <see cref="CultureInfo"/> instance for test purposes /// </summary> /// <param name="cultureName">Culture name to create</param> /// <remarks> /// Creates <see cref="CultureInfo"/> instance with non-userOverride /// flag to provide expected results when running tests in different /// system cultures(with overriden culture options) /// </remarks> protected static CultureInfo GetCultureInfo(string cultureName) { return new CultureInfo(cultureName, false); } /// <summary> /// Are we running on Linux environment or Windows environemtn ? /// </summary> /// <returns>true when something else than Windows</returns> protected static bool IsLinux() { return !NLog.Internal.PlatformDetector.IsWin32; } /// <summary> /// Are we running on AppVeyor? /// </summary> /// <returns></returns> protected static bool IsAppVeyor() { var val = Environment.GetEnvironmentVariable("APPVEYOR"); return val != null && val.Equals("true", StringComparison.OrdinalIgnoreCase); } public delegate void SyncAction(); public sealed class NoThrowNLogExceptions : IDisposable { private readonly bool throwExceptions; public NoThrowNLogExceptions() { throwExceptions = LogManager.ThrowExceptions; LogManager.ThrowExceptions = false; } public void Dispose() { LogManager.ThrowExceptions = throwExceptions; } } public sealed class InternalLoggerScope : IDisposable { private readonly TextWriter oldConsoleOutputWriter; public StringWriter ConsoleOutputWriter { get; private set; } private readonly TextWriter oldConsoleErrorWriter; public StringWriter ConsoleErrorWriter { get; private set; } private readonly LogLevel globalThreshold; private readonly bool throwExceptions; private readonly bool? throwConfigExceptions; public InternalLoggerScope(bool redirectConsole = false) { InternalLogger.LogLevel = LogLevel.Info; if (redirectConsole) { ConsoleOutputWriter = new StringWriter() { NewLine = "\n" }; ConsoleErrorWriter = new StringWriter() { NewLine = "\n" }; oldConsoleOutputWriter = Console.Out; oldConsoleErrorWriter = Console.Error; Console.SetOut(ConsoleOutputWriter); Console.SetError(ConsoleErrorWriter); } globalThreshold = LogManager.GlobalThreshold; throwExceptions = LogManager.ThrowExceptions; throwConfigExceptions = LogManager.ThrowConfigExceptions; } public void Dispose() { var logFile = InternalLogger.LogFile; InternalLogger.Reset(); LogManager.GlobalThreshold = globalThreshold; LogManager.ThrowExceptions = throwExceptions; LogManager.ThrowConfigExceptions = throwConfigExceptions; if (ConsoleOutputWriter != null) Console.SetOut(oldConsoleOutputWriter); if (ConsoleErrorWriter != null) Console.SetError(oldConsoleErrorWriter); if (!string.IsNullOrEmpty(InternalLogger.LogFile)) { if (File.Exists(InternalLogger.LogFile)) File.Delete(InternalLogger.LogFile); } if (!string.IsNullOrEmpty(logFile) && logFile != InternalLogger.LogFile) { if (File.Exists(logFile)) File.Delete(logFile); } } } protected static void AssertContainsInDictionary<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey key, TValue value) { Assert.Contains(key, dictionary); Assert.Equal(value, dictionary[key]); } } } <file_sep>using System; using NLog; using NLog.Targets; class Example { static void Main(string[] args) { DebugTarget target = new DebugTarget(); target.Layout = "${message}"; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); logger.Debug("another log message"); Console.WriteLine("The debug target has been hit {0} times.", target.Counter); Console.WriteLine("The last message was '{0}'.", target.LastMessage); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers.Wrappers { using System; using System.Text; using NLog.Config; /// <summary> /// Substring the result /// </summary> /// <example> /// ${substring:${level}:start=2:length=2} /// ${substring:${level}:start=-2:length=2} /// ${substring:Inner=${level}:start=2:length=2} /// </example> [LayoutRenderer("substring")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class SubstringLayoutRendererWrapper : WrapperLayoutRendererBase { /// <summary> /// Gets or sets the start index. /// </summary> /// <value>Index</value> /// <docgen category='Layout Options' order='10' /> public int Start { get; set; } /// <summary> /// Gets or sets the length in characters. If <c>null</c>, then the whole string /// </summary> /// <value>Index</value> /// <docgen category='Layout Options' order='10' /> public int? Length { get; set; } /// <inheritdoc/> protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { if (Length == 0) { return; } Inner.Render(logEvent, builder); var renderedLength = builder.Length - orgLength; if (renderedLength > 0) { var start = CalcStart(renderedLength); var length = CalcLength(renderedLength, start); var substring = builder.ToString(orgLength + start, length); builder.Length = orgLength; builder.Append(substring); } } /// <inheritdoc/> protected override string Transform(string text) { throw new NotSupportedException(); } /// <summary> /// Calculate start position /// </summary> /// <returns>0 or positive number</returns> private int CalcStart(int textLength) { var start = Start; if (start > textLength) { start = textLength; } if (start < 0) { start = (textLength + start); if (start < 0) start = 0; } return start; } /// <summary> /// Calculate needed length /// </summary> /// <returns>0 or positive number</returns> private int CalcLength(int textLength, int start) { var length = textLength - start; if (Length.HasValue && textLength > Length.Value + start) { length = Length.Value; } if (length < 0) { length = 0; } return length; } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !MONO && !NETSTANDARD namespace NLog.Internal.FileAppenders { using System; using System.IO; using System.Security; using System.Threading; using NLog.Common; /// <summary> /// Provides a multi process-safe atomic file append while /// keeping the files open. /// </summary> [SecuritySafeCritical] internal class WindowsMultiProcessFileAppender : BaseMutexFileAppender { public static readonly IFileAppenderFactory TheFactory = new Factory(); private FileStream _fileStream; /// <summary> /// Initializes a new instance of the <see cref="WindowsMultiProcessFileAppender" /> class. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="parameters">The parameters.</param> public WindowsMultiProcessFileAppender(string fileName, ICreateFileParameters parameters) : base(fileName, parameters) { try { CreateAppendOnlyFile(fileName); } catch { CloseFileSafe(ref _fileStream, fileName); throw; } } /// <summary> /// Creates or opens a file in a special mode, so that writes are automatically /// as atomic writes at the file end. /// See also "UnixMultiProcessFileAppender" which does a similar job on *nix platforms. /// </summary> /// <param name="fileName">File to create or open</param> private void CreateAppendOnlyFile(string fileName) { string dir = Path.GetDirectoryName(fileName); if (!Directory.Exists(dir)) { if (!CreateFileParameters.CreateDirs) { throw new DirectoryNotFoundException(dir); } Directory.CreateDirectory(dir); } var fileShare = FileShare.ReadWrite; if (CreateFileParameters.EnableFileDelete) fileShare |= FileShare.Delete; try { bool fileExists = File.Exists(fileName); // https://blogs.msdn.microsoft.com/oldnewthing/20151127-00/?p=92211/ // https://msdn.microsoft.com/en-us/library/ff548289.aspx // If only the FILE_APPEND_DATA and SYNCHRONIZE flags are set, the caller can write only to the end of the file, // and any offset information about writes to the file is ignored. // However, the file will automatically be extended as necessary for this type of write operation. _fileStream = new FileStream( fileName, FileMode.Append, System.Security.AccessControl.FileSystemRights.AppendData | System.Security.AccessControl.FileSystemRights.Synchronize, // <- Atomic append fileShare, 1, // No internal buffer, write directly from user-buffer FileOptions.None); long filePosition = _fileStream.Position; if (fileExists || filePosition > 0) { CreationTimeUtc = File.GetCreationTimeUtc(FileName); if (CreationTimeUtc < DateTime.UtcNow - TimeSpan.FromSeconds(2) && filePosition == 0) { // File wasn't created "almost now". // This could mean creation time has tunneled through from another file (see comment below). Thread.Sleep(50); // Having waited for a short amount of time usually means the file creation process has continued // code execution just enough to the above point where it has fixed up the creation time. CreationTimeUtc = File.GetCreationTimeUtc(FileName); } } else { // We actually created the file and eventually concurrent processes // may have opened the same file in between. // Only the one process creating the file should adjust the file creation time // to avoid being thwarted by Windows' Tunneling capabilities (https://support.microsoft.com/en-us/kb/172190). // Unfortunately we can't use the native SetFileTime() to prevent opening the file 2nd time. // This would require another desiredAccess flag which would disable the atomic append feature. // See also UpdateCreationTime() CreationTimeUtc = DateTime.UtcNow; File.SetCreationTimeUtc(FileName, CreationTimeUtc); } } catch { CloseFileSafe(ref _fileStream, fileName); throw; } } /// <inheritdoc/> public override void Write(byte[] bytes, int offset, int count) { _fileStream?.Write(bytes, offset, count); } /// <inheritdoc/> public override void Close() { CloseFileSafe(ref _fileStream, FileName); } /// <inheritdoc/> public override void Flush() { // do nothing, the file is written directly } /// <inheritdoc/> public override DateTime? GetFileCreationTimeUtc() { return CreationTimeUtc; // File is kept open, so creation time is static } /// <inheritdoc/> public override long? GetFileLength() { return _fileStream?.Length; } /// <summary> /// Factory class. /// </summary> private sealed class Factory : IFileAppenderFactory { /// <inheritdoc/> BaseFileAppender IFileAppenderFactory.Open(string fileName, ICreateFileParameters parameters) { return new WindowsMultiProcessFileAppender(fileName, parameters); } } } } #endif <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.Reflection; using JetBrains.Annotations; using NLog.Internal; using NLog.Common; /// <summary> /// Repository of interfaces used by NLog to allow override for dependency injection /// </summary> internal sealed class ServiceRepositoryInternal : ServiceRepository { private readonly Dictionary<Type, Func<object>> _creatorMap = new Dictionary<Type, Func<object>>(); private readonly Dictionary<Type, CompiledConstructor> _lateBoundMap = new Dictionary<Type, CompiledConstructor>(); private readonly object _lockObject = new object(); public event EventHandler<ServiceRepositoryUpdateEventArgs> TypeRegistered; /// <summary> /// Initializes a new instance of the <see cref="ServiceRepositoryInternal"/> class. /// </summary> internal ServiceRepositoryInternal(bool resetGlobalCache = false) { if (resetGlobalCache) ConfigurationItemFactory.Default = null; //build new global factory this.RegisterDefaults(); // Maybe also include active TimeSource ? Could also be done with LogFactory extension-methods } public override void RegisterService(Type type, object instance) { Guard.ThrowIfNull(type); Guard.ThrowIfNull(instance); lock (_lockObject) { _creatorMap[type] = () => instance; } TypeRegistered?.Invoke(this, new ServiceRepositoryUpdateEventArgs(type)); } public override object GetService(Type serviceType) { var serviceInstance = DefaultResolveInstance(serviceType, null); if (serviceInstance is null && serviceType.IsAbstract()) { throw new NLogDependencyResolveException("Instance of class must be registered", serviceType); } return serviceInstance; } internal override bool TryGetService<T>(out T serviceInstance) { serviceInstance = DefaultResolveInstance(typeof(T), null) as T; return !(serviceInstance is null); } private object DefaultResolveInstance(Type itemType, HashSet<Type> seenTypes) { Guard.ThrowIfNull(itemType); Func<object> objectResolver = null; CompiledConstructor compiledConstructor = null; lock (_lockObject) { if (!_creatorMap.TryGetValue(itemType, out objectResolver)) { _lateBoundMap.TryGetValue(itemType, out compiledConstructor); } } if (objectResolver is null && compiledConstructor is null) { if (itemType.IsAbstract()) { if (seenTypes is null) return null; else throw new NLogDependencyResolveException("Instance of class must be registered", itemType); } // Do not hold lock while resolving types to avoid deadlock on initialization of type static members #pragma warning disable CS0618 // Type or member is obsolete var newCompiledConstructor = CreateCompiledConstructor(itemType); #pragma warning restore CS0618 // Type or member is obsolete lock (_lockObject) { if (!_lateBoundMap.TryGetValue(itemType, out compiledConstructor)) { _lateBoundMap.Add(itemType, newCompiledConstructor); compiledConstructor = newCompiledConstructor; } } } // Do not hold lock while calling constructor (or resolving parameter values) to avoid deadlock var constructorParameters = compiledConstructor?.Parameters; if (constructorParameters is null) { return objectResolver?.Invoke() ?? compiledConstructor?.Ctor(null); } else { seenTypes = seenTypes ?? new HashSet<Type>(); var parameterValues = CreateCtorParameterValues(constructorParameters, seenTypes); return compiledConstructor?.Ctor(parameterValues); } } [Obsolete("Instead use NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2070")] private CompiledConstructor CreateCompiledConstructor(Type itemType) { try { InternalLogger.Debug("Object reflection needed to create instance of type: {0}", itemType); var defaultConstructor = itemType.GetConstructor(Type.EmptyTypes); if (defaultConstructor is null) { InternalLogger.Trace("Resolves parameterized constructor for {0}", itemType); var ctors = itemType.GetConstructors(); if (ctors.Length == 0) { throw new NLogDependencyResolveException("No public constructor", itemType); } if (ctors.Length > 1) { throw new NLogDependencyResolveException("Multiple public constructor are not supported if there isn't a default constructor'", itemType); } var ctor = ctors[0]; var constructorMethod = ReflectionHelpers.CreateLateBoundConstructor(ctor); return new CompiledConstructor(constructorMethod, ctor.GetParameters()); } else { InternalLogger.Trace("Resolves default constructor for {0}", itemType); var constructorMethod = ReflectionHelpers.CreateLateBoundConstructor(defaultConstructor); return new CompiledConstructor(constructorMethod); } } catch (MissingMethodException exception) { throw new NLogDependencyResolveException("Is the required permission granted?", exception, itemType); } finally { InternalLogger.Trace("Resolve {0} done", itemType.FullName); } } private object[] CreateCtorParameterValues(ParameterInfo[] parameterInfos, HashSet<Type> seenTypes) { var parameterValues = new object[parameterInfos.Length]; for (var i = 0; i < parameterInfos.Length; i++) { var param = parameterInfos[i]; var parameterType = param.ParameterType; if (seenTypes.Contains(parameterType)) { throw new NLogDependencyResolveException("There is a cycle", parameterType); } seenTypes.Add(parameterType); var paramValue = DefaultResolveInstance(parameterType, seenTypes); parameterValues[i] = paramValue; } return parameterValues; } private sealed class CompiledConstructor { [NotNull] public ReflectionHelpers.LateBoundConstructor Ctor { get; } [CanBeNull] public ParameterInfo[] Parameters { get; } public CompiledConstructor([NotNull] ReflectionHelpers.LateBoundConstructor ctor, ParameterInfo[] parameters = null) { Ctor = Guard.ThrowIfNull(ctor); Parameters = parameters; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 namespace NLog.Targets { using System; using System.Collections.Generic; using System.IO; using System.Text; /// <summary> /// Color formatting for <see cref="ColoredConsoleTarget"/> using ANSI Color Codes /// </summary> internal class ColoredConsoleAnsiPrinter : IColoredConsolePrinter { public TextWriter AcquireTextWriter(TextWriter consoleStream, StringBuilder reusableBuilder) { // Writes into an in-memory console writer for sake of optimizations (Possible when not using system-colors) return new StringWriter(reusableBuilder ?? new StringBuilder(50), consoleStream.FormatProvider); } public void ReleaseTextWriter(TextWriter consoleWriter, TextWriter consoleStream, ConsoleColor? oldForegroundColor, ConsoleColor? oldBackgroundColor, bool flush) { // Flushes the in-memory console-writer to the actual console-stream var builder = (consoleWriter as StringWriter)?.GetStringBuilder(); if (builder != null) { builder.Append(TerminalDefaultColorEscapeCode); ConsoleTargetHelper.WriteLineThreadSafe(consoleStream, builder.ToString(), flush); } } public ConsoleColor? ChangeForegroundColor(TextWriter consoleWriter, ConsoleColor? foregroundColor, ConsoleColor? oldForegroundColor = null) { if (foregroundColor.HasValue) { consoleWriter.Write(GetForegroundColorEscapeCode(foregroundColor.Value)); } return null; // There is no "old" console color } public ConsoleColor? ChangeBackgroundColor(TextWriter consoleWriter, ConsoleColor? backgroundColor, ConsoleColor? oldBackgroundColor = null) { if (backgroundColor.HasValue) { consoleWriter.Write(GetBackgroundColorEscapeCode(backgroundColor.Value)); } return null; // There is no "old" console color } public void ResetDefaultColors(TextWriter consoleWriter, ConsoleColor? foregroundColor, ConsoleColor? backgroundColor) { consoleWriter.Write(TerminalDefaultColorEscapeCode); } public void WriteSubString(TextWriter consoleWriter, string text, int index, int endIndex) { // No need to allocate SubString, because we are already writing in-memory for (int i = index; i < endIndex; ++i) consoleWriter.Write(text[i]); } public void WriteChar(TextWriter consoleWriter, char text) { consoleWriter.Write(text); } public void WriteLine(TextWriter consoleWriter, string text) { consoleWriter.Write(text); // Newline is added when flushing to actual console-stream } /// <summary> /// Not using bold to get light colors, as it has to be cleared /// </summary> private static string GetForegroundColorEscapeCode(ConsoleColor color) { switch (color) { case ConsoleColor.Black: return "\x1B[30m"; case ConsoleColor.Blue: return "\x1B[94m"; case ConsoleColor.Cyan: return "\x1B[96m"; case ConsoleColor.DarkBlue: return "\x1B[34m"; case ConsoleColor.DarkCyan: return "\x1B[36m"; case ConsoleColor.DarkGray: return "\x1B[90m"; case ConsoleColor.DarkGreen: return "\x1B[32m"; case ConsoleColor.DarkMagenta: return "\x1B[35m"; case ConsoleColor.DarkRed: return "\x1B[31m"; case ConsoleColor.DarkYellow: return "\x1B[33m"; case ConsoleColor.Gray: return "\x1B[37m"; case ConsoleColor.Green: return "\x1B[92m"; case ConsoleColor.Magenta: return "\x1B[95m"; case ConsoleColor.Red: return "\x1B[91m"; case ConsoleColor.White: return "\x1b[97m"; case ConsoleColor.Yellow: return "\x1B[93m"; default: return TerminalDefaultForegroundColorEscapeCode; // default foreground color } } private static string TerminalDefaultForegroundColorEscapeCode { get { return "\x1B[39m\x1B[22m"; } } /// <summary> /// Not using bold to get light colors, as it has to be cleared (And because it only works for text, and not background) /// </summary> private static string GetBackgroundColorEscapeCode(ConsoleColor color) { switch (color) { case ConsoleColor.Black: return "\x1B[40m"; case ConsoleColor.Blue: return "\x1B[104m"; case ConsoleColor.Cyan: return "\x1B[106m"; case ConsoleColor.DarkBlue: return "\x1B[44m"; case ConsoleColor.DarkCyan: return "\x1B[46m"; case ConsoleColor.DarkGray: return "\x1B[100m"; case ConsoleColor.DarkGreen: return "\x1B[42m"; case ConsoleColor.DarkMagenta: return "\x1B[45m"; case ConsoleColor.DarkRed: return "\x1B[41m"; case ConsoleColor.DarkYellow: return "\x1B[43m"; case ConsoleColor.Gray: return "\x1B[47m"; case ConsoleColor.Green: return "\x1B[102m"; case ConsoleColor.Magenta: return "\x1B[105m"; case ConsoleColor.Red: return "\x1B[101m"; case ConsoleColor.White: return "\x1B[107m"; case ConsoleColor.Yellow: return "\x1B[103m"; default: return TerminalDefaultBackgroundColorEscapeCode; } } private static string TerminalDefaultBackgroundColorEscapeCode { get { return "\x1B[49m"; } } /// <summary> /// Resets both foreground and background color. /// </summary> private static string TerminalDefaultColorEscapeCode { get { return "\x1B[0m"; } } /// <summary> /// ANSI have 8 color-codes (30-37) by default. The "bright" (or "intense") color-codes (90-97) are extended values not supported by all terminals /// </summary> public IList<ConsoleRowHighlightingRule> DefaultConsoleRowHighlightingRules { get; } = new List<ConsoleRowHighlightingRule>() { new ConsoleRowHighlightingRule("level == LogLevel.Fatal", ConsoleOutputColor.DarkRed, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Error", ConsoleOutputColor.DarkYellow, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Warn", ConsoleOutputColor.DarkMagenta, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Info", ConsoleOutputColor.NoChange, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Debug", ConsoleOutputColor.NoChange, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule("level == LogLevel.Trace", ConsoleOutputColor.NoChange, ConsoleOutputColor.NoChange), }; } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Reflection; using Xunit.Abstractions; using Xunit.Sdk; [assembly: Xunit.CollectionBehavior(DisableTestParallelization = true)] [assembly: Xunit.TestFramework("NLogThrowExceptionsDefault", "NLog.UnitTests")] public class NLogThrowExceptionsDefault : XunitTestFramework { public NLogThrowExceptionsDefault(IMessageSink messageSink) :base(messageSink) { NLog.LogManager.ThrowExceptions = true; // Ensure exceptions are thrown by default during unit-testing } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Internal.FileAppenders { using System; using System.IO; using System.Text; using Xunit; using NLog.Targets; using NLog.Internal.FileAppenders; public class FileAppenderCacheTests : NLogTestBase { [Fact] public void FileAppenderCache_Empty() { FileAppenderCache cache = FileAppenderCache.Empty; // An empty FileAppenderCache will have Size = 0 as well as Factory and CreateFileParameters parameters equal to null. Assert.True(cache.Size == 0); Assert.Null(cache.Factory); Assert.Null(cache.CreateFileParameters); } [Fact] public void FileAppenderCache_Construction() { IFileAppenderFactory appenderFactory = SingleProcessFileAppender.TheFactory; ICreateFileParameters fileTarget = new FileTarget(); FileAppenderCache cache = new FileAppenderCache(3, appenderFactory, fileTarget); Assert.True(cache.Size == 3); Assert.NotNull(cache.Factory); Assert.NotNull(cache.CreateFileParameters); } [Fact] public void FileAppenderCache_Allocate() { // Allocate on an Empty FileAppenderCache. FileAppenderCache emptyCache = FileAppenderCache.Empty; Assert.Throws<NullReferenceException>(() => emptyCache.AllocateAppender("file.txt")); // Construct a on non-empty FileAppenderCache. IFileAppenderFactory appenderFactory = SingleProcessFileAppender.TheFactory; ICreateFileParameters fileTarget = new FileTarget(); String tempFile = Path.Combine( Path.GetTempPath(), Path.Combine(Guid.NewGuid().ToString(), "file.txt") ); // Allocate an appender. FileAppenderCache cache = new FileAppenderCache(3, appenderFactory, fileTarget); BaseFileAppender appender = cache.AllocateAppender(tempFile); // // Note: Encoding is ASSUMED to be Unicode. There is no explicit reference to which encoding will be used // for the file. // // Write, flush the content into the file and release the file. // We need to release the file before invoking AssertFileContents() method. appender.Write(StringToBytes("NLog test string.")); appender.Flush(); appender.Close(); // Verify the appender has been allocated correctly. AssertFileContents(tempFile, "NLog test string.", Encoding.Unicode); } [Fact] public void FileAppenderCache_InvalidateAppender() { // Invoke InvalidateAppender() on an Empty FileAppenderCache. FileAppenderCache emptyCache = FileAppenderCache.Empty; emptyCache.InvalidateAppender("file.txt"); // Construct a on non-empty FileAppenderCache. IFileAppenderFactory appenderFactory = SingleProcessFileAppender.TheFactory; ICreateFileParameters fileTarget = new FileTarget(); String tempFile = Path.Combine( Path.GetTempPath(), Path.Combine(Guid.NewGuid().ToString(), "file.txt") ); // Allocate an appender. FileAppenderCache cache = new FileAppenderCache(3, appenderFactory, fileTarget); BaseFileAppender appender = cache.AllocateAppender(tempFile); // // Note: Encoding is ASSUMED to be Unicode. There is no explicit reference to which encoding will be used // for the file. // // Write, flush the content into the file and release the file. This happens through the // InvalidateAppender() method. We need to release the file before invoking AssertFileContents() method. appender.Write(StringToBytes("NLog test string.")); cache.InvalidateAppender(tempFile); // Verify the appender has been allocated correctly. AssertFileContents(tempFile, "NLog test string.", Encoding.Unicode); } [Fact] public void FileAppenderCache_CloseAppenders() { // Invoke CloseAppenders() on an Empty FileAppenderCache. FileAppenderCache emptyCache = FileAppenderCache.Empty; emptyCache.CloseAppenders(string.Empty); emptyCache.CloseExpiredAppenders(DateTime.UtcNow); IFileAppenderFactory appenderFactory = RetryingMultiProcessFileAppender.TheFactory; ICreateFileParameters fileTarget = new FileTarget(); FileAppenderCache cache = new FileAppenderCache(3, appenderFactory, fileTarget); // Invoke CloseAppenders() on non-empty FileAppenderCache - Before allocating any appenders. cache.CloseAppenders(string.Empty); // Invoke CloseAppenders() on non-empty FileAppenderCache - After allocating N appenders. cache.AllocateAppender("file1.txt"); cache.AllocateAppender("file2.txt"); cache.CloseAppenders(string.Empty); // Invoke CloseAppenders() on non-empty FileAppenderCache - After allocating N appenders. cache.AllocateAppender("file1.txt"); cache.AllocateAppender("file2.txt"); cache.CloseAppenders(string.Empty); FileAppenderCache cache2 = new FileAppenderCache(3, appenderFactory, fileTarget); // Invoke CloseAppenders() on non-empty FileAppenderCache - Before allocating any appenders. cache2.CloseExpiredAppenders(DateTime.UtcNow); // Invoke CloseAppenders() on non-empty FileAppenderCache - After allocating N appenders. cache.AllocateAppender("file1.txt"); cache.AllocateAppender("file2.txt"); cache.CloseExpiredAppenders(DateTime.UtcNow.AddMinutes(-1)); var appenderFile1 = cache.InvalidateAppender("file1.txt"); Assert.NotNull(appenderFile1); var appenderFile2 = cache.InvalidateAppender("file2.txt"); Assert.NotNull(appenderFile2); cache.AllocateAppender("file3.txt"); cache.AllocateAppender("file4.txt"); cache.CloseExpiredAppenders(DateTime.UtcNow.AddMinutes(1)); var appenderFile3 = cache.InvalidateAppender("file3.txt"); Assert.Null(appenderFile3); var appenderFile4 = cache.InvalidateAppender("file4.txt"); Assert.Null(appenderFile4); } [Fact] public void FileAppenderCache_GetFileCharacteristics_Single() { IFileAppenderFactory appenderFactory = SingleProcessFileAppender.TheFactory; ICreateFileParameters fileTarget = new FileTarget() { ArchiveNumbering = ArchiveNumberingMode.Date }; FileAppenderCache_GetFileCharacteristics(appenderFactory, fileTarget); } [Fact] public void FileAppenderCache_GetFileCharacteristics_Multi() { IFileAppenderFactory appenderFactory = MutexMultiProcessFileAppender.TheFactory; ICreateFileParameters fileTarget = new FileTarget() { ArchiveNumbering = ArchiveNumberingMode.Date, ForceManaged = true }; FileAppenderCache_GetFileCharacteristics(appenderFactory, fileTarget); } #if !MONO && !NETSTANDARD [Fact] public void FileAppenderCache_GetFileCharacteristics_Windows() { if (NLog.Internal.PlatformDetector.IsWin32) { IFileAppenderFactory appenderFactory = WindowsMultiProcessFileAppender.TheFactory; ICreateFileParameters fileTarget = new FileTarget() { ArchiveNumbering = ArchiveNumberingMode.Date }; FileAppenderCache_GetFileCharacteristics(appenderFactory, fileTarget); } } #endif private static void FileAppenderCache_GetFileCharacteristics(IFileAppenderFactory appenderFactory, ICreateFileParameters fileParameters) { // Invoke GetFileCharacteristics() on an Empty FileAppenderCache. FileAppenderCache emptyCache = FileAppenderCache.Empty; Assert.Null(emptyCache.GetFileCreationTimeSource("file.txt")); Assert.Null(emptyCache.GetFileLastWriteTimeUtc("file.txt")); Assert.Null(emptyCache.GetFileLength("file.txt")); FileAppenderCache cache = new FileAppenderCache(3, appenderFactory, fileParameters); // Invoke GetFileCharacteristics() on non-empty FileAppenderCache - Before allocating any appenders. Assert.Null(emptyCache.GetFileCreationTimeSource("file.txt")); Assert.Null(emptyCache.GetFileLastWriteTimeUtc("file.txt")); Assert.Null(emptyCache.GetFileLength("file.txt")); String tempFile = Path.Combine( Path.GetTempPath(), Path.Combine(Guid.NewGuid().ToString(), "file.txt") ); // Allocate an appender. BaseFileAppender appender = cache.AllocateAppender(tempFile); appender.Write(StringToBytes("NLog test string.")); // // Note: Encoding is ASSUMED to be Unicode. There is no explicit reference to which encoding will be used // for the file. // // File information should be returned. var fileCreationTimeUtc = cache.GetFileCreationTimeSource(tempFile); Assert.NotNull(fileCreationTimeUtc); Assert.True(fileCreationTimeUtc > Time.TimeSource.Current.FromSystemTime(DateTime.UtcNow.AddMinutes(-2)),"creationtime is wrong"); var fileLastWriteTimeUtc = cache.GetFileLastWriteTimeUtc(tempFile); Assert.NotNull(fileLastWriteTimeUtc); Assert.True(fileLastWriteTimeUtc > DateTime.UtcNow.AddMinutes(-2), "lastwrite is wrong"); Assert.Equal(34, cache.GetFileLength(tempFile)); // Clean up. appender.Flush(); appender.Close(); } /// <summary> /// Converts a string to byte array. /// </summary> private static byte[] StringToBytes(string text) { byte[] bytes = new byte[sizeof(char) * text.Length]; Buffer.BlockCopy(text.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Common { using System; /// <summary> /// A cyclic buffer of <see cref="LogEventInfo"/> object. /// </summary> [Obsolete("Use AsyncRequestQueue instead. Marked obsolete on NLog 5.0")] public class LogEventInfoBuffer { private readonly object _lockObject = new object(); private readonly bool _growAsNeeded; private readonly int _growLimit; private AsyncLogEventInfo[] _buffer; private int _getPointer; private int _putPointer; private int _count; /// <summary> /// Initializes a new instance of the <see cref="LogEventInfoBuffer" /> class. /// </summary> /// <param name="size">Buffer size.</param> /// <param name="growAsNeeded">Whether buffer should grow as it becomes full.</param> /// <param name="growLimit">The maximum number of items that the buffer can grow to.</param> public LogEventInfoBuffer(int size, bool growAsNeeded, int growLimit) { _growAsNeeded = growAsNeeded; _buffer = new AsyncLogEventInfo[size]; _growLimit = growLimit; _getPointer = 0; _putPointer = 0; } /// <summary> /// Gets the capacity of the buffer /// </summary> public int Size => _buffer.Length; /// <summary> /// Gets the number of items in the buffer /// </summary> internal int Count { get { lock (_lockObject) return _count; } } /// <summary> /// Adds the specified log event to the buffer. /// </summary> /// <param name="eventInfo">Log event.</param> /// <returns>The number of items in the buffer.</returns> public int Append(AsyncLogEventInfo eventInfo) { lock (_lockObject) { // make room for additional item if (_count >= _buffer.Length) { if (_growAsNeeded && _buffer.Length < _growLimit) { // create a new buffer, copy data from current int newLength = _buffer.Length * 2; if (newLength >= _growLimit) { newLength = _growLimit; } InternalLogger.Trace("Enlarging LogEventInfoBuffer from {0} to {1}", _buffer.Length, newLength); var newBuffer = new AsyncLogEventInfo[newLength]; Array.Copy(_buffer, 0, newBuffer, 0, _buffer.Length); _buffer = newBuffer; } else { // lose the oldest item _getPointer = _getPointer + 1; } } // put the item _putPointer = _putPointer % _buffer.Length; _buffer[_putPointer] = eventInfo; _putPointer = _putPointer + 1; _count++; if (_count >= _buffer.Length) { _count = _buffer.Length; } return _count; } } /// <summary> /// Gets the array of events accumulated in the buffer and clears the buffer as one atomic operation. /// </summary> /// <returns>Events in the buffer.</returns> public AsyncLogEventInfo[] GetEventsAndClear() { lock (_lockObject) { int cnt = _count; if (cnt == 0) return Internal.ArrayHelper.Empty<AsyncLogEventInfo>(); var returnValue = new AsyncLogEventInfo[cnt]; for (int i = 0; i < cnt; ++i) { int p = (_getPointer + i) % _buffer.Length; var e = _buffer[p]; _buffer[p] = default(AsyncLogEventInfo); // we don't want memory leaks returnValue[i] = e; } _count = 0; _getPointer = 0; _putPointer = 0; return returnValue; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Internal { using System; using System.Linq; using System.Collections.Generic; using NLog.MessageTemplates; using Xunit; using NLog.Internal; public class PropertiesDictionaryTests : NLogTestBase { [Fact] public void DefaultPropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(); IDictionary<object, object> dictionary = logEvent.Properties; Assert.Empty(dictionary); foreach (var item in dictionary) Assert.False(true, "Should be empty"); foreach (var item in dictionary.Keys) Assert.False(true, "Should be empty"); foreach (var item in dictionary.Values) Assert.False(true, "Should be empty"); Assert.DoesNotContain("Hello World", dictionary); Assert.False(dictionary.ContainsKey("Hello World")); Assert.False(dictionary.Keys.Contains("Hello World")); Assert.False(dictionary.Values.Contains(42)); object value; Assert.False(dictionary.TryGetValue("Hello World", out value)); Assert.Null(value); Assert.False(dictionary.Remove("Hello World")); dictionary.CopyTo(ArrayHelper.Empty<KeyValuePair<object, object>>(), 0); dictionary.Values.CopyTo(ArrayHelper.Empty<object>(), 0); dictionary.Keys.CopyTo(ArrayHelper.Empty<object>(), 0); dictionary.Clear(); } [Fact] public void EmptyEventPropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(); IDictionary<object, object> dictionary = logEvent.Properties; dictionary.Add("Hello World", 42); Assert.True(dictionary.Remove("Hello World")); Assert.Empty(dictionary); foreach (var item in dictionary) Assert.False(true, "Should be empty"); foreach (var item in dictionary.Keys) Assert.False(true, "Should be empty"); foreach (var item in dictionary.Values) Assert.False(true, "Should be empty"); Assert.DoesNotContain("Hello World", dictionary); Assert.False(dictionary.ContainsKey("Hello World")); Assert.False(dictionary.Keys.Contains("Hello World")); Assert.False(dictionary.Values.Contains(42)); object value; Assert.False(dictionary.TryGetValue("Hello World", out value)); Assert.Null(value); Assert.False(dictionary.Remove("Hello World")); dictionary.CopyTo(ArrayHelper.Empty<KeyValuePair<object, object>>(), 0); dictionary.Values.CopyTo(ArrayHelper.Empty<object>(), 0); dictionary.Keys.CopyTo(ArrayHelper.Empty<object>(), 0); dictionary.Clear(); } [Fact] public void EmptyMessagePropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", string.Empty, (IList<MessageTemplateParameter>)null); IDictionary<object, object> dictionary = logEvent.Properties; Assert.Empty(dictionary); foreach (var item in dictionary) Assert.False(true, "Should be empty"); foreach (var item in dictionary.Keys) Assert.False(true, "Should be empty"); foreach (var item in dictionary.Values) Assert.False(true, "Should be empty"); Assert.False(dictionary.ContainsKey("Hello World")); Assert.False(dictionary.Keys.Contains("Hello World")); Assert.False(dictionary.Values.Contains(42)); Assert.DoesNotContain("Hello World", dictionary); object value; Assert.False(dictionary.TryGetValue("Hello World", out value)); Assert.Null(value); Assert.False(dictionary.Remove("Hello World")); dictionary.CopyTo(ArrayHelper.Empty<KeyValuePair<object, object>>(), 0); dictionary.Values.CopyTo(new object[0], 0); dictionary.Keys.CopyTo(new object[0], 0); dictionary.Clear(); } [Fact] public void EmptyPropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", string.Empty, (IList<MessageTemplateParameter>)null); IDictionary<object, object> dictionary = logEvent.Properties; dictionary.Add("Hello World", null); Assert.True(dictionary.Remove("Hello World")); Assert.Empty(dictionary); foreach (var item in dictionary) Assert.False(true, "Should be empty"); foreach (var item in dictionary.Keys) Assert.False(true, "Should be empty"); foreach (var item in dictionary.Values) Assert.False(true, "Should be empty"); Assert.False(dictionary.ContainsKey("Hello World")); Assert.False(dictionary.Keys.Contains("Hello World")); Assert.False(dictionary.Values.Contains(42)); Assert.DoesNotContain("Hello World", dictionary); object value; Assert.False(dictionary.TryGetValue("Hello World", out value)); Assert.Null(value); Assert.False(dictionary.Remove("Hello World")); dictionary.CopyTo(ArrayHelper.Empty<KeyValuePair<object, object>>(), 0); dictionary.Values.CopyTo(ArrayHelper.Empty<object>(), 0); dictionary.Keys.CopyTo(ArrayHelper.Empty<object>(), 0); dictionary.Clear(); } [Fact] public void SingleItemEventPropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(); IDictionary<object, object> dictionary = logEvent.Properties; dictionary.Add("Hello World", 42); Assert.Single(dictionary); foreach (var item in dictionary) { Assert.Equal("Hello World", item.Key); Assert.Equal(42, item.Value); } foreach (var item in dictionary.Keys) Assert.Equal("Hello World", item); foreach (var item in dictionary.Values) Assert.Equal(42, item); AssertContainsInDictionary(dictionary, "Hello World", 42); Assert.True(dictionary.ContainsKey("Hello World")); Assert.True(dictionary.Keys.Contains("Hello World")); Assert.True(dictionary.Values.Contains(42)); Assert.False(dictionary.ContainsKey("Goodbye World")); Assert.False(dictionary.Keys.Contains("Goodbye World")); Assert.DoesNotContain("Goodbye World", dictionary); object value; Assert.True(dictionary.TryGetValue("Hello World", out value)); Assert.Equal(42, value); Assert.False(dictionary.TryGetValue("Goodbye World", out value)); Assert.Null(value); var copyToArray = new KeyValuePair<object, object>[1]; dictionary.CopyTo(copyToArray, 0); Assert.Equal("Hello World", copyToArray[0].Key); Assert.Equal(42, copyToArray[0].Value); var copyToValuesArray = new object[1]; dictionary.Values.CopyTo(copyToValuesArray, 0); Assert.Equal(42, copyToValuesArray[0]); var copyToKeysArray = new object[1]; dictionary.Keys.CopyTo(copyToKeysArray, 0); Assert.Equal("Hello World", copyToKeysArray[0]); Assert.True(dictionary.Remove("Hello World")); Assert.Empty(dictionary); dictionary["Hello World"] = 42; Assert.Single(dictionary); dictionary.Clear(); Assert.Empty(dictionary); } [Fact] public void SingleItemMessagePropertiesDictionaryNoLookup() { LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", string.Empty, new[] { new MessageTemplateParameter("Hello World", 42, null, CaptureType.Normal) }); IDictionary<object, object> dictionary = logEvent.Properties; Assert.Single(dictionary); foreach (var item in dictionary) { Assert.Equal("Hello World", item.Key); Assert.Equal(42, item.Value); } foreach (var item in dictionary.Keys) Assert.Equal("Hello World", item); foreach (var item in dictionary.Values) Assert.Equal(42, item); var copyToArray = new KeyValuePair<object, object>[1]; dictionary.CopyTo(copyToArray, 0); Assert.Equal("Hello World", copyToArray[0].Key); Assert.Equal(42, copyToArray[0].Value); var copyToValuesArray = new object[1]; dictionary.Values.CopyTo(copyToValuesArray, 0); Assert.Equal(42, copyToValuesArray[0]); var copyToKeysArray = new object[1]; dictionary.Keys.CopyTo(copyToKeysArray, 0); Assert.Equal("Hello World", copyToKeysArray[0]); dictionary.Clear(); Assert.Empty(dictionary); } [Fact] public void SingleItemMessagePropertiesDictionaryWithLookup() { LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", string.Empty, new[] { new MessageTemplateParameter("Hello World", 42, null, CaptureType.Normal) }); IDictionary<object, object> dictionary = logEvent.Properties; Assert.Single(dictionary); AssertContainsInDictionary(dictionary, "Hello World", 42); Assert.True(dictionary.ContainsKey("Hello World")); Assert.True(dictionary.Keys.Contains("Hello World")); Assert.True(dictionary.Values.Contains(42)); Assert.False(dictionary.ContainsKey("Goodbye World")); Assert.False(dictionary.Keys.Contains("Goodbye World")); Assert.DoesNotContain("Goodbye World", dictionary); object value; Assert.True(dictionary.TryGetValue("Hello World", out value)); Assert.Equal(42, value); Assert.False(dictionary.TryGetValue("Goodbye World", out value)); Assert.Null(value); var copyToArray = new KeyValuePair<object, object>[1]; dictionary.CopyTo(copyToArray, 0); Assert.Equal("Hello World", copyToArray[0].Key); Assert.Equal(42, copyToArray[0].Value); var copyToValuesArray = new object[1]; dictionary.Values.CopyTo(copyToValuesArray, 0); Assert.Equal(42, copyToValuesArray[0]); var copyToKeysArray = new object[1]; dictionary.Keys.CopyTo(copyToKeysArray, 0); Assert.Equal("Hello World", copyToKeysArray[0]); dictionary.Clear(); Assert.Empty(dictionary); } [Fact] public void MultiItemPropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", string.Empty, new[] { new MessageTemplateParameter("Hello World", 42, null, CaptureType.Normal) }); IDictionary<object, object> dictionary = logEvent.Properties; dictionary["Goodbye World"] = 666; Assert.Equal(2, dictionary.Count); int i = 0; foreach (var item in dictionary) { switch (i++) { case 0: Assert.Equal("Hello World", item.Key); Assert.Equal(42, item.Value); break; case 1: Assert.Equal("Goodbye World", item.Key); Assert.Equal(666, item.Value); break; } } Assert.Equal(2, i); i = 0; foreach (var item in dictionary.Keys) { switch (i++) { case 0: Assert.Equal("Hello World", item); break; case 1: Assert.Equal("Goodbye World", item); break; } } Assert.Equal(2, i); i = 0; foreach (var item in dictionary.Values) { switch (i++) { case 0: Assert.Equal(42, item); break; case 1: Assert.Equal(666, item); break; } } Assert.True(dictionary.ContainsKey("Hello World")); AssertContainsInDictionary(dictionary, "Hello World", 42); Assert.True(dictionary.Keys.Contains("Hello World")); Assert.True(dictionary.Values.Contains(42)); Assert.True(dictionary.ContainsKey("Goodbye World")); AssertContainsInDictionary(dictionary, "Goodbye World", 666); Assert.True(dictionary.Keys.Contains("Goodbye World")); Assert.True(dictionary.Values.Contains(666)); Assert.False(dictionary.Keys.Contains("Mad World")); Assert.False(dictionary.ContainsKey("Mad World")); object value; Assert.True(dictionary.TryGetValue("Hello World", out value)); Assert.Equal(42, value); Assert.True(dictionary.TryGetValue("Goodbye World", out value)); Assert.Equal(666, value); Assert.False(dictionary.TryGetValue("Mad World", out value)); Assert.Null(value); var copyToArray = new KeyValuePair<object, object>[2]; dictionary.CopyTo(copyToArray, 0); Assert.Contains(new KeyValuePair<object, object>("Hello World", 42), copyToArray); Assert.Contains(new KeyValuePair<object, object>("Goodbye World", 666), copyToArray); var copyToValuesArray = new object[2]; dictionary.Values.CopyTo(copyToValuesArray, 0); Assert.Contains(42, copyToValuesArray); Assert.Contains(666, copyToValuesArray); var copyToKeysArray = new object[2]; dictionary.Keys.CopyTo(copyToKeysArray, 0); Assert.Contains("Hello World", copyToKeysArray); Assert.Contains("Goodbye World", copyToKeysArray); Assert.True(dictionary.Remove("Goodbye World")); Assert.Single(dictionary); dictionary["Goodbye World"] = 666; Assert.Equal(2, dictionary.Count); dictionary.Clear(); Assert.Empty(dictionary); } [Fact] public void OverrideMessagePropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", string.Empty, new[] { new MessageTemplateParameter("Hello World", 42, null, CaptureType.Normal), new MessageTemplateParameter("Goodbye World", 666, null, CaptureType.Normal) }); IDictionary<object, object> dictionary = logEvent.Properties; Assert.Equal(42, dictionary["Hello World"]); dictionary["Hello World"] = 999; Assert.Equal(999, dictionary["Hello World"]); Assert.True(dictionary.Values.Contains(999)); Assert.True(dictionary.Values.Contains(666)); Assert.False(dictionary.Values.Contains(42)); int i = 0; foreach (var item in dictionary) { switch (i++) { case 1: Assert.Equal("Hello World", item.Key); Assert.Equal(999, item.Value); break; case 0: Assert.Equal("Goodbye World", item.Key); Assert.Equal(666, item.Value); break; } } Assert.Equal(2, i); i = 0; foreach (var item in dictionary.Keys) { switch (i++) { case 1: Assert.Equal("Hello World", item); break; case 0: Assert.Equal("Goodbye World", item); break; } } Assert.Equal(2, i); i = 0; foreach (var item in dictionary.Values) { switch (i++) { case 1: Assert.Equal(999, item); break; case 0: Assert.Equal(666, item); break; } } dictionary["Goodbye World"] = 42; i = 0; foreach (var item in dictionary.Keys) { switch (i++) { case 0: Assert.Equal("Hello World", item); break; case 1: Assert.Equal("Goodbye World", item); break; } } Assert.Equal(2, i); dictionary.Remove("Hello World"); Assert.Single(dictionary); dictionary.Remove("Goodbye World"); Assert.Empty(dictionary); } [Fact] public void NonUniqueMessagePropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", string.Empty, new[] { new MessageTemplateParameter("Hello World", 42, null, CaptureType.Normal), new MessageTemplateParameter("Hello World", 666, null, CaptureType.Normal) }); IDictionary<object, object> dictionary = logEvent.Properties; Assert.Equal(2, dictionary.Count); Assert.Equal(42, dictionary["Hello World"]); Assert.Equal(666, dictionary["Hello World_1"]); foreach (var property in dictionary) { if (property.Value.Equals(42)) Assert.Equal("Hello World", property.Key); else if (property.Value.Equals(666)) Assert.Equal("Hello World_1", property.Key); else Assert.Null(property.Key); } } #if !NET35 [Fact] public void NonUniqueEventPropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", string.Empty, new[] { new KeyValuePair<object,object>("Hello World", 42), new KeyValuePair<object,object>("Hello World", 666), }); IDictionary<object, object> dictionary = logEvent.Properties; Assert.Single(dictionary); Assert.Equal(666, dictionary["Hello World"]); // Last one wins } #endif } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; namespace NLog.Internal.FileAppenders { internal interface IFileAppenderCache : IDisposable { /// <summary> /// Gets the parameters which will be used for creating a file. /// </summary> ICreateFileParameters CreateFileParameters { get; } /// <summary> /// Gets the file appender factory used by all the appenders in this list. /// </summary> IFileAppenderFactory Factory { get; } /// <summary> /// Gets the number of appenders which the list can hold. /// </summary> int Size { get; } /// <summary> /// Subscribe to background monitoring of active file appenders /// </summary> event EventHandler CheckCloseAppenders; /// <summary> /// It allocates the first slot in the list when the file name does not already in the list and clean up any /// unused slots. /// </summary> /// <param name="fileName">File name associated with a single appender.</param> /// <returns>The allocated appender.</returns> BaseFileAppender AllocateAppender(string fileName); /// <summary> /// Close all the allocated appenders. /// </summary> void CloseAppenders(string reason); /// <summary> /// Close the allocated appenders initialized before the supplied time. /// </summary> /// <param name="expireTimeUtc">The time which prior the appenders considered expired</param> void CloseExpiredAppenders(DateTime expireTimeUtc); /// <summary> /// Flush all the allocated appenders. /// </summary> void FlushAppenders(); DateTime? GetFileCreationTimeSource(string filePath, DateTime? fallbackTimeSource = null); /// <summary> /// File Archive Logic uses the File-Creation-TimeStamp to detect if time to archive, and the File-LastWrite-Timestamp to name the archive-file. /// </summary> /// <remarks> /// NLog always closes all relevant appenders during archive operation, so no need to lookup file-appender /// </remarks> DateTime? GetFileLastWriteTimeUtc(string filePath); long? GetFileLength(string filePath); /// <summary> /// Closes the specified appender and removes it from the list. /// </summary> /// <param name="filePath">File name of the appender to be closed.</param> /// <returns>File Appender that matched the filePath (null if none found)</returns> BaseFileAppender InvalidateAppender(string filePath); #if !NETSTANDARD1_3 /// <summary> /// The archive file path pattern that is used to detect when archiving occurs. /// </summary> string ArchiveFilePatternToWatch { get; set; } /// <summary> /// Invalidates appenders for all files that were archived. /// </summary> void InvalidateAppendersForArchivedFiles(); #endif } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Internal { using System; using System.Collections; using System.Collections.Generic; /// <summary> /// Special Expando-Object that has custom object-value (Similar to JObject) /// </summary> internal class ExpandoTestDictionary : IDictionary<string, IFormattable> { private readonly Dictionary<string, IFormattable> _properties = new Dictionary<string, IFormattable>(); public IFormattable this[string key] { get => ((IDictionary<string, IFormattable>)_properties)[key]; set => ((IDictionary<string, IFormattable>)_properties)[key] = value; } public ICollection<string> Keys => ((IDictionary<string, IFormattable>)_properties).Keys; public ICollection<IFormattable> Values => ((IDictionary<string, IFormattable>)_properties).Values; public int Count => ((IDictionary<string, IFormattable>)_properties).Count; public bool IsReadOnly => ((IDictionary<string, IFormattable>)_properties).IsReadOnly; public void Add(string key, IFormattable value) { ((IDictionary<string, IFormattable>)_properties).Add(key, value); } public void Add(KeyValuePair<string, IFormattable> item) { ((IDictionary<string, IFormattable>)_properties).Add(item); } public void Clear() { ((IDictionary<string, IFormattable>)_properties).Clear(); } public bool Contains(KeyValuePair<string, IFormattable> item) { return ((IDictionary<string, IFormattable>)_properties).Contains(item); } public bool ContainsKey(string key) { return ((IDictionary<string, IFormattable>)_properties).ContainsKey(key); } public void CopyTo(KeyValuePair<string, IFormattable>[] array, int arrayIndex) { ((IDictionary<string, IFormattable>)_properties).CopyTo(array, arrayIndex); } public IEnumerator<KeyValuePair<string, IFormattable>> GetEnumerator() { return ((IDictionary<string, IFormattable>)_properties).GetEnumerator(); } public bool Remove(string key) { return ((IDictionary<string, IFormattable>)_properties).Remove(key); } public bool Remove(KeyValuePair<string, IFormattable> item) { return ((IDictionary<string, IFormattable>)_properties).Remove(item); } public bool TryGetValue(string key, out IFormattable value) { return ((IDictionary<string, IFormattable>)_properties).TryGetValue(key, out value); } IEnumerator IEnumerable.GetEnumerator() { return ((IDictionary<string, IFormattable>)_properties).GetEnumerator(); } } } <file_sep>using System; using NLog; using NLog.Targets; class Example { static void Main(string[] args) { MemoryTarget target = new MemoryTarget(); target.Layout = "${message}"; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); foreach (string s in target.Logs) { Console.Write("logged: {0}", s); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LayoutRenderers { using NLog.Layouts; using NLog.LayoutRenderers.Wrappers; using Xunit; public class Rot13Tests : NLogTestBase { [Fact] public void Test1() { Assert.Equal("NOPQRSTUVWXYZABCDEFGHIJKLM", Rot13LayoutRendererWrapper.DecodeRot13("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); Assert.Equal("nopqrstuvwxyzabcdefghijklm0123456789", Rot13LayoutRendererWrapper.DecodeRot13("abcdefghijklmnopqrstuvwxyz0123456789")); Assert.Equal("How can you tell an extrovert from an introvert at NSA? Va gur ryringbef, gur rkgebiregf ybbx ng gur BGURE thl'f fubrf.", Rot13LayoutRendererWrapper.DecodeRot13( "Ubj pna lbh gryy na rkgebireg sebz na vagebireg ng AFN? In the elevators, the extroverts look at the OTHER guy's shoes.")); } [Fact] public void Test2() { Layout l = "${rot13:HELLO}"; LogEventInfo lei = LogEventInfo.Create(LogLevel.Info, "aaa", "bbb"); Assert.Equal("URYYB", l.Render(lei)); } [Fact] public void Test3() { Layout l = "${rot13:text=HELLO}"; LogEventInfo lei = LogEventInfo.Create(LogLevel.Info, "aaa", "bbb"); Assert.Equal("URYYB", l.Render(lei)); } [Fact] public void Test4() { Layout l = "${rot13:${event-context:aaa}}"; LogEventInfo lei = LogEventInfo.Create(LogLevel.Info, "aaa", "bbb"); lei.Properties["aaa"] = "HELLO"; Assert.Equal("URYYB", l.Render(lei)); } [Fact] public void Test5() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${rot13:${mdc:A}}' /> <target name='debug2' type='Debug' layout='${rot13:${rot13:${scopeproperty:A}}}' /> </targets> <rules> <logger name='*' levels='Trace' writeTo='debug,debug2' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("NLog.UnitTests.LayoutRenderers.Rot13Tests"); using (logger.PushScopeProperty("A", "Foo.Bar!")) { logger.Trace("aaa"); } logFactory.AssertDebugLastMessage("Debug", "Sbb.One!"); // double rot-13 should be identity logFactory.AssertDebugLastMessage("debug2", "Foo.Bar!"); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Internal { using System; using NLog.Common; using Xunit; public class ConversionHelpersTests : NLogTestBase { enum TestEnum { Foo, bar, } #region tryparse - ignorecase parameter: false [Fact] public void EnumParse1_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam("Foo", false, TestEnum.Foo, true); } [Fact] public void EnumParse2_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam("foo", false, TestEnum.Foo, false); } [Fact] public void EnumParseDefault_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam("BAR", false, TestEnum.Foo, false); } [Fact] public void EnumParseDefault2_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam("x", false, TestEnum.Foo, false); } [Fact] public void EnumParseBar_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam("bar", false, TestEnum.bar, true); } [Fact] public void EnumParseBar2_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam(" bar ", false, TestEnum.bar, true); } [Fact] public void EnumParseBar3_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam(" \r\nbar ", false, TestEnum.bar, true); } [Fact] public void EnumParse_null_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam(null, false, TestEnum.Foo, false); } [Fact] public void EnumParse_emptystring_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam(string.Empty, false, TestEnum.Foo, false); } [Fact] public void EnumParse_whitespace_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam(" ", false, TestEnum.Foo, false); } [Fact] public void EnumParse_wrongInput_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam("not enum", false, TestEnum.Foo, false); } #endregion #region tryparse - ignorecase parameter: true [Fact] public void EnumParse1_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam("Foo", true, TestEnum.Foo, true); } [Fact] public void EnumParse2_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam("foo", true, TestEnum.Foo, true); } [Fact] public void EnumParseDefault_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam("BAR", true, TestEnum.bar, true); } [Fact] public void EnumParseDefault2_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam("x", true, TestEnum.Foo, false); } [Fact] public void EnumParseBar_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam("bar", true, TestEnum.bar, true); } [Fact] public void EnumParseBar2_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam(" bar ", true, TestEnum.bar, true); } [Fact] public void EnumParseBar3_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam(" \r\nbar ", true, TestEnum.bar, true); } [Fact] public void EnumParse_null_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam(null, true, TestEnum.Foo, false); } [Fact] public void EnumParse_emptystring_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam(string.Empty, true, TestEnum.Foo, false); } [Fact] public void EnumParse_whitespace_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam(" ", true, TestEnum.Foo, false); } [Fact] public void EnumParse_ArgumentException_ignoreCaseTrue() { double result; Assert.Throws<ArgumentException>(() => ConversionHelpers.TryParseEnum("not enum", true, out result)); } #endregion #region helpers private static void TestEnumParseCaseIgnoreCaseParam(string value, bool ignoreCase, TestEnum expected, bool expectedReturn) { { var returnResult = ConversionHelpers.TryParseEnum(value, ignoreCase, out TestEnum result); Assert.Equal(expected, result); Assert.Equal(expectedReturn, returnResult); } // if true, test also other TryParseEnum if (ignoreCase) { { var returnResult = ConversionHelpers.TryParseEnum<TestEnum>(value, out var result); Assert.Equal(expected, result); Assert.Equal(expectedReturn, returnResult); } { var returnResult = ConversionHelpers.TryParseEnum(value, typeof(TestEnum), out var result); Assert.Equal(expectedReturn, returnResult); if (expectedReturn) { Assert.Equal(expected, result); } else { Assert.Null(result); } } } } #endregion } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Filters { using NLog.Filters; using NLog.Layouts; using Xunit; public class WhenContainsTests : NLogTestBase { [Fact] public void WhenContainsTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug'> <filters defaultAction='log'> <whenContains layout='${message}' substring='zzz' action='Ignore' /> </filters> </logger> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Debug("a"); logFactory.AssertDebugLastMessage("a"); logger.Debug("zzz"); logFactory.AssertDebugLastMessage("a"); logger.Debug("ZzzZ"); logFactory.AssertDebugLastMessage("ZzzZ"); Assert.True(logFactory.Configuration.LoggingRules[0].Filters[0] is WhenContainsFilter); var wcf = (WhenContainsFilter)logFactory.Configuration.LoggingRules[0].Filters[0]; Assert.IsType<SimpleLayout>(wcf.Layout); Assert.Equal("${message}", ((SimpleLayout)wcf.Layout).Text); Assert.Equal("zzz", wcf.Substring); Assert.Equal(FilterResult.Ignore, wcf.Action); } [Fact] public void WhenContainsInsensitiveTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug'> <filters defaultAction='log'> <whenContains layout='${message}' substring='zzz' action='Ignore' ignoreCase='true' /> </filters> </logger> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Debug("a"); logFactory.AssertDebugLastMessage("a"); logger.Debug("zzz"); logFactory.AssertDebugLastMessage("a"); logger.Debug("ZzzZ"); logFactory.AssertDebugLastMessage("a"); logger.Debug("aaa"); logFactory.AssertDebugLastMessage("aaa"); } [Fact] public void WhenContainsQuoteTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug'> <filters defaultAction='log'> <whenContains layout='${message}' substring='&apos;' action='Ignore' ignoreCase='true' /> </filters> </logger> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Debug("a"); logFactory.AssertDebugLastMessage("a"); logger.Debug("'"); logFactory.AssertDebugLastMessage("a"); logger.Debug("a'a"); logFactory.AssertDebugLastMessage("a"); logger.Debug("aaa"); logFactory.AssertDebugLastMessage("aaa"); } [Fact] public void WhenContainsQuoteTestComplex() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug'> <filters defaultAction='log'> <when condition=""contains('${message}', 'Cannot insert the value NULL into column ''Col1')"" action=""Log""></when> <when condition='true' action='Ignore' /> </filters> </logger> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); var expectedMessage = "Cannot insert the value NULL into column 'Col1"; logger.Debug(expectedMessage); logFactory.AssertDebugLastMessage(expectedMessage); expectedMessage = "Cannot insert the value NULL into column 'Col1'"; logger.Debug(expectedMessage); logFactory.AssertDebugLastMessage(expectedMessage); expectedMessage = "Cannot insert the value NULL into column 'COL1'"; logger.Debug(expectedMessage); logFactory.AssertDebugLastMessage(expectedMessage); logger.Debug("Cannot insert the value NULL into column Col1"); logFactory.AssertDebugLastMessage(expectedMessage); logger.Debug("Test"); logFactory.AssertDebugLastMessage(expectedMessage); } [Fact] public void WhenContainsFilterActionMustOverrideDefault() { var ex = Assert.Throws<NLogConfigurationException>(() => { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug'> <filters defaultAction='Ignore'> <whenContains layout='${message}' substring='zzz' action='Ignore' /> </filters> </logger> </rules> </nlog>").LogFactory; }); Assert.Contains("FilterDefaultAction=Ignore", ex.InnerException?.Message ?? ex.Message); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using NLog.Common; using NLog.Config; /// <summary> /// Scans (breadth-first) the object graph following all the edges whose are /// instances have <see cref="NLogConfigurationItemAttribute"/> attached and returns /// all objects implementing a specified interfaces. /// </summary> internal static class ObjectGraphScanner { /// <summary> /// Finds the objects which have attached <see cref="NLogConfigurationItemAttribute"/> which are reachable /// from any of the given root objects when traversing the object graph over public properties. /// </summary> /// <typeparam name="T">Type of the objects to return.</typeparam> /// <param name="configFactory">Configuration Reflection Helper</param> /// <param name="aggressiveSearch">Also search the properties of the wanted objects.</param> /// <param name="rootObjects">The root objects.</param> /// <returns>Ordered list of objects implementing T.</returns> public static List<T> FindReachableObjects<T>(ConfigurationItemFactory configFactory, bool aggressiveSearch, params object[] rootObjects) where T : class { if (InternalLogger.IsTraceEnabled) { InternalLogger.Trace("FindReachableObject<{0}>:", typeof(T)); } var result = new List<T>(); var visitedObjects = new HashSet<object>(SingleItemOptimizedHashSet<object>.ReferenceEqualityComparer.Default); foreach (var rootObject in rootObjects) { if (PropertyHelper.IsConfigurationItemType(configFactory, rootObject?.GetType())) { ScanProperties(configFactory, aggressiveSearch, rootObject, result, 0, visitedObjects); } } return result; } private static void ScanProperties<T>(ConfigurationItemFactory configFactory, bool aggressiveSearch, object targetObject, List<T> result, int level, HashSet<object> visitedObjects) where T : class { if (targetObject is null) { return; } if (visitedObjects.Contains(targetObject)) { return; } if (targetObject is T t) { result.Add(t); if (!aggressiveSearch) { return; } } var type = targetObject.GetType(); if (InternalLogger.IsTraceEnabled) { InternalLogger.Trace("{0}Scanning {1} '{2}'", new string(' ', level), type.Name, targetObject); } foreach (var configProp in PropertyHelper.GetAllConfigItemProperties(configFactory, type)) { if (string.IsNullOrEmpty(configProp.Key)) continue; // Ignore default values if (!PropertyHelper.IsConfigurationItemType(configFactory, configProp.Value.PropertyType)) continue; var propInfo = configProp.Value; var propValue = propInfo.GetValue(targetObject, null); if (propValue is null) continue; visitedObjects.Add(targetObject); ScanPropertyForObject(configFactory, aggressiveSearch, propValue, propInfo, result, level, visitedObjects); } } private static void ScanPropertyForObject<T>(ConfigurationItemFactory configFactory, bool aggressiveSearch, object propValue, PropertyInfo prop, List<T> result, int level, HashSet<object> visitedObjects) where T : class { if (InternalLogger.IsTraceEnabled) { InternalLogger.Trace("{0}Scanning Property {1} '{2}' {3}", new string(' ', level + 1), prop.Name, propValue, prop.PropertyType); } if (propValue is IEnumerable enumerable) { var propListValue = ConvertEnumerableToList(enumerable, visitedObjects); if (propListValue.Count > 0) { ScanPropertiesList(configFactory, aggressiveSearch, propListValue, result, level + 1, visitedObjects); } } else { ScanProperties(configFactory, aggressiveSearch, propValue, result, level + 1, visitedObjects); } } private static void ScanPropertiesList<T>(ConfigurationItemFactory configFactory, bool aggressiveSearch, IList list, List<T> result, int level, HashSet<object> visitedObjects) where T : class { var firstElement = list[0]; if (firstElement is null || PropertyHelper.IsConfigurationItemType(configFactory, firstElement.GetType())) { ScanProperties(configFactory, aggressiveSearch, firstElement, result, level, visitedObjects); for (int i = 1; i < list.Count; i++) { var element = list[i]; ScanProperties(configFactory, aggressiveSearch, element, result, level, visitedObjects); } } } private static IList ConvertEnumerableToList(IEnumerable enumerable, HashSet<object> visitedObjects) { if (enumerable is ICollection collection && collection.Count == 0) { return ArrayHelper.Empty<object>(); } if (visitedObjects.Contains(enumerable)) { return ArrayHelper.Empty<object>(); } visitedObjects.Add(enumerable); if (enumerable is IList list) { if (!list.IsReadOnly && !(list is Array)) { // Protect against collection was modified List<object> elements = new List<object>(list.Count); lock (list.SyncRoot) { for (int i = 0; i < list.Count; i++) { elements.Add(list[i]); } } return elements; } return list; } //new list to prevent: Collection was modified after the enumerator was instantiated. //note .Cast is tread-unsafe! But at least it isn't a ICollection / IList return enumerable.Cast<object>().ToList(); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 #define CaptureCallSiteInfo #endif namespace NLog { using System; using System.Collections.Generic; using System.Diagnostics; using JetBrains.Annotations; using NLog.Common; using NLog.Config; using NLog.Filters; using NLog.Internal; /// <summary> /// Implementation of logging engine. /// </summary> internal static class LoggerImpl { private const int StackTraceSkipMethods = 0; internal static void Write([NotNull] Type loggerType, [NotNull] TargetWithFilterChain targetsForLevel, LogEventInfo logEvent, LogFactory logFactory) { logEvent.SetMessageFormatter(logFactory.ActiveMessageFormatter, targetsForLevel.NextInChain is null ? logFactory.SingleTargetMessageFormatter : null); #if CaptureCallSiteInfo StackTraceUsage stu = targetsForLevel.StackTraceUsage; if (stu != StackTraceUsage.None) { bool attemptCallSiteOptimization = targetsForLevel.TryCallSiteClassNameOptimization(stu, logEvent); if (attemptCallSiteOptimization && targetsForLevel.TryLookupCallSiteClassName(logEvent, out string callSiteClassName)) { logEvent.CallSiteInformation.CallerClassName = callSiteClassName; } else if (attemptCallSiteOptimization || targetsForLevel.MustCaptureStackTrace(stu, logEvent)) { CaptureCallSiteInfo(logFactory, loggerType, logEvent, stu); if (attemptCallSiteOptimization) { targetsForLevel.TryRememberCallSiteClassName(logEvent); } } } #endif AsyncContinuation exceptionHandler = SingleCallContinuation.Completed; if (logFactory.ThrowExceptions) { int originalThreadId = AsyncHelpers.GetManagedThreadId(); exceptionHandler = ex => { if (ex != null && AsyncHelpers.GetManagedThreadId() == originalThreadId) { throw new NLogRuntimeException("Exception occurred in NLog", ex); } }; } IList<Filter> prevFilterChain = ArrayHelper.Empty<Filter>(); FilterResult prevFilterResult = FilterResult.Neutral; for (var t = targetsForLevel; t != null; t = t.NextInChain) { var currentFilterChain = t.FilterChain; FilterResult result = ReferenceEquals(prevFilterChain, currentFilterChain) ? prevFilterResult : GetFilterResult(currentFilterChain, logEvent, t.FilterDefaultAction); if (!WriteToTargetWithFilterChain(t.Target, result, logEvent, exceptionHandler)) { break; } prevFilterResult = result; // Cache the result, and reuse it for the next target, if it comes from the same logging-rule prevFilterChain = currentFilterChain; } } #if CaptureCallSiteInfo private static void CaptureCallSiteInfo(LogFactory logFactory, Type loggerType, LogEventInfo logEvent, StackTraceUsage stackTraceUsage) { try { bool includeSource = (stackTraceUsage & StackTraceUsage.WithFileNameAndLineNumber) != 0; #if NETSTANDARD1_5 var stackTrace = (StackTrace)Activator.CreateInstance(typeof(StackTrace), new object[] { includeSource }); #else var stackTrace = new StackTrace(StackTraceSkipMethods, includeSource); #endif logEvent.GetCallSiteInformationInternal().SetStackTrace(stackTrace, null, loggerType); } catch (Exception ex) { #if DEBUG if (ex.MustBeRethrownImmediately()) throw; #endif if (logFactory.ThrowExceptions || LogManager.ThrowExceptions) throw; InternalLogger.Error(ex, "{0} Failed to capture CallSite. Platform might not support ${{callsite}}", logEvent.LoggerName); } } #endif private static bool WriteToTargetWithFilterChain(Targets.Target target, FilterResult result, LogEventInfo logEvent, AsyncContinuation onException) { if ((result == FilterResult.Ignore) || (result == FilterResult.IgnoreFinal)) { if (InternalLogger.IsDebugEnabled) { InternalLogger.Debug("{0} [{1}] Rejecting message because of a filter.", logEvent.LoggerName, logEvent.Level); } if (result == FilterResult.IgnoreFinal) { return false; } return true; } target.WriteAsyncLogEvent(logEvent.WithContinuation(onException)); if (result == FilterResult.LogFinal) { return false; } return true; } /// <summary> /// Gets the filter result. /// </summary> /// <param name="filterChain">The filter chain.</param> /// <param name="logEvent">The log event.</param> /// <param name="filterDefaultAction">default result if there are no filters, or none of the filters decides.</param> /// <returns>The result of the filter.</returns> private static FilterResult GetFilterResult(IList<Filter> filterChain, LogEventInfo logEvent, FilterResult filterDefaultAction) { if (filterChain.Count == 0) return FilterResult.Neutral; try { //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < filterChain.Count; i++) { Filter f = filterChain[i]; var result = f.GetFilterResult(logEvent); if (result != FilterResult.Neutral) { return result; } } return filterDefaultAction; } catch (Exception exception) { InternalLogger.Warn(exception, "Exception during filter evaluation. Message will be ignore."); if (exception.MustBeRethrown()) { throw; } return FilterResult.Ignore; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Internal { using System; using System.Collections; using System.Collections.Generic; /// <summary> /// Tricky implementation of IDictionary where GetEnumerator does not return expected DictionaryEntry by default /// </summary> internal class TrickyTestDictionary : IDictionary<object, object>, IDictionary { readonly Dictionary<object, object> _inner = new Dictionary<object, object>(); public object this[object key] { get => _inner[key]; set => _inner[key] = value; } public ICollection<object> Keys => _inner.Keys; public ICollection<object> Values => _inner.Values; public int Count => _inner.Count; public bool IsReadOnly => ((IDictionary)_inner).IsReadOnly; public bool IsFixedSize => ((IDictionary)_inner).IsFixedSize; public object SyncRoot => ((IDictionary)_inner).SyncRoot; public bool IsSynchronized => ((IDictionary)_inner).IsSynchronized; ICollection IDictionary.Keys => _inner.Keys; ICollection IDictionary.Values => _inner.Values; public void Add(object key, object value) { _inner.Add(key, value); } public void Add(KeyValuePair<object, object> item) { _inner.Add(item.Key, item.Value); } public void Clear() { _inner.Clear(); } public bool Contains(KeyValuePair<object, object> item) { return ((IDictionary)_inner).Contains(item); } public bool Contains(object key) { return ((IDictionary)_inner).Contains(key); } public bool ContainsKey(object key) { return _inner.ContainsKey(key); } public void CopyTo(KeyValuePair<object, object>[] array, int arrayIndex) { ((IDictionary)_inner).CopyTo(array, arrayIndex); } public void CopyTo(Array array, int index) { ((IDictionary)_inner).CopyTo(array, index); } public IEnumerator<KeyValuePair<object, object>> GetEnumerator() { return _inner.GetEnumerator(); } public bool Remove(object key) { return _inner.Remove(key); } public bool Remove(KeyValuePair<object, object> item) { return _inner.Remove(item.Key); } public bool TryGetValue(object key, out object value) { return _inner.TryGetValue(key, out value); } IEnumerator IEnumerable.GetEnumerator() { return _inner.GetEnumerator(); } IDictionaryEnumerator IDictionary.GetEnumerator() { return _inner.GetEnumerator(); // Non-standard enumerator returned. Should be: ((IDictionary)_inner).GetEnumerator() } void IDictionary.Remove(object key) { _inner.Remove(key); } } } <file_sep>using NLog; using NLog.Targets; namespace ManuallyLoadedExtension { [Target("ManuallyLoadedTarget")] public class ManuallyLoadedTarget : Target { protected override void Write(LogEventInfo logEvent) { // do nothing } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using NLog.Common; using NLog.Internal; using NLog.Layouts; /// <summary> /// Dynamic filtering with a positive list of enabled levels /// </summary> internal class DynamicLogLevelFilter : ILoggingRuleLevelFilter { private readonly LoggingRule _loggingRule; private readonly SimpleLayout _levelFilter; private readonly SimpleLayout _finalMinLevelFilter; private KeyValuePair<string, bool[]> _activeFilter; public bool[] LogLevels => GenerateLogLevels(); public LogLevel FinalMinLevel => GenerateFinalMinLevel(); public DynamicLogLevelFilter(LoggingRule loggingRule, SimpleLayout levelFilter, SimpleLayout finalMinLevelFilter) { _loggingRule = loggingRule; _levelFilter = levelFilter; _finalMinLevelFilter = finalMinLevelFilter; _activeFilter = new KeyValuePair<string, bool[]>(string.Empty, LoggingRuleLevelFilter.Off.LogLevels); } public LoggingRuleLevelFilter GetSimpleFilterForUpdate() { return new LoggingRuleLevelFilter(LogLevels, FinalMinLevel); } private bool[] GenerateLogLevels() { var levelFilter = _levelFilter.Render(LogEventInfo.CreateNullEvent()); if (string.IsNullOrEmpty(levelFilter)) return LoggingRuleLevelFilter.Off.LogLevels; var activeFilter = _activeFilter; if (activeFilter.Key != levelFilter) { bool[] logLevels; if (levelFilter.IndexOf(',') >= 0) { logLevels = ParseLevels(levelFilter); } else { logLevels = ParseSingleLevel(levelFilter); } if (ReferenceEquals(logLevels, LoggingRuleLevelFilter.Off.LogLevels)) return logLevels; _activeFilter = activeFilter = new KeyValuePair<string, bool[]>(levelFilter, logLevels); } return activeFilter.Value; } private LogLevel GenerateFinalMinLevel() { var levelFilter = _finalMinLevelFilter?.Render(LogEventInfo.CreateNullEvent()); return ParseLogLevel(levelFilter, null); } private bool[] ParseSingleLevel(string levelFilter) { var logLevel = ParseLogLevel(levelFilter, null); if (logLevel is null || logLevel == LogLevel.Off) return LoggingRuleLevelFilter.Off.LogLevels; bool[] logLevels = new bool[LogLevel.MaxLevel.Ordinal + 1]; logLevels[logLevel.Ordinal] = true; return logLevels; } private LogLevel ParseLogLevel(string logLevel, LogLevel levelIfEmpty) { try { if (string.IsNullOrEmpty(logLevel)) return levelIfEmpty; return LogLevel.FromString(logLevel.Trim()); } catch (ArgumentException ex) { InternalLogger.Warn(ex, "Logging rule {0} with pattern '{1}' has invalid loglevel: {2}", _loggingRule.RuleName, _loggingRule.LoggerNamePattern, logLevel); return null; } } private bool[] ParseLevels(string levelFilter) { var levels = levelFilter.SplitAndTrimTokens(','); if (levels.Length == 0) return LoggingRuleLevelFilter.Off.LogLevels; if (levels.Length == 1) return ParseSingleLevel(levels[0]); bool[] logLevels = new bool[LogLevel.MaxLevel.Ordinal + 1]; foreach (var level in levels) { try { var logLevel = LogLevel.FromString(level); if (logLevel == LogLevel.Off) continue; logLevels[logLevel.Ordinal] = true; } catch (ArgumentException ex) { InternalLogger.Warn(ex, "Logging rule {0} with pattern '{1}' has invalid loglevel: {2}", _loggingRule.RuleName, _loggingRule.LoggerNamePattern, levelFilter); } } return logLevels; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Globalization; using System.IO; using NLog.Internal; namespace NLog.Targets.FileArchiveModes { /// <summary> /// Archives the log-files using a sequence style numbering. The most recent archive has the highest number. /// /// When the number of archive files exceed <see cref="FileTarget.MaxArchiveFiles"/> the obsolete archives are deleted. /// When the age of archive files exceed <see cref="FileTarget.MaxArchiveDays"/> the obsolete archives are deleted. /// </summary> internal sealed class FileArchiveModeSequence : FileArchiveModeBase { private readonly string _archiveDateFormat; public FileArchiveModeSequence(string archiveDateFormat, bool isArchiveCleanupEnabled) :base(isArchiveCleanupEnabled) { _archiveDateFormat = archiveDateFormat; } public override bool AttemptCleanupOnInitializeFile(string archiveFilePath, int maxArchiveFiles, int maxArchiveDays) { return false; // For historic reasons, then cleanup of sequence archives are not done on startup } protected override DateAndSequenceArchive GenerateArchiveFileInfo(FileInfo archiveFile, FileNameTemplate fileTemplate) { string baseName = Path.GetFileName(archiveFile.FullName) ?? ""; int trailerLength = fileTemplate.Template.Length - fileTemplate.EndAt; string number = baseName.Substring(fileTemplate.BeginAt, baseName.Length - trailerLength - fileTemplate.BeginAt); int num; try { num = Convert.ToInt32(number, CultureInfo.InvariantCulture); } catch (FormatException) { return null; } var creationTimeUtc = archiveFile.LookupValidFileCreationTimeUtc(); var creationTime = creationTimeUtc > DateTime.MinValue ? NLog.Time.TimeSource.Current.FromSystemTime(creationTimeUtc) : DateTime.MinValue; return new DateAndSequenceArchive(archiveFile.FullName, creationTime, string.Empty, num); } public override DateAndSequenceArchive GenerateArchiveFileName(string archiveFilePath, DateTime archiveDate, List<DateAndSequenceArchive> existingArchiveFiles) { int nextSequenceNumber = 0; FileNameTemplate archiveFileNameTemplate = GenerateFileNameTemplate(archiveFilePath); foreach (var existingFile in existingArchiveFiles) nextSequenceNumber = Math.Max(nextSequenceNumber, existingFile.Sequence + 1); int minSequenceLength = archiveFileNameTemplate.EndAt - archiveFileNameTemplate.BeginAt - 2; string paddedSequence = nextSequenceNumber.ToString().PadLeft(minSequenceLength, '0'); string dirName = Path.GetDirectoryName(archiveFilePath); archiveFilePath = Path.Combine(dirName, archiveFileNameTemplate.ReplacePattern("*").Replace("*", paddedSequence)); archiveFilePath = Path.GetFullPath(archiveFilePath); // Rebuild to fix non-standard path-format return new DateAndSequenceArchive(archiveFilePath, archiveDate, _archiveDateFormat, nextSequenceNumber); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections; using System.Collections.Generic; namespace NLog.Internal { /// <summary> /// Ensures that IDictionary.GetEnumerator returns DictionaryEntry values /// </summary> internal struct DictionaryEntryEnumerable : IEnumerable<DictionaryEntry> { private readonly IDictionary _dictionary; public DictionaryEntryEnumerable(IDictionary dictionary) { _dictionary = dictionary; } public DictionaryEntryEnumerator GetEnumerator() { return new DictionaryEntryEnumerator(_dictionary?.Count > 0 ? _dictionary : null); } IEnumerator<DictionaryEntry> IEnumerable<DictionaryEntry>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } internal struct DictionaryEntryEnumerator : IEnumerator<DictionaryEntry> { private readonly IDictionaryEnumerator _entryEnumerator; public DictionaryEntry Current => _entryEnumerator.Entry; public DictionaryEntryEnumerator(IDictionary dictionary) { _entryEnumerator = dictionary?.GetEnumerator(); } object IEnumerator.Current => Current; public void Dispose() { if (_entryEnumerator is IDisposable disposable) disposable.Dispose(); } public bool MoveNext() { return _entryEnumerator?.MoveNext() ?? false; } public void Reset() { _entryEnumerator?.Reset(); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD #define DISABLE_FILE_INTERNAL_LOGGING namespace NLog.UnitTests.Targets { using System; using System.Diagnostics; using System.IO; using System.Threading; using NLog.Config; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; using System.Collections.Generic; using System.Linq; using Xunit.Extensions; public class ConcurrentFileTargetTests : NLogTestBase { private Logger _logger = LogManager.GetLogger("NLog.UnitTests.Targets.ConcurrentFileTargetTests"); private void ConfigureSharedFile(string mode, string fileName) { var modes = mode.Split('|'); FileTarget ft = new FileTarget(); ft.FileName = fileName; ft.Layout = "${message}"; ft.ConcurrentWrites = true; ft.OpenFileCacheTimeout = 10; ft.OpenFileCacheSize = 1; ft.LineEnding = LineEndingMode.LF; ft.KeepFileOpen = Array.IndexOf(modes, "retry") >= 0 ? false : true; ft.ForceMutexConcurrentWrites = Array.IndexOf(modes, "mutex") >= 0 ? true : false; ft.ArchiveAboveSize = Array.IndexOf(modes, "archive") >= 0 ? 50 : -1; if (ft.ArchiveAboveSize > 0) { string archivePath = Path.Combine(Path.GetDirectoryName(fileName), "Archive"); ft.ArchiveFileName = Path.Combine(archivePath, "{####}_" + Path.GetFileName(fileName)); ft.MaxArchiveFiles = 10000; } var name = "ConfigureSharedFile_" + mode.Replace('|', '_') + "-wrapper"; switch (modes[0]) { case "async": var asyncTarget = new AsyncTargetWrapper(ft, 100, AsyncTargetWrapperOverflowAction.Grow) { Name = name, TimeToSleepBetweenBatches = 10 }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(asyncTarget)); break; case "buffered": var bufferTarget = new BufferingTargetWrapper(ft, 100) { Name = name }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(bufferTarget)); break; case "buffered_timed_flush": var bufferFlushTarget = new BufferingTargetWrapper(ft, 100, 10) { Name = name }; LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(bufferFlushTarget)); break; default: LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(ft)); break; } } #pragma warning disable xUnit1013 // Needed for test public void Process(string processIndex, string fileName, string numLogsString, string mode) #pragma warning restore xUnit1013 { Thread.CurrentThread.Name = processIndex; int numLogs = Convert.ToInt32(numLogsString); int idxProcess = Convert.ToInt32(processIndex); ConfigureSharedFile(mode, fileName); string format = processIndex + " {0}"; // Having the internal logger enabled would just slow things down, reducing the // likelyhood for uncovering racing conditions. Uncomment #define DISABLE_FILE_INTERNAL_LOGGING #if !DISABLE_FILE_INTERNAL_LOGGING var logWriter = new StringWriter { NewLine = Environment.NewLine }; NLog.Common.InternalLogger.LogLevel = LogLevel.Trace; NLog.Common.InternalLogger.LogFile = Path.Combine(Path.GetDirectoryName(fileName), string.Format("Internal_{0}.txt", processIndex)); NLog.Common.InternalLogger.LogWriter = logWriter; NLog.Common.InternalLogger.LogToConsole = true; try #endif { using (new NoThrowNLogExceptions()) { Thread.Sleep(Math.Max((10 - idxProcess), 1) * 5); // Delay to wait for the other processes for (int i = 0; i < numLogs; ++i) { _logger.Debug(format, i); } LogManager.Configuration = null; // Flush + Close } } #if !DISABLE_FILE_INTERNAL_LOGGING catch (Exception ex) { using (var textWriter = File.AppendText(Path.Combine(Path.GetDirectoryName(fileName), string.Format("Internal_{0}.txt", processIndex)))) { textWriter.WriteLine(ex.ToString()); textWriter.WriteLine(logWriter.GetStringBuilder().ToString()); } throw; } using (var textWriter = File.AppendText(Path.Combine(Path.GetDirectoryName(fileName), string.Format("Internal_{0}.txt", processIndex)))) { textWriter.WriteLine(logWriter.GetStringBuilder().ToString()); } #endif } private string MakeFileName(int numProcesses, int numLogs, string mode) { // Having separate file names for the various tests makes debugging easier. return $"test_{numProcesses}_{numLogs}_{mode.Replace('|', '_')}.txt"; } private void DoConcurrentTest(int numProcesses, int numLogs, string mode) { string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); string archivePath = Path.Combine(tempPath, "Archive"); try { Directory.CreateDirectory(tempPath); Directory.CreateDirectory(archivePath); string logFile = Path.Combine(tempPath, MakeFileName(numProcesses, numLogs, mode)); if (File.Exists(logFile)) { throw new Exception($"file '{logFile}' already exists"); } Process[] processes = new Process[numProcesses]; for (int i = 0; i < numProcesses; ++i) { processes[i] = ProcessRunner.SpawnMethod( GetType(), "Process", i.ToString(), logFile, numLogs.ToString(), mode); } // In case we'd like to capture stdout, we would need to drain it continuously. // StandardOutput.ReadToEnd() wont work, since the other processes console only has limited buffer. for (int i = 0; i < numProcesses; ++i) { processes[i].WaitForExit(); Assert.Equal(0, processes[i].ExitCode); processes[i].Dispose(); processes[i] = null; } var files = new System.Collections.Generic.List<string>(Directory.GetFiles(archivePath)); files.Add(logFile); bool verifyFileSize = files.Count > 1; var receivedNumbersSet = new List<int>[numProcesses]; for (int i = 0; i < numProcesses; i++) { var receivedNumbers = new List<int>(numLogs); receivedNumbersSet[i] = receivedNumbers; } //Console.WriteLine("Verifying output file {0}", logFile); foreach (var file in files) { using (StreamReader sr = File.OpenText(file)) { string line; while ((line = sr.ReadLine()) != null) { string[] tokens = line.Split(' '); Assert.Equal(2, tokens.Length); int thread = Convert.ToInt32(tokens[0]); int number = Convert.ToInt32(tokens[1]); Assert.True(thread >= 0); Assert.True(thread < numProcesses); receivedNumbersSet[thread].Add(number); } if (verifyFileSize) { if (sr.BaseStream.Length > 100) throw new InvalidOperationException( $"Error when reading file {file}, size {sr.BaseStream.Length} is too large"); else if (sr.BaseStream.Length < 35 && files[files.Count - 1] != file) throw new InvalidOperationException( $"Error when reading file {file}, size {sr.BaseStream.Length} is too small"); } } } var expected = Enumerable.Range(0, numLogs).ToList(); int currentProcess = 0; bool? equalsWhenReorderd = null; try { for (; currentProcess < numProcesses; currentProcess++) { var receivedNumbers = receivedNumbersSet[currentProcess]; var equalLength = expected.Count == receivedNumbers.Count; var fastCheck = equalLength && expected.SequenceEqual(receivedNumbers); if (!fastCheck) //assert equals on two long lists in xUnit is lame. Not showing the difference. { if (equalLength) { var reodered = receivedNumbers.OrderBy(i => i); equalsWhenReorderd = expected.SequenceEqual(reodered); } Assert.Equal(string.Join(",", expected), string.Join(",", receivedNumbers)); } } } catch (Exception ex) { var reoderProblem = equalsWhenReorderd is null ? "Dunno" : (equalsWhenReorderd == true ? "Yes" : "No"); throw new InvalidOperationException($"Error when comparing path {tempPath} for process {currentProcess}. Is this a recording problem? {reoderProblem}", ex); } } finally { try { if (Directory.Exists(archivePath)) Directory.Delete(archivePath, true); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } catch { } } } [Theory] [InlineData(2, 10000, "none")] [InlineData(5, 4000, "none")] [InlineData(10, 2000, "none")] #if !MONO // MONO Doesn't work well with global mutex, and it is needed for successful concurrent archive operations [InlineData(2, 500, "none|archive")] [InlineData(2, 500, "none|mutex|archive")] [InlineData(2, 10000, "none|mutex")] [InlineData(5, 4000, "none|mutex")] [InlineData(10, 2000, "none|mutex")] #endif public void SimpleConcurrentTest(int numProcesses, int numLogs, string mode) { RetryingIntegrationTest(3, () => DoConcurrentTest(numProcesses, numLogs, mode)); } [Theory] [InlineData("async")] #if !MONO [InlineData("async|mutex")] #endif public void AsyncConcurrentTest(string mode) { // Before 2 processes are running into concurrent writes, // the first process typically already has written couple thousand events. // Thus to have a meaningful test, at least 10K events are required. // Due to the buffering it makes no big difference in runtime, whether we // have 2 process writing 10K events each or couple more processes with even more events. // Runtime is mostly defined by Runner.exe compilation and JITing the first. DoConcurrentTest(5, 1000, mode); } [Theory] [InlineData("buffered")] #if !MONO [InlineData("buffered|mutex")] #endif public void BufferedConcurrentTest(string mode) { DoConcurrentTest(5, 1000, mode); } [Theory] [InlineData("buffered_timed_flush")] #if !MONO [InlineData("buffered_timed_flush|mutex")] #endif public void BufferedTimedFlushConcurrentTest(string mode) { DoConcurrentTest(5, 1000, mode); } } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal.NetworkSenders { using System; using System.Net.Sockets; /// <summary> /// Socket proxy for mocking Socket code. /// </summary> internal sealed class SocketProxy : ISocket, IDisposable { private readonly Socket _socket; /// <summary> /// Initializes a new instance of the <see cref="SocketProxy"/> class. /// </summary> /// <param name="addressFamily">The address family.</param> /// <param name="socketType">Type of the socket.</param> /// <param name="protocolType">Type of the protocol.</param> internal SocketProxy(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { _socket = new Socket(addressFamily, socketType, protocolType); #if !NET35 if (addressFamily == AddressFamily.InterNetworkV6) { _socket.DualMode = true; // Allow for IPv4 mapped addresses over IPv6 } #endif } /// <summary> /// Gets underlying socket instance. /// </summary> public Socket UnderlyingSocket => _socket; /// <summary> /// Closes the wrapped socket. /// </summary> public void Close() { _socket.Close(); } /// <summary> /// Invokes ConnectAsync method on the wrapped socket. /// </summary> /// <param name="args">The <see cref="SocketAsyncEventArgs"/> instance containing the event data.</param> /// <returns>Result of original method.</returns> public bool ConnectAsync(SocketAsyncEventArgs args) { return _socket.ConnectAsync(args); } /// <summary> /// Invokes SendAsync method on the wrapped socket. /// </summary> /// <param name="args">The <see cref="SocketAsyncEventArgs"/> instance containing the event data.</param> /// <returns>Result of original method.</returns> public bool SendAsync(SocketAsyncEventArgs args) { return _socket.SendAsync(args); } /// <summary> /// Invokes SendToAsync method on the wrapped socket. /// </summary> /// <param name="args">The <see cref="SocketAsyncEventArgs"/> instance containing the event data.</param> /// <returns>Result of original method.</returns> public bool SendToAsync(SocketAsyncEventArgs args) { return _socket.SendToAsync(args); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { ((IDisposable)_socket).Dispose(); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; #if !NETSTANDARD using System.Net.Configuration; #endif using System.IO; using System.Linq; using System.Net; using System.Net.Mail; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using Xunit; public class MailTargetTests { public MailTargetTests() { LogManager.ThrowExceptions = true; } [Fact] public void SimpleEmailTest() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", CC = "<EMAIL>;<EMAIL>", Bcc = "<EMAIL>;<EMAIL>", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; logFactory.GetLogger("MyLogger").Info("log message 1"); Assert.Single(mmt.CreatedMocks); var mock = mmt.CreatedMocks[0]; Assert.Single(mock.MessagesSent); Assert.Equal("server1", mock.Host); Assert.Equal(27, mock.Port); Assert.False(mock.EnableSsl); Assert.Null(mock.Credentials); var msg = mock.MessagesSent[0]; Assert.Equal("Hello from NLog", msg.Subject); Assert.Equal("<EMAIL>", msg.From.Address); Assert.Single(msg.To); Assert.Equal("<EMAIL>", msg.To[0].Address); Assert.Equal(2, msg.CC.Count); Assert.Equal("<EMAIL>", msg.CC[0].Address); Assert.Equal("<EMAIL>", msg.CC[1].Address); Assert.Equal(2, msg.Bcc.Count); Assert.Equal("<EMAIL>", msg.Bcc[0].Address); Assert.Equal("<EMAIL>", msg.Bcc[1].Address); Assert.Equal("Info MyLogger log message 1", msg.Body); } [Fact] public void MailTarget_WithNewlineInSubject_SendsMail() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", CC = "<EMAIL>;<EMAIL>", Bcc = "<EMAIL>;<EMAIL>", Subject = "Hello from NLog\n", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; logFactory.GetLogger("MyLogger").Info("log message 1"); Assert.Single(mmt.CreatedMocks); var mock = mmt.CreatedMocks[0]; Assert.Single(mock.MessagesSent); var msg = mock.MessagesSent[0]; } [Fact] public void NtlmEmailTest() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", SmtpServer = "server1", SmtpAuthentication = SmtpAuthenticationMode.Ntlm, }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; logFactory.GetLogger("MyLogger").Info("log message 1"); Assert.Single(mmt.CreatedMocks); var mock = mmt.CreatedMocks[0]; Assert.Equal(CredentialCache.DefaultNetworkCredentials, mock.Credentials); } [Fact] public void BasicAuthEmailTest() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", SmtpServer = "server1", SmtpAuthentication = SmtpAuthenticationMode.Basic, SmtpUserName = "${scopeproperty:username}", SmtpPassword = "${scopeproperty:password}", }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; var logger = logFactory.GetLogger("MyLogger"); using (logger.PushScopeProperty("username", "u1")) using (logger.PushScopeProperty("password", "p1")) logger.Info("log message 1"); Assert.Single(mmt.CreatedMocks); var mock = mmt.CreatedMocks[0]; var credential = mock.Credentials as NetworkCredential; Assert.NotNull(credential); Assert.Equal("u1", credential.UserName); Assert.Equal("p1", credential.Password); Assert.Equal(string.Empty, credential.Domain); } [Fact] public void CsvLayoutTest() { var layout = new CsvLayout() { Delimiter = CsvColumnDelimiterMode.Semicolon, WithHeader = true, Columns = { new CsvColumn("name", "${logger}"), new CsvColumn("level", "${level}"), new CsvColumn("message", "${message}"), } }; var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", SmtpServer = "server1", AddNewLines = true, Layout = layout, }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "MyLogger3", "log message 3").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Single(mmt.CreatedMocks); var mock = mmt.CreatedMocks[0]; Assert.Single(mock.MessagesSent); var msg = mock.MessagesSent[0]; string expectedBody = "name;level;message\nMyLogger1;Info;log message 1\nMyLogger2;Debug;log message 2\nMyLogger3;Error;log message 3\n"; Assert.Equal(expectedBody, msg.Body); } [Fact] public void PerMessageServer() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", SmtpServer = "${logger}.mydomain.com", Body = "${message}", AddNewLines = true, }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); // 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com Assert.Equal(2, mmt.CreatedMocks.Count); var mock1 = mmt.CreatedMocks[0]; Assert.Equal("MyLogger1.mydomain.com", mock1.Host); Assert.Single(mock1.MessagesSent); var msg1 = mock1.MessagesSent[0]; Assert.Equal("log message 1\nlog message 3\n", msg1.Body); var mock2 = mmt.CreatedMocks[1]; Assert.Equal("MyLogger2.mydomain.com", mock2.Host); Assert.Single(mock2.MessagesSent); var msg2 = mock2.MessagesSent[0]; Assert.Equal("log message 2\n", msg2.Body); } [Fact] public void ErrorHandlingTest() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", SmtpServer = "${logger}", Body = "${message}", AddNewLines = true, }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; try { LogManager.ThrowExceptions = false; var exceptions = new List<Exception>(); var exceptions2 = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "ERROR", "log message 2").WithContinuation(exceptions2.Add), new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Null(exceptions[1]); Assert.NotNull(exceptions2[0]); Assert.Equal("Some SMTP error.", exceptions2[0].Message); } finally { LogManager.ThrowExceptions = true; } // 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com Assert.Equal(2, mmt.CreatedMocks.Count); var mock1 = mmt.CreatedMocks[0]; Assert.Equal("MyLogger1", mock1.Host); Assert.Single(mock1.MessagesSent); var msg1 = mock1.MessagesSent[0]; Assert.Equal("log message 1\nlog message 3\n", msg1.Body); var mock2 = mmt.CreatedMocks[1]; Assert.Equal("ERROR", mock2.Host); Assert.Single(mock2.MessagesSent); var msg2 = mock2.MessagesSent[0]; Assert.Equal("log message 2\n", msg2.Body); } /// <summary> /// Tests that it is possible to user different email address for each log message, /// for example by using ${logger}, ${event-context} or any other layout renderer. /// </summary> [Fact] public void PerMessageAddress() { var mmt = new MockMailTarget { From = "<EMAIL>", To = <EMAIL>", Body = "${message}", SmtpServer = "server1.mydomain.com", AddNewLines = true, }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); // 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com Assert.Equal(2, mmt.CreatedMocks.Count); var mock1 = mmt.CreatedMocks[0]; Assert.Single(mock1.MessagesSent); var msg1 = mock1.MessagesSent[0]; Assert.Equal("<EMAIL>", msg1.To[0].Address); Assert.Equal("log message 1\nlog message 3\n", msg1.Body); var mock2 = mmt.CreatedMocks[1]; Assert.Single(mock2.MessagesSent); var msg2 = mock2.MessagesSent[0]; Assert.Equal("<EMAIL>", msg2.To[0].Address); Assert.Equal("log message 2\n", msg2.Body); } [Fact] public void CustomHeaderAndFooter() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", SmtpServer = "server1", AddNewLines = true, Layout = "${message}", Header = "First event: ${logger}", Footer = "Last event: ${logger}", }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "MyLogger3", "log message 3").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Single(mmt.CreatedMocks); var mock = mmt.CreatedMocks[0]; Assert.Single(mock.MessagesSent); var msg = mock.MessagesSent[0]; string expectedBody = "First event: MyLogger1\nlog message 1\nlog message 2\nlog message 3\nLast event: MyLogger3\n"; Assert.Equal(expectedBody, msg.Body); } [Fact] public void DefaultSmtpClientTest() { var mailTarget = new MailTarget(); var client = mailTarget.CreateSmtpClient(); Assert.IsType<MySmtpClient>(client); } [Fact] public void ReplaceNewlinesWithBreakInHtmlMail() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", Subject = "Hello from NLog", SmtpServer = "server1", Body = "${level}${newline}${logger}${newline}${message}", Html = true, ReplaceNewlineWithBrTagInHtml = true }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; logFactory.GetLogger("MyLogger").Info("log message 1"); var messageSent = mmt.CreatedMocks[0].MessagesSent[0]; Assert.True(messageSent.IsBodyHtml); var lines = messageSent.Body.Split(new[] { "<br/>" }, StringSplitOptions.RemoveEmptyEntries); Assert.True(lines.Length == 3); } [Fact] public void NoReplaceNewlinesWithBreakInHtmlMail() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", Subject = "Hello from NLog", SmtpServer = "server1", Body = "${level}${newline}${logger}${newline}${message}", Html = true, ReplaceNewlineWithBrTagInHtml = false }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; logFactory.GetLogger("MyLogger").Info("log message 1"); var messageSent = mmt.CreatedMocks[0].MessagesSent[0]; Assert.True(messageSent.IsBodyHtml); var lines = messageSent.Body.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); Assert.True(lines.Length == 3); } [Fact] public void MailTarget_WithPriority_SendsMailWithPrioritySet() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", Subject = "Hello from NLog", SmtpServer = "server1", Priority = "high" }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; logFactory.GetLogger("MyLogger").Info("log message 1"); var messageSent = mmt.CreatedMocks[0].MessagesSent[0]; Assert.Equal(MailPriority.High, messageSent.Priority); } [Fact] public void MailTarget_WithoutPriority_SendsMailWithNormalPriority() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", Subject = "Hello from NLog", SmtpServer = "server1", }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; logFactory.GetLogger("MyLogger").Info("log message 1"); var messageSent = mmt.CreatedMocks[0].MessagesSent[0]; Assert.Equal(MailPriority.Normal, messageSent.Priority); } [Fact] public void MailTarget_WithInvalidPriority_SendsMailWithNormalPriority() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", Subject = "Hello from NLog", SmtpServer = "server1", Priority = "${scopeproperty:scopePriority}" }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; using (logFactory.GetCurrentClassLogger().PushScopeProperty("scopePriority", "InvalidPriority")) { logFactory.GetLogger("MyLogger").Info("log message 1"); } var messageSent = mmt.CreatedMocks[0].MessagesSent[0]; Assert.Equal(MailPriority.Normal, messageSent.Priority); } [Fact] public void MailTarget_WithValidToAndEmptyCC_SendsMail() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", CC = "", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}", }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; logFactory.GetLogger("MyLogger").Info("log message 1"); Assert.Single(mmt.CreatedMocks); Assert.Single(mmt.CreatedMocks[0].MessagesSent); } [Fact] public void MailTarget_WithValidToAndEmptyBcc_SendsMail() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", Bcc = "", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}", }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; logFactory.GetLogger("MyLogger").Info("log message 1"); Assert.Single(mmt.CreatedMocks); Assert.Single(mmt.CreatedMocks[0].MessagesSent); } [Fact] public void MailTarget_WithEmptyTo_ThrowsNLogRuntimeException() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}", }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.LogFactory.ThrowExceptions = true; cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; Assert.Throws<NLogRuntimeException>(() => logFactory.GetLogger("MyLogger").Info("log message 1")); } [Fact] public void MailTarget_WithEmptyFrom_ThrowsNLogRuntimeException() { var mmt = new MockMailTarget { From = "", To = "<EMAIL>", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.LogFactory.ThrowExceptions = true; cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; Assert.Throws<NLogRuntimeException>(() => logFactory.GetLogger("MyLogger").Info("log message 1")); } [Fact] public void MailTarget_WithEmptySmtpServer_ThrowsNLogRuntimeException() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", Subject = "Hello from NLog", SmtpServer = "", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.LogFactory.ThrowExceptions = true; cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; Assert.Throws<NLogRuntimeException>(() => logFactory.GetLogger("MyLogger").Info("log message 1")); } [Fact] public void MailTargetInitialize_WithoutSpecifiedTo_ThrowsConfigException() { var mmt = new MockMailTarget { From = "<EMAIL>", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; Assert.Throws<NLogConfigurationException>(() => new LogFactory().Setup().LoadConfiguration(cfg => { cfg.LogFactory.ThrowConfigExceptions = true; cfg.Configuration.AddRuleForAllLevels(mmt); }) ); } [Fact] public void MailTargetInitialize_WithoutSpecifiedFrom_ThrowsConfigException() { var mmt = new MockMailTarget { To = "<EMAIL>", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}", UseSystemNetMailSettings = false }; Assert.Throws<NLogConfigurationException>(() => new LogFactory().Setup().LoadConfiguration(cfg => { cfg.LogFactory.ThrowConfigExceptions = true; cfg.Configuration.AddRuleForAllLevels(mmt); }) ); } [Fact] public void MailTargetInitialize_WithoutSpecifiedSmtpServer_should_not_ThrowsConfigException() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", Subject = "Hello from NLog", SmtpPort = 27, Body = "${level} ${logger} ${message}", UseSystemNetMailSettings = true }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; Assert.Single(logFactory.Configuration.AllTargets); } [Fact] public void MailTargetInitialize_WithoutSpecifiedSmtpServer_ThrowsConfigException_if_UseSystemNetMailSettings() { LogManager.ThrowConfigExceptions = true; var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", Subject = "Hello from NLog", SmtpPort = 27, Body = "${level} ${logger} ${message}", UseSystemNetMailSettings = false }; Assert.Throws<NLogConfigurationException>(() => new LogFactory().Setup().LoadConfiguration(cfg => { cfg.LogFactory.ThrowConfigExceptions = true; cfg.Configuration.AddRuleForAllLevels(mmt); }) ); } /// <summary> /// Test for https://github.com/NLog/NLog/issues/690 /// </summary> [Fact] public void MailTarget_UseSystemNetMailSettings_False_Override_ThrowsNLogRuntimeException_if_DeliveryMethodNotSpecified() { var mmt = new MockMailTarget() { From = "<EMAIL>", To = "<EMAIL>", Subject = "Hello from NLog", SmtpPort = 27, Body = "${level} ${logger} ${message}", PickupDirectoryLocation = @"C:\TEMP", UseSystemNetMailSettings = false }; Assert.Throws<NLogConfigurationException>(() => mmt.InitializeTarget()); } /// <summary> /// Test for https://github.com/NLog/NLog/issues/690 /// </summary> [Fact] public void MailTarget_UseSystemNetMailSettings_False_Override_DeliveryMethod_SpecifiedDeliveryMethod() { var inConfigVal = @"C:\config"; var mmt = new MockMailTarget() { From = "<EMAIL>", To = "<EMAIL>", Subject = "Hello from NLog", SmtpPort = 27, Body = "${level} ${logger} ${message}", PickupDirectoryLocation = @"C:\TEMP", UseSystemNetMailSettings = false, DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory }; mmt.InitializeTarget(); mmt.ConfigureMailClient(LogEventInfo.CreateNullEvent(), mmt.CreateSmtpClient()); Assert.NotEqual(mmt.SmtpClientPickUpDirectory, inConfigVal); } [Fact] public void MailTarget_UseSystemNetMailSettings_True() { var mmt = new MockMailTarget() { From = "<EMAIL>", To = "<EMAIL>", Subject = "Hello from NLog", Body = "${level} ${logger} ${message}", UseSystemNetMailSettings = true }; mmt.InitializeTarget(); Assert.True(mmt.UseSystemNetMailSettings); } [Fact] public void MailTarget_UseSystemNetMailSettings_True_WithVirtualPath() { var inConfigVal = @"~/App_Data/Mail"; var mmt = new MockMailTarget() { From = "<EMAIL>", To = "<EMAIL>", Subject = "Hello from NLog", Body = "${level} ${logger} ${message}", UseSystemNetMailSettings = false, PickupDirectoryLocation = inConfigVal, DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory }; mmt.InitializeTarget(); mmt.ConfigureMailClient(LogEventInfo.CreateNullEvent(), mmt.CreateSmtpClient()); Assert.NotEqual(inConfigVal, mmt.SmtpClientPickUpDirectory); var separator = Path.DirectorySeparatorChar; Assert.Contains(string.Format("{0}App_Data{0}Mail", separator), mmt.SmtpClientPickUpDirectory); } [Fact] public void MailTarget_UseSystemNetMailSettings_True_ReadFromFromConfigFile_dontoverride() { var mmt = new MailTarget() { From = "<EMAIL>", To = "<EMAIL>", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}", UseSystemNetMailSettings = true, #if !NETSTANDARD SmtpSection = new SmtpSection { From = "<EMAIL>" } #endif }; Assert.Equal("<EMAIL>", mmt.From.ToString()); new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }); Assert.Equal("<EMAIL>", mmt.From.ToString()); } #if !NETSTANDARD [Fact] public void MailTarget_UseSystemNetMailSettings_True_ReadFromFromConfigFile() { var mmt = new MailTarget() { From = null, To = "<EMAIL>", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}", UseSystemNetMailSettings = true, SmtpSection = new SmtpSection { From = "<EMAIL>" } }; Assert.Equal("<EMAIL>", mmt.From.ToString()); new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }); Assert.Equal("<EMAIL>", mmt.From.ToString()); } #endif #if !NETSTANDARD [Fact] public void MailTarget_UseSystemNetMailSettings_False_ReadFromFromConfigFile() { var mmt = new MailTarget() { From = null, To = "<EMAIL>", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}", UseSystemNetMailSettings = false, SmtpSection = new SmtpSection { From = "<EMAIL>" } }; Assert.Null(mmt.From); Assert.Throws<NLogConfigurationException>(() => new LogFactory().Setup().LoadConfiguration(cfg => { cfg.LogFactory.ThrowConfigExceptions = true; cfg.Configuration.AddRuleForAllLevels(mmt); }) ); } #endif [Fact] public void MailTarget_WithoutSubject_SendsMessageWithDefaultSubject() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; logFactory.GetLogger("MyLogger").Info("log message 1"); Assert.Single(mmt.CreatedMocks); var mock = mmt.CreatedMocks[0]; Assert.Single(mock.MessagesSent); Assert.Equal($"Message from NLog on {Environment.MachineName}", mock.MessagesSent[0].Subject); } [Fact] public void MailTarget_WithMessageHeaders_SendsMail() { var mmt = new MockMailTarget { From = "<EMAIL>", To = "<EMAIL>", Subject = "Hello from NLog", SmtpServer = "server1", }; mmt.MailHeaders.Add(new MethodCallParameter("Hello", "World")); var logFactory = new LogFactory().Setup().LoadConfiguration(cfg => { cfg.Configuration.AddRuleForAllLevels(mmt); }).LogFactory; logFactory.GetLogger("MyLogger").Info("log message 1"); var messageSent = mmt.CreatedMocks[0].MessagesSent[0]; Assert.NotEmpty(messageSent.Headers); Assert.Contains("Hello", messageSent.Headers.Keys.Cast<string>()); Assert.Equal("World", messageSent.Headers["Hello"]); } public sealed class MockSmtpClient : ISmtpClient { public MockSmtpClient() { MessagesSent = new List<MailMessage>(); } public SmtpDeliveryMethod DeliveryMethod { get; set; } public string Host { get; set; } public int Port { get; set; } public int Timeout { get; set; } public string PickupDirectoryLocation { get; set; } public ICredentialsByHost Credentials { get; set; } public bool EnableSsl { get; set; } public List<MailMessage> MessagesSent { get; private set; } public void Send(MailMessage msg) { if (string.IsNullOrEmpty(Host) && string.IsNullOrEmpty(PickupDirectoryLocation)) { throw new ApplicationException("[Host/Pickup directory] is null or empty."); } MessagesSent.Add(msg); if (Host == "ERROR") { throw new ApplicationException("Some SMTP error."); } } public void Dispose() { } } public class MockMailTarget : MailTarget { public List<MockSmtpClient> CreatedMocks = new List<MockSmtpClient>(); internal override ISmtpClient CreateSmtpClient() { var client = new MockSmtpClient(); CreatedMocks.Add(client); return client; } public new void InitializeTarget() { base.InitializeTarget(); } public string SmtpClientPickUpDirectory => System.Linq.Enumerable.LastOrDefault(CreatedMocks)?.PickupDirectoryLocation; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.MessageTemplates { using System; using System.Collections; using System.Collections.Generic; using NLog.Common; using NLog.Internal; /// <summary> /// Parameters extracted from parsing <see cref="LogEventInfo.Message"/> as MessageTemplate /// </summary> public sealed class MessageTemplateParameters : IEnumerable<MessageTemplateParameter> { internal static readonly MessageTemplateParameters Empty = new MessageTemplateParameters(string.Empty, ArrayHelper.Empty<object>()); private readonly IList<MessageTemplateParameter> _parameters; /// <inheritDoc/> public IEnumerator<MessageTemplateParameter> GetEnumerator() { return _parameters.GetEnumerator(); } /// <inheritDoc/> IEnumerator IEnumerable.GetEnumerator() { return _parameters.GetEnumerator(); } /// <summary> /// Gets the parameters at the given index /// </summary> public MessageTemplateParameter this[int index] => _parameters[index]; /// <summary> /// Number of parameters /// </summary> public int Count => _parameters.Count; /// <summary>Indicates whether the template should be interpreted as positional /// (all holes are numbers) or named.</summary> public bool IsPositional { get; } /// <summary> /// Indicates whether the template was parsed successful, and there are no unmatched parameters /// </summary> internal bool IsValidTemplate { get; } /// <summary> /// Constructor for parsing the message template with parameters /// </summary> /// <param name="message"><see cref="LogEventInfo.Message"/> including any parameter placeholders</param> /// <param name="parameters">All <see cref="LogEventInfo.Parameters"/></param> internal MessageTemplateParameters(string message, object[] parameters) { var hasParameters = parameters?.Length > 0; bool isPositional = hasParameters; bool isValidTemplate = !hasParameters; _parameters = hasParameters ? ParseMessageTemplate(message, parameters, out isPositional, out isValidTemplate) : ArrayHelper.Empty<MessageTemplateParameter>(); IsPositional = isPositional; IsValidTemplate = isValidTemplate; } /// <summary> /// Constructor for named parameters that already has been parsed /// </summary> internal MessageTemplateParameters(IList<MessageTemplateParameter> templateParameters, string message, object[] parameters) { _parameters = templateParameters ?? ArrayHelper.Empty<MessageTemplateParameter>(); if (parameters != null && _parameters.Count != parameters.Length) { IsValidTemplate = false; } } /// <summary> /// Create MessageTemplateParameter from <paramref name="parameters"/> /// </summary> private static IList<MessageTemplateParameter> ParseMessageTemplate(string template, object[] parameters, out bool isPositional, out bool isValidTemplate) { isPositional = true; isValidTemplate = true; List<MessageTemplateParameter> templateParameters = new List<MessageTemplateParameter>(parameters.Length); try { short holeIndex = 0; TemplateEnumerator templateEnumerator = new TemplateEnumerator(template); while (templateEnumerator.MoveNext()) { if (templateEnumerator.Current.Literal.Skip != 0) { var hole = templateEnumerator.Current.Hole; if (hole.Index != -1 && isPositional) { holeIndex = GetMaxHoleIndex(holeIndex, hole.Index); var value = GetHoleValueSafe(parameters, hole.Index, ref isValidTemplate); templateParameters.Add(new MessageTemplateParameter(hole.Name, value, hole.Format, hole.CaptureType)); } else { if (isPositional) { isPositional = false; if (holeIndex != 0) { // rewind and try again templateEnumerator = new TemplateEnumerator(template); holeIndex = 0; templateParameters.Clear(); continue; } } var value = GetHoleValueSafe(parameters, holeIndex, ref isValidTemplate); templateParameters.Add(new MessageTemplateParameter(hole.Name, value, hole.Format, hole.CaptureType)); holeIndex++; } } } if (isPositional) { if (templateParameters.Count < parameters.Length || holeIndex != parameters.Length) { isValidTemplate = false; } } else { if (templateParameters.Count != parameters.Length) { isValidTemplate = false; } } return templateParameters; } catch (Exception ex) { isValidTemplate = false; InternalLogger.Warn(ex, "Error when parsing a message."); return templateParameters; } } private static short GetMaxHoleIndex(short maxHoleIndex, short holeIndex) { if (maxHoleIndex == 0) maxHoleIndex++; if (maxHoleIndex <= holeIndex) { maxHoleIndex = holeIndex; maxHoleIndex++; } return maxHoleIndex; } private static object GetHoleValueSafe(object[] parameters, short holeIndex, ref bool isValidTemplate) { if (parameters.Length > holeIndex) { return parameters[holeIndex]; } isValidTemplate = false; return null; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System.Collections.Generic; using System.Data; using NLog.Config; using NLog.Layouts; /// <summary> /// Information about database command + parameters. /// </summary> [NLogConfigurationItem] public class DatabaseCommandInfo { /// <summary> /// Gets or sets the type of the command. /// </summary> /// <value>The type of the command.</value> /// <docgen category='Command Options' order='10' /> [RequiredParameter] public CommandType CommandType { get; set; } = CommandType.Text; /// <summary> /// Gets or sets the connection string to run the command against. If not provided, connection string from the target is used. /// </summary> /// <docgen category='Command Options' order='10' /> public Layout ConnectionString { get; set; } /// <summary> /// Gets or sets the command text. /// </summary> /// <docgen category='Command Options' order='10' /> [RequiredParameter] public Layout Text { get; set; } /// <summary> /// Gets or sets a value indicating whether to ignore failures. /// </summary> /// <docgen category='Command Options' order='10' /> public bool IgnoreFailures { get; set; } /// <summary> /// Gets the collection of parameters. Each parameter contains a mapping /// between NLog layout and a database named or positional parameter. /// </summary> /// <docgen category='Command Options' order='10' /> [ArrayParameter(typeof(DatabaseParameterInfo), "parameter")] public IList<DatabaseParameterInfo> Parameters { get; } = new List<DatabaseParameterInfo>(); } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Linq; using System.Text; using JetBrains.Annotations; namespace NLog.Internal { /// <summary> /// Helpers for <see cref="string"/>. /// </summary> internal static class StringHelpers { /// <summary> /// IsNullOrWhiteSpace, including for .NET 3.5 /// </summary> /// <param name="value"></param> /// <returns></returns> [ContractAnnotation("value:null => true")] internal static bool IsNullOrWhiteSpace(string value) { #if !NET35 return string.IsNullOrWhiteSpace(value); #else if (value is null) return true; if (value.Length == 0) return true; return String.IsNullOrEmpty(value.Trim()); #endif } internal static string[] SplitAndTrimTokens(this string value, char delimiter) { if (IsNullOrWhiteSpace(value)) return ArrayHelper.Empty<string>(); if (value.IndexOf(delimiter) == -1) { return new[] { value.Trim() }; } var result = value.Split(new char[] { delimiter }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < result.Length; ++i) { result[i] = result[i].Trim(); if (string.IsNullOrEmpty(result[i])) return result.Where(s => !IsNullOrWhiteSpace(s)).Select(s => s.Trim()).ToArray(); } return result; } /// <summary> /// Replace string with <paramref name="comparison"/> /// </summary> /// <param name="str"></param> /// <param name="oldValue"></param> /// <param name="newValue"></param> /// <param name="comparison"></param> /// <returns>The same reference of nothing has been replaced.</returns> public static string Replace([NotNull] string str, [NotNull] string oldValue, string newValue, StringComparison comparison) { Guard.ThrowIfNull(str); Guard.ThrowIfNull(oldValue); if (str.Length == 0) { //nothing to do return str; } StringBuilder sb = null; int previousIndex = 0; int index = str.IndexOf(oldValue, comparison); while (index != -1) { sb = sb ?? new StringBuilder(str.Length); if (previousIndex >= str.Length) { // for cases that 2 chars is one symbol break; } sb.Append(str.Substring(previousIndex, index - previousIndex)); sb.Append(newValue); index += oldValue.Length; previousIndex = index; if (index >= str.Length) { // for cases that 2 chars is one symbol break; } index = str.IndexOf(oldValue, index, comparison); } if (sb is null) { //nothing replaced return str; } if (previousIndex < str.Length) { sb.Append(str.Substring(previousIndex)); } return sb.ToString(); } /// <summary>Concatenates all the elements of a string array, using the specified separator between each element. </summary> /// <param name="separator">The string to use as a separator. <paramref name="separator" /> is included in the returned string only if <paramref name="values" /> has more than one element.</param> /// <param name="values">An collection that contains the elements to concatenate. </param> /// <returns>A string that consists of the elements in <paramref name="values" /> delimited by the <paramref name="separator" /> string. If <paramref name="values" /> is an empty array, the method returns <see cref="System.String.Empty" />.</returns> /// <exception cref="System.ArgumentNullException"> /// <paramref name="values" /> is <see langword="null" />. </exception> internal static string Join(string separator, IEnumerable<string> values) { #if !NET35 return string.Join(separator, values); #else return string.Join(separator, values.ToArray()); #endif } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; namespace NLog.Targets { /// <summary> /// Arguments for <see cref="NetworkTarget.LogEventDropped"/> events. /// </summary> public class NetworkLogEventDroppedEventArgs : EventArgs { /// <inheritdoc cref="NetworkLogEventDroppedReason.MaxMessageSizeOverflow"/> internal static readonly NetworkLogEventDroppedEventArgs MaxMessageSizeOverflow = new NetworkLogEventDroppedEventArgs(NetworkLogEventDroppedReason.MaxMessageSizeOverflow); /// <inheritdoc cref="NetworkLogEventDroppedReason.MaxConnectionsOverflow"/> internal static readonly NetworkLogEventDroppedEventArgs MaxConnectionsOverflow = new NetworkLogEventDroppedEventArgs(NetworkLogEventDroppedReason.MaxConnectionsOverflow); /// <inheritdoc cref="NetworkLogEventDroppedReason.MaxQueueOverflow"/> internal static readonly NetworkLogEventDroppedEventArgs MaxQueueOverflow = new NetworkLogEventDroppedEventArgs(NetworkLogEventDroppedReason.MaxQueueOverflow); /// <inheritdoc cref="NetworkLogEventDroppedReason.NetworkError"/> internal static readonly NetworkLogEventDroppedEventArgs NetworkErrorDetected = new NetworkLogEventDroppedEventArgs(NetworkLogEventDroppedReason.NetworkError); /// <summary> /// Creates new instance of NetworkTargetLogEventDroppedEventArgs /// </summary> public NetworkLogEventDroppedEventArgs(NetworkLogEventDroppedReason reason) { Reason = reason; } /// <summary> /// The reason why log was dropped /// </summary> public NetworkLogEventDroppedReason Reason { get; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Config { using System; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.IO; using MyExtensionNamespace; using NLog.Common; using NLog.Config; using NLog.Filters; using NLog.Layouts; using NLog.Targets; using Xunit; public class ExtensionTests : NLogTestBase { private readonly static string extensionAssemblyName1 = "SampleExtensions"; private readonly static string extensionAssemblyFullPath1 = Path.GetFullPath("SampleExtensions.dll"); private static string GetExtensionAssemblyFullPath() { #if NETSTANDARD Assert.NotNull(typeof(FooLayout)); return typeof(FooLayout).GetTypeInfo().Assembly.Location; #else return extensionAssemblyFullPath1; #endif } [Fact] public void ExtensionTest1() { Assert.NotNull(typeof(FooLayout)); var configuration = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <extensions> <add assemblyFile='" + GetExtensionAssemblyFullPath() + @"' /> </extensions> <targets> <target name='t' type='MyTarget' /> <target name='d1' type='Debug' layout='${foo}' /> <target name='d2' type='Debug'> <layout type='FooLayout' x='1'> </layout> </target> </targets> <rules> <logger name='*' writeTo='t'> <filters> <whenFoo x='44' action='Log' /> </filters> </logger> </rules> </nlog>").LogFactory.Configuration; Target myTarget = configuration.FindTargetByName("t"); Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName); var d1Target = (DebugTarget)configuration.FindTargetByName("d1"); var layout = d1Target.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Single(layout.Renderers); Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName); var d2Target = (DebugTarget)configuration.FindTargetByName("d2"); Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName); Assert.Equal(1, configuration.LoggingRules[0].Filters.Count); Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName); } [Fact] public void ExtensionTest2() { var configuration = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <extensions> <add assembly='" + extensionAssemblyName1 + @"' /> </extensions> <targets> <target name='t' type='MyTarget' /> <target name='d1' type='Debug' layout='${foo}' /> <target name='d2' type='Debug'> <layout type='FooLayout' x='1'> </layout> </target> </targets> <rules> <logger name='*' writeTo='t'> <filters> <whenFoo x='44' action='Ignore' /> <when condition='myrandom(10)==3' action='Log' /> </filters> </logger> </rules> </nlog>").LogFactory.Configuration; Target myTarget = configuration.FindTargetByName("t"); Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName); var d1Target = (DebugTarget)configuration.FindTargetByName("d1"); var layout = d1Target.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Single(layout.Renderers); Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName); var d2Target = (DebugTarget)configuration.FindTargetByName("d2"); Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName); Assert.Equal(2, configuration.LoggingRules[0].Filters.Count); Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName); var cbf = configuration.LoggingRules[0].Filters[1] as ConditionBasedFilter; Assert.NotNull(cbf); Assert.Equal("(myrandom(10) == 3)", cbf.Condition.ToString()); } [Fact] public void ExtensionWithPrefixLoadTwiceTest() { var configuration = new LogFactory().Setup().SetupExtensions(ext => ext.RegisterAssembly(extensionAssemblyName1)) .LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <extensions> <add assembly='" + extensionAssemblyName1 + @"' prefix='twice' /> </extensions> <targets> <target name='t' type='twice.MyTarget' /> <target name='d1' type='Debug' layout='${foo}' /> <target name='d2' type='Debug'> <layout type='twice.FooLayout' x='1'> </layout> </target> </targets> <rules> <logger name='*' writeTo='t'> <filters> <whenFoo x='44' action='Ignore' /> <when condition='myrandom(10)==3' action='Log' /> </filters> </logger> </rules> </nlog>").LogFactory.Configuration; Target myTarget = configuration.FindTargetByName("t"); Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName); var d1Target = (DebugTarget)configuration.FindTargetByName("d1"); var layout = d1Target.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Single(layout.Renderers); Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName); var d2Target = (DebugTarget)configuration.FindTargetByName("d2"); Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName); Assert.Equal(2, configuration.LoggingRules[0].Filters.Count); Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName); var cbf = configuration.LoggingRules[0].Filters[1] as ConditionBasedFilter; Assert.NotNull(cbf); Assert.Equal("(myrandom(10) == 3)", cbf.Condition.ToString()); } [Fact] public void ExtensionWithPrefixTest() { var configuration = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <extensions> <add prefix='myprefix' assemblyFile='" + GetExtensionAssemblyFullPath() + @"' /> </extensions> <targets> <target name='t' type='myprefix.MyTarget' /> <target name='d1' type='Debug' layout='${myprefix.foo}' /> <target name='d2' type='Debug'> <layout type='myprefix.FooLayout' x='1'> </layout> </target> </targets> <rules> <logger name='*' writeTo='t'> <filters> <myprefix.whenFoo x='44' action='Log' /> </filters> </logger> </rules> </nlog>").LogFactory.Configuration; Target myTarget = configuration.FindTargetByName("t"); Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName); var d1Target = (DebugTarget)configuration.FindTargetByName("d1"); var layout = d1Target.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Single(layout.Renderers); Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName); var d2Target = (DebugTarget)configuration.FindTargetByName("d2"); Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName); Assert.Equal(1, configuration.LoggingRules[0].Filters.Count); Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName); } [Fact] public void ExtensionTest4() { Assert.NotNull(typeof(FooLayout)); var configuration = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <extensions> <add type='" + typeof(MyTarget).AssemblyQualifiedName + @"' /> <add type='" + typeof(FooLayout).AssemblyQualifiedName + @"' /> <add type='" + typeof(FooLayoutRenderer).AssemblyQualifiedName + @"' /> <add type='" + typeof(WhenFooFilter).AssemblyQualifiedName + @"' /> </extensions> <targets> <target name='t' type='MyTarget' /> <target name='d1' type='Debug' layout='${foo}' /> <target name='d2' type='Debug'> <layout type='FooLayout' x='1'> </layout> </target> </targets> <rules> <logger name='*' writeTo='t'> <filters> <whenFoo x='44' action='Log' /> </filters> </logger> </rules> </nlog>").LogFactory.Configuration; Target myTarget = configuration.FindTargetByName("t"); Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName); var d1Target = (DebugTarget)configuration.FindTargetByName("d1"); var layout = d1Target.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Single(layout.Renderers); Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName); var d2Target = (DebugTarget)configuration.FindTargetByName("d2"); Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName); Assert.Equal(1, configuration.LoggingRules[0].Filters.Count); Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName); } [Fact] [Obsolete("Instead override type-creation by calling NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public void RegisterNamedTypeLessTest() { Assert.NotNull(typeof(FooLayout)); var configurationItemFactory = new ConfigurationItemFactory(); configurationItemFactory.GetLayoutFactory().RegisterNamedType("foo", typeof(FooLayout).ToString() + "," + typeof(FooLayout).Assembly.GetName().Name); Assert.NotNull(configurationItemFactory.LayoutFactory.CreateInstance("foo")); } [Fact] public void ExtensionTest_extensions_not_top_and_used() { Assert.NotNull(typeof(FooLayout)); var configuration = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='t' type='MyTarget' /> <target name='d1' type='Debug' layout='${foo}' /> <target name='d2' type='Debug'> <layout type='FooLayout' x='1'> </layout> </target> </targets> <rules> <logger name='*' writeTo='t'> <filters> <whenFoo x='44' action='Log' /> </filters> </logger> </rules> <extensions> <add assemblyFile='" + GetExtensionAssemblyFullPath() + @"' /> </extensions> </nlog>").LogFactory.Configuration; Target myTarget = configuration.FindTargetByName("t"); Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName); var d1Target = (DebugTarget)configuration.FindTargetByName("d1"); var layout = d1Target.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Single(layout.Renderers); Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName); var d2Target = (DebugTarget)configuration.FindTargetByName("d2"); Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName); Assert.Equal(1, configuration.LoggingRules[0].Filters.Count); Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName); } [Fact] public void ExtensionShouldThrowNLogConfiguratonExceptionWhenRegisteringInvalidType() { var configXml = @" <nlog throwConfigExceptions='true'> <extensions> <add type='some_type_that_doesnt_exist'/> </extensions> </nlog>"; Assert.Throws<NLogConfigurationException>(() => XmlLoggingConfiguration.CreateFromXmlString(configXml)); } [Fact] public void ExtensionShouldThrowNLogConfiguratonExceptionWhenRegisteringInvalidAssembly() { var configXml = @" <nlog throwConfigExceptions='true'> <extensions> <add assembly='some_assembly_that_doesnt_exist'/> </extensions> </nlog>"; Assert.Throws<NLogConfigurationException>(() => XmlLoggingConfiguration.CreateFromXmlString(configXml)); } [Fact] public void ExtensionShouldThrowNLogConfiguratonExceptionWhenRegisteringInvalidAssemblyFile() { var configXml = @" <nlog throwConfigExceptions='true'> <extensions> <add assemblyfile='some_file_that_doesnt_exist'/> </extensions> </nlog>"; Assert.Throws<NLogConfigurationException>(() => XmlLoggingConfiguration.CreateFromXmlString(configXml)); } [Fact] public void ExtensionShouldNotThrowWhenRegisteringInvalidTypeIfThrowConfigExceptionsFalse() { var configXml = @" <nlog throwConfigExceptions='false'> <extensions> <add type='some_type_that_doesnt_exist'/> <add assembly='NLog'/> </extensions> </nlog>"; var result = XmlLoggingConfiguration.CreateFromXmlString(configXml); Assert.NotNull(result); } [Fact] public void ExtensionShouldNotThrowWhenRegisteringInvalidAssemblyIfThrowConfigExceptionsFalse() { var configXml = @" <nlog throwConfigExceptions='false'> <extensions> <add assembly='some_assembly_that_doesnt_exist'/> </extensions> </nlog>"; var result = XmlLoggingConfiguration.CreateFromXmlString(configXml); Assert.NotNull(result); } [Fact] public void ExtensionShouldNotThrowWhenRegisteringInvalidAssemblyFileIfThrowConfigExceptionsFalse() { var configXml = @" <nlog throwConfigExceptions='false'> <extensions> <add assemblyfile='some_file_that_doesnt_exist'/> </extensions> </nlog>"; var result = XmlLoggingConfiguration.CreateFromXmlString(configXml); Assert.NotNull(result); } [Fact] public void CustomXmlNamespaceTest() { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true' xmlns:foo='http://bar'> <targets> <target name='d' type='foo:Debug' /> </targets> </nlog>"); var d1Target = (DebugTarget)configuration.FindTargetByName("d"); Assert.NotNull(d1Target); } [Fact] [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] public void Extension_should_be_auto_loaded_when_following_NLog_dll_format() { var fileLocations = AssemblyExtensionLoader.GetAutoLoadingFileLocations().ToArray(); Assert.NotEmpty(fileLocations); Assert.NotNull(fileLocations[0].Key); Assert.NotNull(fileLocations[0].Value); // Primary search location is NLog-assembly Assert.Equal(fileLocations.Length, fileLocations.Select(f => f.Key).Distinct().Count()); var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true' autoLoadExtensions='true'> <targets> <target name='t' type='AutoLoadTarget' /> </targets> <rules> <logger name='*' writeTo='t' /> </rules> </nlog>").LogFactory; var autoLoadedTarget = logFactory.Configuration.FindTargetByName("t"); Assert.Equal("NLogAutloadExtension.AutoLoadTarget", autoLoadedTarget.GetType().ToString()); } [Fact] public void ExtensionTypeWithAssemblyNameCanLoad() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='t' type='AutoLoadTarget, NLogAutoLoadExtension' /> </targets> <rules> <logger name='*' writeTo='t' /> </rules> </nlog>").LogFactory; var autoLoadedTarget = logFactory.Configuration.FindTargetByName("t"); Assert.Equal("NLogAutloadExtension.AutoLoadTarget", autoLoadedTarget.GetType().ToString()); } [Theory] [InlineData(true)] [InlineData(false)] [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] public void Extension_loading_could_be_canceled(bool cancel) { ConfigurationItemFactory.Default = null; EventHandler<AssemblyLoadingEventArgs> onAssemblyLoading = (sender, e) => { if (e.Assembly.FullName.Contains("NLogAutoLoadExtension")) { e.Cancel = cancel; } }; try { ConfigurationItemFactory.AssemblyLoading += onAssemblyLoading; using (new NoThrowNLogExceptions()) { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='false' autoLoadExtensions='true'> <targets> <target name='t' type='AutoLoadTarget' /> </targets> <rules> <logger name='*' writeTo='t' /> </rules> </nlog>").LogFactory; var autoLoadedTarget = logFactory.Configuration.FindTargetByName("t"); if (cancel) { Assert.Null(autoLoadedTarget); } else { Assert.Equal("NLogAutloadExtension.AutoLoadTarget", autoLoadedTarget.GetType().ToString()); } } } finally { //cleanup ConfigurationItemFactory.AssemblyLoading -= onAssemblyLoading; } } [Fact] public void Extensions_NLogPackageLoader_should_beCalled() { try { var writer = new StringWriter(); InternalLogger.LogWriter = writer; InternalLogger.LogLevel = LogLevel.Debug; var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <extensions> <add assembly='PackageLoaderTestAssembly' /> </extensions> </nlog>"); var logs = writer.ToString(); Assert.Contains("Preload successfully invoked for 'LoaderTestInternal.NLogPackageLoader'", logs); Assert.Contains("Preload successfully invoked for 'LoaderTestPublic.NLogPackageLoader'", logs); Assert.Contains("Preload successfully invoked for 'LoaderTestPrivateNestedStatic.SomeType+NLogPackageLoader'", logs); Assert.Contains("Preload successfully invoked for 'LoaderTestPrivateNested.SomeType+NLogPackageLoader'", logs); //4 times successful Assert.Equal(4, Regex.Matches(logs, Regex.Escape("Preload successfully invoked for '")).Count); } finally { InternalLogger.Reset(); } } [Fact] public void ImplicitConversionOperatorTest() { var config = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <extensions> <add assemblyFile='" + GetExtensionAssemblyFullPath() + @"' /> </extensions> <targets> <target name='myTarget' type='MyTarget' layout='123' /> </targets> <rules> <logger name='*' level='Debug' writeTo='myTarget' /> </rules> </nlog>"); var target = config.FindTargetByName<MyTarget>("myTarget"); Assert.NotNull(target); Assert.Equal(123, target.Layout.X); } [Fact] [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] public void LoadExtensionFromAppDomain() { try { LoadManuallyLoadedExtensionDll(); InternalLogger.LogLevel = LogLevel.Trace; var writer = new StringWriter(); InternalLogger.LogWriter = writer; var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <extensions> <add assembly='Manually-Loaded-Extension' /> </extensions> <targets> <target name='t' type='ManuallyLoadedTarget' /> </targets> </nlog>"); // We get Exception for normal Assembly-Load only in net452. #if !NETSTANDARD && !MONO var logs = writer.ToString(); Assert.Contains("Try find 'Manually-Loaded-Extension' in current domain", logs); #endif // Was AssemblyLoad successful? var autoLoadedTarget = configuration.FindTargetByName("t"); Assert.Equal("ManuallyLoadedExtension.ManuallyLoadedTarget", autoLoadedTarget.GetType().FullName); } finally { InternalLogger.Reset(); } } [Fact] [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] public void FullyQualifiedExtensionTest() { // Arrange LoadManuallyLoadedExtensionDll(); // Act var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"<nlog throwConfigExceptions='true'> <targets> <target name='t' type='ManuallyLoadedTarget, Manually-Loaded-Extension' /> </targets> </nlog>").LogFactory; // Assert Assert.NotNull(logFactory.Configuration.FindTargetByName("t")); } [Theory] [InlineData(null, null)] [InlineData("", null)] [InlineData("ManuallyLoadedTarget", "ManuallyLoadedExtension.ManuallyLoadedTarget")] [InlineData("ManuallyLoaded-Target", "ManuallyLoadedExtension.ManuallyLoadedTarget")] [InlineData(", Manually-Loaded-Extension", null)] // border case [InlineData("ManuallyLoadedTarget,", null)] // border case [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] public void NormalizeNameTest(string input, string expected) { // Arrange var assembly = LoadManuallyLoadedExtensionDll(); var configFactory = new ConfigurationItemFactory(assembly); // Act var foundDefinition = configFactory.GetTargetFactory().TryGetDefinition(input, out var outputDefinition); var foundInstance = configFactory.TargetFactory.TryCreateInstance(input, out var outputInstance); var instance = (foundDefinition || foundInstance || expected != null) ? configFactory.GetTargetFactory().CreateInstance(input) : null; // Assert Assert.Equal(expected != null, foundInstance); Assert.Equal(expected != null, foundDefinition); Assert.Equal(expected, instance?.GetType().ToString()); Assert.Equal(expected, outputInstance?.GetType().ToString()); Assert.Equal(expected, outputDefinition?.ToString()); } [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] private static Assembly LoadManuallyLoadedExtensionDll() { // ...\NLog\tests\NLog.UnitTests\bin\Debug\netcoreapp2.0\nlog.dll var nlogDirectory = new DirectoryInfo(AssemblyExtensionLoader.GetAutoLoadingFileLocations().First().Key); var configurationDirectory = nlogDirectory.Parent; var testsDirectory = configurationDirectory.Parent.Parent.Parent; var manuallyLoadedAssemblyPath = Path.Combine(testsDirectory.FullName, "ManuallyLoadedExtension", "bin", configurationDirectory.Name, #if NETSTANDARD "netstandard2.0", #elif NET35 || NET40 || NET45 "net461", #else nlogDirectory.Name, #endif "Manually-Loaded-Extension.dll"); return Assembly.LoadFrom(manuallyLoadedAssemblyPath); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Globalization; using System.Reflection; using NLog.Config; using NLog.Internal; namespace NLog.Layouts { /// <summary> /// Typed Value that is easily configured from NLog.config file /// </summary> [NLogConfigurationItem] public sealed class ValueTypeLayoutInfo { private static readonly Layout<string> _fixedNullValue = new Layout<string>(null); /// <summary> /// Initializes a new instance of the <see cref="ValueTypeLayoutInfo" /> class. /// </summary> public ValueTypeLayoutInfo() { } /// <summary> /// Gets or sets the layout that will render the result value /// </summary> /// <docgen category='Layout Options' order='10' /> [RequiredParameter] public Layout Layout { get => _layout ?? (_layout = CreateTypedLayout(ValueType, ExtractExistingValue(_innerLayout))); // Ensure the correct Layout-object is initialized by config, and scanned by NLog Target set { _defaultValueObject = null; if (value is ITypedLayout typedLayout) { _layout = _innerLayout = value; _valueType = typedLayout.ValueType; _typedLayout = typedLayout; } else { _layout = null; _innerLayout = value; _typedLayout = null; } } } private Layout _layout; private Layout _innerLayout; private ITypedLayout _typedLayout; /// <summary> /// Gets or sets the result value type, for conversion of layout rendering output /// </summary> /// <docgen category='Layout Options' order='50' /> public Type ValueType { get => _valueType; set { _valueType = value; _layout = null; if (!ReferenceEquals(_innerLayout, _typedLayout) && !(_innerLayout is null)) _typedLayout = null; _defaultValueObject = null; } } private Type _valueType; /// <summary> /// Gets or sets the fallback value when result value is not available /// </summary> /// <docgen category='Layout Options' order='50' /> public Layout DefaultValue { get => _defaultValue; set { _defaultValue = value; _defaultValueObject = null; _typedDefaultValue = value as ITypedLayout; } } private Layout _defaultValue; private ITypedLayout _typedDefaultValue; private object _defaultValueObject; /// <summary> /// Gets or sets the fallback value should be null (instead of default value of <see cref="ValueType"/>) when result value is not available /// </summary> /// <docgen category='Layout Options' order='100' /> public bool ForceDefaultValueNull { get => _forceDefaultValueNull; set { _forceDefaultValueNull = value; if (value) DefaultValue = _fixedNullValue; else if (DefaultValue is Layout<string> typedLayout && typedLayout.IsFixed && typedLayout.FixedValue is null) DefaultValue = null; } } private bool _forceDefaultValueNull; /// <summary> /// Gets or sets format used for parsing parameter string-value for type-conversion /// </summary> /// <docgen category='Layout Options' order='100' /> public string ValueParseFormat { get => _valueParseFormat; set { _valueParseFormat = value; if (!ReferenceEquals(_innerLayout, _typedLayout) && !(_innerLayout is null)) _typedLayout = null; _defaultValueObject = null; } } private string _valueParseFormat; /// <summary> /// Gets or sets the culture used for parsing parameter string-value for type-conversion /// </summary> /// <docgen category='Layout Options' order='100' /> public CultureInfo ValueParseCulture { get => _valueParseCulture; set { _valueParseCulture = value; if (!ReferenceEquals(_innerLayout, _typedLayout) && !(_innerLayout is null)) _typedLayout = null; _defaultValueObject = null; } } private CultureInfo _valueParseCulture = CultureInfo.InvariantCulture; /// <summary> /// Render Result Value /// </summary> /// <param name="logEvent">Log event for rendering</param> /// <returns>Result value when available, else fallback to defaultValue</returns> public object RenderValue(LogEventInfo logEvent) { var layout = Layout; if (_typedLayout != null) { var defaultValue = GetTypedDefaultValue(); return _typedLayout.RenderValue(logEvent, defaultValue); } else if (layout != null) { var valueType = _valueType ?? (_valueType = ValueType ?? typeof(string)); if (valueType == typeof(object) && layout.TryGetRawValue(logEvent, out var rawValue)) { return rawValue; } var stringValue = layout.Render(logEvent); if (string.IsNullOrEmpty(stringValue)) { return GetTypedDefaultValue(); } return stringValue; } else { return null; } } private object GetTypedDefaultValue() { return _defaultValueObject ?? (_defaultValueObject = CreateTypedDefaultValue()); } private Layout CreateTypedLayout(Type valueType, object existingValue) { if (valueType is null || valueType == typeof(string) || valueType == typeof(object)) return existingValue as Layout ?? _innerLayout; try { var concreteType = typeof(Layout<>).MakeGenericType(valueType); var constructorParams = existingValue is Layout ? new object[] { existingValue, ValueParseFormat, ValueParseCulture } : new object[] { existingValue }; var typedLayout = (Layout)Activator.CreateInstance(concreteType, BindingFlags.Instance | BindingFlags.Public, null, constructorParams, null); _typedLayout = typedLayout as ITypedLayout; return typedLayout; } catch (TargetInvocationException ex) { if (ex.InnerException is null) throw; if (ex.InnerException.MustBeRethrown()) throw ex.InnerException; return _innerLayout; } } private object ExtractExistingValue(object innerValue) { if (innerValue is SimpleLayout simpleLayout) return simpleLayout; else if (innerValue is ITypedLayout typedLayout) return typedLayout.InnerLayout ?? typedLayout.FixedObjectValue; else if (innerValue is Layout innerLayout) return innerLayout.Render(LogEventInfo.CreateNullEvent()); else return innerValue; } private object CreateTypedDefaultValue() { if (_typedDefaultValue != null && _typedDefaultValue.IsFixed) return _typedDefaultValue.FixedObjectValue; if (_defaultValue is null) return string.Empty; if (_typedLayout is null) return _defaultValue.Render(LogEventInfo.CreateNullEvent()); if (_typedLayout.IsFixed) return string.Empty; var defaultStringValue = _defaultValue.Render(LogEventInfo.CreateNullEvent()); if (string.IsNullOrEmpty(defaultStringValue)) return string.Empty; if (_typedLayout.TryParseValueFromString(defaultStringValue, out object defaultObjectValue)) return defaultObjectValue ?? string.Empty; return string.Empty; } } } <file_sep>using NLog; using NLog.Targets; using NLog.Targets.Wrappers; using System.Threading; class Example { static void Main(string[] args) { FileTarget target = new FileTarget(); target.Layout = "${longdate} ${logger} ${message}"; target.FileName = "${basedir}/logs/logfile.txt"; // where to store the archive files target.ArchiveFileName = "${basedir}/archives/log.{#####}.txt"; target.ArchiveEvery = FileTarget.ArchiveEveryMode.Minute; target.ArchiveNumbering = FileTarget.ArchiveNumberingMode.Rolling; target.MaxArchiveFiles = 3; target.ArchiveAboveSize = 10000; // this speeds up things when no other processes are writing to the file target.ConcurrentWrites = true; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); // generate a large number of messages, sleeping 1/10 of second between writes // to observe time-based archiving which occurs every minute // the volume is high enough to cause ArchiveAboveSize to be triggered // so that log files larger than 10000 bytes are archived as well // // you get: // logs/logfile.txt // // and your archives go to: // // archives/log.00000.txt // archives/log.00001.txt // archives/log.00002.txt // archives/log.00003.txt // archives/log.00004.txt for (int i = 0; i < 2500; ++i) { logger.Debug("log message {i}", i); Thread.Sleep(100); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD namespace NLog.UnitTests { using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.IO; using System.Text; using Microsoft.CSharp; using Xunit; static class ProcessRunner { static ProcessRunner() { string sourceCode = @" using System; using System.Reflection; class C1 { static int Main(string[] args) { try { if (args.Length < 3) throw new Exception(""Usage: Runner.exe \""AssemblyName\"" \""ClassName\"" \""MethodName\"" \""Parameter1...N\""""); string assemblyName = args[0]; string className = args[1]; string methodName = args[2]; object[] arguments = new object[args.Length - 3]; for (int i = 0; i < arguments.Length; ++i) arguments[i] = args[3 + i]; Assembly assembly = Assembly.Load(assemblyName); Type type = assembly.GetType(className); if (type == null) throw new Exception(className + "" not found in "" + assemblyName); MethodInfo method = type.GetMethod(methodName); if (method == null) throw new Exception(methodName + "" not found in "" + type); object targetObject = null; if (!method.IsStatic) targetObject = Activator.CreateInstance(type); method.Invoke(targetObject, arguments); return 0; } catch (Exception ex) { Console.WriteLine(ex); return 1; } } }"; CSharpCodeProvider provider = new CSharpCodeProvider(); var options = new CompilerParameters(); options.OutputAssembly = "Runner.exe"; options.GenerateExecutable = true; options.IncludeDebugInformation = true; // To allow debugging the generated Runner.exe we need to keep files. // See https://stackoverflow.com/questions/875723/how-to-debug-break-in-codedom-compiled-code options.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true); var results = provider.CompileAssemblyFromSource(options, sourceCode); Assert.False(results.Errors.HasWarnings); Assert.False(results.Errors.HasErrors); } public static Process SpawnMethod(Type type, string methodName, params string[] p) { string assemblyName = type.Assembly.FullName; string typename = type.FullName; StringBuilder sb = new StringBuilder(); #if MONO sb.AppendFormat("\"{0}\" ", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Runner.exe")); #endif sb.AppendFormat("\"{0}\" \"{1}\" \"{2}\"", assemblyName, typename, methodName); foreach (string s in p) { sb.Append(" "); sb.Append("\""); sb.Append(s); sb.Append("\""); } Process proc = new Process(); proc.StartInfo.Arguments = sb.ToString(); #if MONO proc.StartInfo.FileName = "mono"; #else proc.StartInfo.FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Runner.exe"); #endif proc.StartInfo.UseShellExecute = false; proc.StartInfo.CreateNoWindow = true; // Hint: // In case we wanna redirect stdout we should drain the redirected pipe continuously. // Otherwise Runner.exe's console buffer is full rather fast, leading to a lock within Console.Write(Line). proc.Start(); return proc; } } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using NLog.Config; using Xunit; namespace NLog.UnitTests.Internal.Reflection { public class PropertyHelperTests : NLogTestBase { [Fact] public void AssignArrayPropertyFromStringWillResultInNotSupportedExceptionSomeWhereDeep() { // Arrange var config = @" <nlog throwExceptions='true'> <targets> <target name='f' type='File' filename='test.log'> <layout type='CSVLayout' column='a'> </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='f' /> </rules> </nlog>"; // Act var ex = Assert.Throws<NLogConfigurationException>(() => XmlLoggingConfiguration.CreateFromXmlString(config)); // Assert Assert.IsType<NLogConfigurationException>(ex.InnerException); Assert.IsType<NotSupportedException>(ex.InnerException.InnerException); Assert.Contains("because property of type array and not scalar value", ex.InnerException.InnerException.Message); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets { using System; using System.Linq; using System.Collections.Generic; using Xunit; using NLog.Targets; using NLog.Targets.Wrappers; public class TargetWithContextTest : NLogTestBase { public class CustomTargetWithContext : TargetWithContext { public bool SkipAssert { get; set; } public class CustomTargetPropertyWithContext : TargetPropertyWithContext { public string Hello { get; set; } } [NLog.Config.ArrayParameter(typeof(CustomTargetPropertyWithContext), "contextproperty")] public override IList<TargetPropertyWithContext> ContextProperties { get; } public CustomTargetWithContext() { ContextProperties = new List<TargetPropertyWithContext>(); } public IDictionary<string, object> LastCombinedProperties; public string LastMessage; protected override void Write(LogEventInfo logEvent) { if (!SkipAssert) { Assert.True(logEvent.HasStackTrace); var scopeProperties = ScopeContext.GetAllProperties(); // See that async-timer cannot extract anything from scope-context Assert.Empty(scopeProperties); var scopeNested = ScopeContext.GetAllNestedStates(); // See that async-timer cannot extract anything from scope-context Assert.Empty(scopeNested); } LastCombinedProperties = base.GetAllProperties(logEvent); var nestedStates = base.GetScopeContextNested(logEvent); if (nestedStates.Count != 0) LastCombinedProperties["TestKey"] = nestedStates[0]; LastMessage = base.RenderLogEvent(Layout, logEvent); } } [Fact] public void TargetWithContextAsyncTest() { CustomTargetWithContext target = new CustomTargetWithContext(); target.ContextProperties.Add(new TargetPropertyWithContext("threadid", "${threadid}")); target.IncludeScopeProperties = true; target.IncludeGdc = true; target.IncludeScopeNested = true; target.IncludeCallSite = true; AsyncTargetWrapper wrapper = new AsyncTargetWrapper(); wrapper.WrappedTarget = target; wrapper.TimeToSleepBetweenBatches = 0; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(wrapper); }).GetLogger("Example"); GlobalDiagnosticsContext.Clear(); ScopeContext.Clear(); GlobalDiagnosticsContext.Set("TestKey", "Hello Global World"); GlobalDiagnosticsContext.Set("GlobalKey", "Hello Global World"); ScopeContext.PushProperty("TestKey", "Hello Async World"); ScopeContext.PushProperty("AsyncKey", "Hello Async World"); logger.Debug("log message"); Assert.True(WaitForLastMessage(target)); Assert.NotEqual(0, target.LastMessage.Length); Assert.NotNull(target.LastCombinedProperties); Assert.NotEmpty(target.LastCombinedProperties); Assert.Equal(5, target.LastCombinedProperties.Count); Assert.Contains(new KeyValuePair<string, object>("GlobalKey", "Hello Global World"), target.LastCombinedProperties); Assert.Contains(new KeyValuePair<string, object>("AsyncKey", "Hello Async World"), target.LastCombinedProperties); Assert.Contains(new KeyValuePair<string, object>("TestKey", "Hello Async World"), target.LastCombinedProperties); Assert.Contains(new KeyValuePair<string, object>("TestKey_1", "Hello Global World"), target.LastCombinedProperties); Assert.Contains(new KeyValuePair<string, object>("threadid", System.Environment.CurrentManagedThreadId.ToString()), target.LastCombinedProperties); } private static bool WaitForLastMessage(CustomTargetWithContext target) { System.Threading.Thread.Sleep(1); for (int i = 0; i < 1000; ++i) { if (target.LastMessage != null) return true; System.Threading.Thread.Sleep(1); } return false; } [Fact] [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public void TargetWithContextMdcSerializeTest() { MappedDiagnosticsContext.Clear(); MappedDiagnosticsContext.Set("TestKey", new { a = "b" }); CustomTargetWithContext target = new CustomTargetWithContext() { IncludeMdc = true, SkipAssert = true }; WriteAndAssertSingleKey(target); } [Fact] [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public void TargetWithContextMdlcSerializeTest() { MappedDiagnosticsLogicalContext.Clear(); MappedDiagnosticsLogicalContext.Set("TestKey", new { a = "b" }); CustomTargetWithContext target = new CustomTargetWithContext() { IncludeMdlc = true, SkipAssert = true }; WriteAndAssertSingleKey(target); } [Fact] [Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")] public void TargetWithContextNdcSerializeTest() { NestedDiagnosticsContext.Clear(); NestedDiagnosticsContext.Push(new { a = "b" }); CustomTargetWithContext target = new CustomTargetWithContext() { IncludeNdc = true, SkipAssert = true }; WriteAndAssertSingleKey(target); } [Fact] [Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")] public void TargetWithContextNdlcSerializeTest() { NestedDiagnosticsLogicalContext.Clear(); NestedDiagnosticsLogicalContext.Push(new { a = "b" }); CustomTargetWithContext target = new CustomTargetWithContext() { IncludeNdlc = true, SkipAssert = true }; WriteAndAssertSingleKey(target); } private static void WriteAndAssertSingleKey(CustomTargetWithContext target) { AsyncTargetWrapper wrapper = new AsyncTargetWrapper { WrappedTarget = target, TimeToSleepBetweenBatches = 0 }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(wrapper); }).GetLogger("Example"); logger.Debug("log message"); Assert.True(WaitForLastMessage(target)); Assert.Equal("{ a = b }", target.LastCombinedProperties["TestKey"]); } [Fact] public void TargetWithContextConfigTest() { var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterTarget<CustomTargetWithContext>("contexttarget")) .LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='contexttarget' includeCallSite='true'> <contextproperty name='threadid' layout='${threadid}' hello='world' /> </target> </targets> <rules> <logger name='*' levels='Error' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); ScopeContext.Clear(); logger.Error("log message"); var target = logFactory.Configuration.FindTargetByName("debug") as CustomTargetWithContext; Assert.NotEqual(0, target.LastMessage.Length); var lastCombinedProperties = target.LastCombinedProperties; Assert.NotEmpty(lastCombinedProperties); Assert.Contains(new KeyValuePair<string, object>("threadid", System.Environment.CurrentManagedThreadId.ToString()), lastCombinedProperties); } [Fact] public void TargetWithContextAsyncPropertyTest() { var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterTarget<CustomTargetWithContext>("contexttarget")) .LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <default-wrapper type='AsyncWrapper' timeToSleepBetweenBatches='0' overflowAction='Block' /> <target name='debug' type='contexttarget' includeCallSite='true' includeEventProperties='true' excludeProperties='password' /> </targets> <rules> <logger name='*' levels='Error' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); var target = logFactory.Configuration.AllTargets.OfType<CustomTargetWithContext>().FirstOrDefault(); LogEventInfo logEvent = LogEventInfo.Create(LogLevel.Error, logger.Name, "Hello"); logEvent.Properties["name"] = "Kenny"; logEvent.Properties["password"] = "<PASSWORD>"; logger.Error(logEvent); logFactory.Flush(); Assert.NotEqual(0, target.LastMessage.Length); var lastCombinedProperties = target.LastCombinedProperties; Assert.Single(lastCombinedProperties); Assert.Contains(new KeyValuePair<string, object>("name", "Kenny"), lastCombinedProperties); logger.Error("Hello {name}", "Cartman"); logEvent.Properties["Password"] = "<PASSWORD>"; logFactory.Flush(); lastCombinedProperties = target.LastCombinedProperties; Assert.Single(lastCombinedProperties); Assert.Contains(new KeyValuePair<string, object>("name", "Cartman"), lastCombinedProperties); } [Fact] public void TargetWithContextAsyncBufferScopePropertyTest() { var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterTarget<CustomTargetWithContext>("contexttarget")) .LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <default-wrapper type='AsyncWrapper' timeToSleepBetweenBatches='0' overflowAction='Block' /> <target name='debug_buffer' type='BufferingWrapper'> <target name='debug' type='contexttarget' includeCallSite='true' includeScopeProperties='true' excludeProperties='password' /> </target> </targets> <rules> <logger name='*' levels='Error' writeTo='debug_buffer' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); var target = logFactory.Configuration.AllTargets.OfType<CustomTargetWithContext>().FirstOrDefault(); using (logger.PushScopeProperty("name", "Kenny")) using (logger.PushScopeProperty("password", "<PASSWORD>")) { logger.Error("Hello"); } logFactory.Flush(); Assert.NotEqual(0, target.LastMessage.Length); var lastCombinedProperties = target.LastCombinedProperties; Assert.Single(lastCombinedProperties); Assert.Contains(new KeyValuePair<string, object>("name", "Kenny"), lastCombinedProperties); } [Fact] public void TargetWithContextJsonTest() { var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterTarget<CustomTargetWithContext>("contexttarget")) .LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <default-wrapper type='AsyncWrapper' timeToSleepBetweenBatches='0' overflowAction='Block' /> <target name='debug' type='contexttarget' includeCallSite='true'> <layout type='JsonLayout' includeScopeProperties='true'> <attribute name='level' layout='${level:upperCase=true}'/> <attribute name='message' layout='${message}' /> <attribute name='exception' layout='${exception}' /> <attribute name='threadid' layout='${threadid}' /> </layout> </target> </targets> <rules> <logger name='*' levels='Error' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); ScopeContext.Clear(); ScopeContext.PushProperty("TestKey", "Hello Thread World"); logger.Error("log message"); var target = logFactory.Configuration.AllTargets.OfType<CustomTargetWithContext>().FirstOrDefault(); System.Threading.Thread.Sleep(1); for (int i = 0; i < 1000; ++i) { if (target.LastMessage != null) break; System.Threading.Thread.Sleep(1); } Assert.NotEqual(0, target.LastMessage.Length); Assert.Contains(System.Environment.CurrentManagedThreadId.ToString(), target.LastMessage); var lastCombinedProperties = target.LastCombinedProperties; Assert.Empty(lastCombinedProperties); } [Fact] public void TargetWithContextPropertyTypeTest() { var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterTarget<CustomTargetWithContext>("contexttarget")) .LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <default-wrapper type='AsyncWrapper' timeToSleepBetweenBatches='0' overflowAction='Block' /> <target name='debug' type='contexttarget' includeCallSite='true'> <contextproperty name='threadid' layout='${threadid}' propertyType='System.Int32' /> <contextproperty name='processid' layout='${processid}' propertyType='System.Int32' /> <contextproperty name='timestamp' layout='${date}' propertyType='System.DateTime' /> <contextproperty name='int-non-existing' layout='${event-properties:non-existing}' propertyType='System.Int32' includeEmptyValue='true' /> <contextproperty name='int-non-existing-empty' layout='${event-properties:non-existing}' propertyType='System.Int32' includeEmptyValue='false' /> <contextproperty name='object-non-existing' layout='${event-properties:non-existing}' propertyType='System.Object' includeEmptyValue='true' /> <contextproperty name='object-non-existing-empty' layout='${event-properties:non-existing}' propertyType='System.Object' includeEmptyValue='false' /> </target> </targets> <rules> <logger name='*' levels='Error' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); ScopeContext.Clear(); var logEvent = new LogEventInfo() { Message = "log message" }; logger.Error(logEvent); logFactory.Flush(); var target = logFactory.Configuration.AllTargets.OfType<CustomTargetWithContext>().FirstOrDefault(); Assert.NotEqual(0, target.LastMessage.Length); var lastCombinedProperties = target.LastCombinedProperties; Assert.NotEmpty(lastCombinedProperties); Assert.Contains(new KeyValuePair<string, object>("threadid", System.Environment.CurrentManagedThreadId), lastCombinedProperties); Assert.Contains(new KeyValuePair<string, object>("processid", System.Diagnostics.Process.GetCurrentProcess().Id), lastCombinedProperties); Assert.Contains(new KeyValuePair<string, object>("int-non-existing", 0), lastCombinedProperties); Assert.DoesNotContain("int-non-existing-empty", lastCombinedProperties.Keys); Assert.Contains(new KeyValuePair<string, object>("object-non-existing", ""), lastCombinedProperties); Assert.DoesNotContain("object-non-existing-empty", lastCombinedProperties.Keys); } } } <file_sep>using NLog; using NLog.Targets; class Example { static void Main(string[] args) { DatabaseTarget target = new DatabaseTarget(); DatabaseParameterInfo param; target.DBProvider = "mssql"; target.DBHost = "."; target.DBUserName = "nloguser"; target.DBPassword = "<PASSWORD>"; target.DBDatabase = "databasename"; target.CommandText = "insert into LogTable(time_stamp,level,logger,message) values(@time_stamp, @level, @logger, @message);"; param = new DatabaseParameterInfo(); param.Name = "@time_stamp"; param.Layout = "${date}"; target.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@level"; param.Layout = "${level}"; target.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@logger"; param.Layout = "${logger}"; target.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@message"; param.Layout = "${message}"; target.Parameters.Add(param); NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); } } <file_sep>using NLog; using NLog.Config; using NLog.Win32.Targets; class Example { static void Main(string[] args) { NLog.Internal.InternalLogger.LogToConsole = true; MSMQTarget target = new MSMQTarget(); target.Queue = ".\\private$\\nlog"; target.Label = "${message}"; target.Layout = "${message}"; target.CreateQueueIfNotExists = true; target.Recoverable = true; SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace); Logger l = LogManager.GetLogger("AAA"); l.Error("This is an error. It goes to .\\private$\\nlog queue."); l.Debug("This is a debug information. It goes to .\\private$\\nlog queue."); l.Info("This is a information. It goes to .\\private$\\nlog queue."); l.Warn("This is a warn information. It goes to .\\private$\\nlog queue."); l.Fatal("This is a fatal information. It goes to .\\private$\\nlog queue."); l.Trace("This is a trace information. It goes to .\\private$\\nlog queue."); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Threading; using NLog.Common; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class LimitingTargetWrapperTests : NLogTestBase { [Fact] public void WriteMoreMessagesThanLimitOnlyWritesLimitMessages() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <wrapper-target name='limiting' type='LimitingWrapper' messagelimit='5'> <target name='debug' type='Debug' layout='${message}' /> </wrapper-target> </targets> <rules> <logger name='*' level='Debug' writeTo='limiting' /> </rules> </nlog>").LogFactory; const int messagelimit = 5; var logger = logFactory.GetLogger("A"); for (int i = 1; i <= 10; i++) { logger.Debug("message {0}", i); //Should have only written 5 messages, since limit is 5. if (i <= messagelimit) logFactory.AssertDebugLastMessage($"message {i}"); } logFactory.AssertDebugLastMessage("debug", $"message {messagelimit}"); } [Fact] public void WriteMessagesAfterLimitExpiredWritesMessages() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <wrapper-target name='limiting' type='LimitingWrapper' messagelimit='5' interval='0:0:0:0.100'> <target name='debug' type='Debug' layout='${message}' /> </wrapper-target> </targets> <rules> <logger name='*' level='Debug' writeTo='limiting' /> </rules> </nlog>").LogFactory; const int messagelimit = 5; var logger = logFactory.GetLogger("A"); for (int i = 1; i <= 10; i++) { logger.Debug("message {0}", i); if (i <= messagelimit) logFactory.AssertDebugLastMessage($"message {i}"); } //Wait for the interval to expire. Thread.Sleep(100); for (int i = 1; i <= 10; i++) { logger.Debug("message {0}", i + 10); if (i <= messagelimit) logFactory.AssertDebugLastMessage($"message {i + 10}"); } //Should have written 10 messages. //5 from the first interval and 5 from the second. logFactory.AssertDebugLastMessage("debug", "message 15"); } [Fact] public void WriteMessagesLessThanMessageLimitWritesToWrappedTarget() { MyTarget wrappedTarget = new MyTarget(); LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget, 5, TimeSpan.FromMilliseconds(100)); InitializeTargets(wrappedTarget, wrapper); // Write limit number of messages should just write them to the wrappedTarget. WriteNumberAsyncLogEventsStartingAt(0, 5, wrapper); Assert.Equal(5, wrappedTarget.WriteCount); //Let the interval expire to start a new one. Thread.Sleep(100); // Write limit number of messages should just write them to the wrappedTarget. var lastException = WriteNumberAsyncLogEventsStartingAt(5, 5, wrapper); // We should have 10 messages (5 from first interval, 5 from second interval). Assert.Equal(10, wrappedTarget.WriteCount); Assert.Null(lastException); } [Fact] public void WriteMoreMessagesThanMessageLimitDiscardsExcessMessages() { MyTarget wrappedTarget = new MyTarget(); LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget, 5, TimeSpan.FromHours(1)); InitializeTargets(wrappedTarget, wrapper); // Write limit number of messages should just write them to the wrappedTarget. var lastException = WriteNumberAsyncLogEventsStartingAt(0, 5, wrapper); Assert.Equal(5, wrappedTarget.WriteCount); //Additional messages will be discarded, but InternalLogger will write to trace. string internalLog = RunAndCaptureInternalLog(() => { wrapper.WriteAsyncLogEvent( new LogEventInfo(LogLevel.Debug, "test", $"Hello {5}").WithContinuation(ex => lastException = ex)); }, LogLevel.Trace); Assert.Equal(5, wrappedTarget.WriteCount); Assert.Contains("MessageLimit", internalLog); Assert.Null(lastException); } [Fact] public void WriteMessageAfterIntervalHasExpiredStartsNewInterval() { MyTarget wrappedTarget = new MyTarget(); LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget, 5, TimeSpan.FromMilliseconds(100)); InitializeTargets(wrappedTarget, wrapper); Exception lastException = null; wrapper.WriteAsyncLogEvent( new LogEventInfo(LogLevel.Debug, "test", "first interval").WithContinuation(ex => lastException = ex)); //Let the interval expire. Thread.Sleep(100); //Writing a logEvent should start a new Interval. This should be written to InternalLogger.Debug. string internalLog = RunAndCaptureInternalLog(() => { // We can write 5 messages again since a new interval started. lastException = WriteNumberAsyncLogEventsStartingAt(0, 5, wrapper); }, LogLevel.Trace); //We should have written 6 messages (1 in first interval and 5 in second interval). Assert.Equal(6, wrappedTarget.WriteCount); Assert.Contains("New interval", internalLog); Assert.Null(lastException); } [Fact] public void TestWritingMessagesOverMultipleIntervals() { MyTarget wrappedTarget = new MyTarget(); LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget, 5, TimeSpan.FromMilliseconds(100)); InitializeTargets(wrappedTarget, wrapper); Exception lastException = null; lastException = WriteNumberAsyncLogEventsStartingAt(0, 10, wrapper); //Let the interval expire. Thread.Sleep(100); Assert.Equal(5, wrappedTarget.WriteCount); Assert.Equal("Hello 4", wrappedTarget.LastWrittenMessage); Assert.Null(lastException); lastException = WriteNumberAsyncLogEventsStartingAt(10, 10, wrapper); //We should have 10 messages (5 from first, 5 from second interval). Assert.Equal(10, wrappedTarget.WriteCount); Assert.Equal("Hello 14", wrappedTarget.LastWrittenMessage); Assert.Null(lastException); //Let the interval expire. Thread.Sleep(230); lastException = WriteNumberAsyncLogEventsStartingAt(20, 10, wrapper); //We should have 15 messages (5 from first, 5 from second, 5 from third interval). Assert.Equal(15, wrappedTarget.WriteCount); Assert.Equal("Hello 24", wrappedTarget.LastWrittenMessage); Assert.Null(lastException); //Let the interval expire. Thread.Sleep(20); lastException = WriteNumberAsyncLogEventsStartingAt(30, 10, wrapper); //No more messages should be been written, since we are still in the third interval. Assert.Equal(15, wrappedTarget.WriteCount); Assert.Equal("Hello 24", wrappedTarget.LastWrittenMessage); Assert.Null(lastException); } [Fact] public void ConstructorWithNoParametersInitialisesDefaultsCorrectly() { LimitingTargetWrapper wrapper = new LimitingTargetWrapper(); Assert.Equal(1000, wrapper.MessageLimit); Assert.Equal(TimeSpan.FromHours(1), wrapper.Interval); } [Fact] public void ConstructorWithTargetInitialisesDefaultsCorrectly() { MyTarget wrappedTarget = new MyTarget(); LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget); Assert.Equal(1000, wrapper.MessageLimit); Assert.Equal(TimeSpan.FromHours(1), wrapper.Interval); } [Fact] public void ConstructorWithNameInitialisesDefaultsCorrectly() { MyTarget wrappedTarget = new MyTarget(); LimitingTargetWrapper wrapper = new LimitingTargetWrapper("Wrapper", wrappedTarget); Assert.Equal(1000, wrapper.MessageLimit); Assert.Equal(TimeSpan.FromHours(1), wrapper.Interval); } [Fact] public void InitializeThrowsNLogConfigurationExceptionIfMessageLimitIsSetToZero() { MyTarget wrappedTarget = new MyTarget(); LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget) {MessageLimit = 0}; wrappedTarget.Initialize(null); LogManager.ThrowConfigExceptions = true; Assert.Throws<NLogConfigurationException>(() => wrapper.Initialize(null)); LogManager.ThrowConfigExceptions = false; } [Fact] public void InitializeThrowsNLogConfigurationExceptionIfMessageLimitIsSmallerZero() { MyTarget wrappedTarget = new MyTarget(); LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget) {MessageLimit = -1}; wrappedTarget.Initialize(null); LogManager.ThrowConfigExceptions = true; Assert.Throws<NLogConfigurationException>(() => wrapper.Initialize(null)); LogManager.ThrowConfigExceptions = false; } [Fact] public void InitializeThrowsNLogConfigurationExceptionIfIntervalIsSmallerZero() { MyTarget wrappedTarget = new MyTarget(); LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget) {Interval = TimeSpan.MinValue}; wrappedTarget.Initialize(null); LogManager.ThrowConfigExceptions = true; Assert.Throws<NLogConfigurationException>(() => wrapper.Initialize(null)); LogManager.ThrowConfigExceptions = false; } [Fact] public void InitializeThrowsNLogConfigurationExceptionIfIntervalIsZero() { MyTarget wrappedTarget = new MyTarget(); LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget) {Interval = TimeSpan.Zero}; wrappedTarget.Initialize(null); LogManager.ThrowConfigExceptions = true; Assert.Throws<NLogConfigurationException>(() => wrapper.Initialize(null)); LogManager.ThrowConfigExceptions = false; } [Fact] public void CreatingFromConfigSetsMessageLimitCorrectly() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <wrapper-target name='limiting' type='LimitingWrapper' messagelimit='50'> <target name='debug' type='Debug' layout='${message}' /> </wrapper-target> </targets> <rules> <logger name='*' level='Debug' writeTo='limiting' /> </rules> </nlog>").LogFactory; LimitingTargetWrapper limitingWrapper = logFactory.Configuration.FindTargetByName<LimitingTargetWrapper>("limiting"); DebugTarget debugTarget = logFactory.Configuration.FindTargetByName<DebugTarget>("debug"); Assert.NotNull(limitingWrapper); Assert.NotNull(debugTarget); Assert.Equal(50, limitingWrapper.MessageLimit); Assert.Equal(TimeSpan.FromHours(1), limitingWrapper.Interval); var logger = logFactory.GetLogger("A"); logger.Debug("a"); logFactory.AssertDebugLastMessage("a"); } [Fact] public void CreatingFromConfigSetsIntervalCorrectly() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <wrapper-target name='limiting' type='LimitingWrapper' interval='1:2:5:00'> <target name='debug' type='Debug' layout='${message}' /> </wrapper-target> </targets> <rules> <logger name='*' level='Debug' writeTo='limiting' /> </rules> </nlog>").LogFactory; LimitingTargetWrapper limitingWrapper = logFactory.Configuration.FindTargetByName<LimitingTargetWrapper>("limiting"); DebugTarget debugTarget = logFactory.Configuration.FindTargetByName<DebugTarget>("debug"); Assert.NotNull(limitingWrapper); Assert.NotNull(debugTarget); Assert.Equal(1000, limitingWrapper.MessageLimit); Assert.Equal(TimeSpan.FromDays(1)+TimeSpan.FromHours(2)+TimeSpan.FromMinutes(5), limitingWrapper.Interval); var logger = logFactory.GetLogger("A"); logger.Debug("a"); logFactory.AssertDebugLastMessage("a"); } private static void InitializeTargets(params Target[] targets) { foreach (Target target in targets) { target.Initialize(null); } } private static Exception WriteNumberAsyncLogEventsStartingAt(int startIndex, int count, WrapperTargetBase wrapper) { Exception lastException = null; for (int i = startIndex; i < startIndex + count; i++) { wrapper.WriteAsyncLogEvent( new LogEventInfo(LogLevel.Debug, "test", $"Hello {i}").WithContinuation(ex => lastException = ex)); } return lastException; } private class MyTarget : Target { public int WriteCount { get; private set; } public string LastWrittenMessage { get; private set; } protected override void Write(AsyncLogEventInfo logEvent) { base.Write(logEvent); LastWrittenMessage = logEvent.LogEvent.FormattedMessage; WriteCount++; } } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LayoutRenderers.Wrappers { using System; using NLog; using NLog.Layouts; using Xunit; public class WhenTests : NLogTestBase { [Fact] public void PositiveWhenTest() { SimpleLayout l = @"${message:when=logger=='logger'}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("message", l.Render(le)); } [Fact] public void NegativeWhenTest() { SimpleLayout l = @"${message:when=logger=='logger'}"; var le = LogEventInfo.Create(LogLevel.Info, "logger2", "message"); Assert.Equal("", l.Render(le)); } [Fact] public void ComplexWhenTest() { // condition is pretty complex here and includes nested layout renderers // we are testing here that layout parsers property invokes Condition parser to consume the right number of characters SimpleLayout l = @"${message:when='${pad:${logger}:padding=10:padCharacter=X}'=='XXXXlogger':padding=-10:padCharacter=Y}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("messageYYY", l.Render(le)); } [Fact] public void ComplexWhenTest2() { // condition is pretty complex here and includes nested layout renderers // we are testing here that layout parsers property invokes Condition parser to consume the right number of characters SimpleLayout l = @"${message:padding=-10:padCharacter=Y:when='${pad:${logger}:padding=10:padCharacter=X}'=='XXXXlogger'}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("messageYYY", l.Render(le)); } [Fact] public void WhenElseCase() { //else cannot be invoked ambiently. First param is inner SimpleLayout l = @"${when:good:when=logger=='logger':else=better}"; { var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("good", l.Render(le)); } { var le = LogEventInfo.Create(LogLevel.Info, "logger1", "message"); Assert.Equal("better", l.Render(le)); } } [Fact] public void WhenElseCase_empty_when() { using (new NoThrowNLogExceptions()) { //else cannot be invoked ambiently. First param is inner SimpleLayout l = @"${when:good:else=better}"; { var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("good", l.Render(le)); } { var le = LogEventInfo.Create(LogLevel.Info, "logger1", "message"); Assert.Equal("good", l.Render(le)); } } } [Fact] public void WhenElseCase_noIf() { //else cannot be invoked ambiently. First param is inner SimpleLayout l = @"${when:when=logger=='logger':else=better}"; { var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("", l.Render(le)); } { var le = LogEventInfo.Create(LogLevel.Info, "logger1", "message"); Assert.Equal("better", l.Render(le)); } } [Fact] public void WhenLogLevelConditionTestLayoutRenderer() { //else cannot be invoked ambiently. First param is inner SimpleLayout l = @"${when:when=level<=LogLevel.Info:inner=Good:else=Bad}"; { var le = LogEventInfo.Create(LogLevel.Debug, "logger", "message"); Assert.Equal("Good", l.Render(le)); } { var le = LogEventInfo.Create(LogLevel.Error, "logger1", "message"); Assert.Equal("Bad", l.Render(le)); } } [Fact] public void WhenLogLevelConditionTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets><target name='debug' type='Debug' layout='${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug'> <filters> <when condition=""level>=LogLevel.Info"" action=""Log""></when> <when condition='true' action='Ignore' /> </filters> </logger> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Fatal("Test"); logFactory.AssertDebugLastMessage("Fatal Test"); logger.Error("Test"); logFactory.AssertDebugLastMessage("Error Test"); logger.Warn("Test"); logFactory.AssertDebugLastMessage("Warn Test"); logger.Info("Test"); logFactory.AssertDebugLastMessage("Info Test"); logger.Debug("Test"); logFactory.AssertDebugLastMessage("Info Test"); logger.Trace("Test"); logFactory.AssertDebugLastMessage("Info Test"); } [Fact] public void WhenNumericAndPropertyConditionTest() { //else cannot be invoked ambiently. First param is inner SimpleLayout l = @"${when:when=100 < '${event-properties:item=Elapsed}':inner=Slow:else=Fast}"; // WhenNumericAndPropertyConditionTest_inner(l, "a", false); WhenNumericAndPropertyConditionTest_inner(l, 101, false); WhenNumericAndPropertyConditionTest_inner(l, 11, true); WhenNumericAndPropertyConditionTest_inner(l, 100, true); WhenNumericAndPropertyConditionTest_inner(l, 1, true); WhenNumericAndPropertyConditionTest_inner(l, 2, true); WhenNumericAndPropertyConditionTest_inner(l, 20, true); WhenNumericAndPropertyConditionTest_inner(l, 100000, false); } private static void WhenNumericAndPropertyConditionTest_inner(SimpleLayout l, object time, bool fast) { var le = LogEventInfo.Create(LogLevel.Debug, "logger", "message"); le.Properties["Elapsed"] = time; Assert.Equal(fast ? "Fast" : "Slow", l.Render(le)); } [Theory] [InlineData("logger", "DBNullValue", true)] [InlineData("logger1", null, false)] public void WhenDbNullRawValueShouldWork(string loggername, object expectedValue, bool expectedSuccess) { expectedValue = OptionalConvert(expectedValue); //else cannot be invoked ambiently. First param is inner SimpleLayout l = @"${when:${db-null}:when=logger=='logger':else=better}"; var le = LogEventInfo.Create(LogLevel.Info, loggername, "message"); var success = l.TryGetRawValue(le, out var result); Assert.Equal(expectedValue, result); Assert.Equal(expectedSuccess, success); } [Theory] [InlineData("logger1", "DBNullValue", true)] [InlineData("logger", null, false)] public void WhenDbNullRawValueShouldWorkElse(string loggername, object expectedValue, bool expectedSuccess) { expectedValue = OptionalConvert(expectedValue); //else cannot be invoked ambiently. First param is inner SimpleLayout l = @"${when:something:when=logger=='logger':else=${db-null}}"; var le = LogEventInfo.Create(LogLevel.Info, loggername, "message"); var success = l.TryGetRawValue(le, out var result); Assert.Equal(expectedValue, result); Assert.Equal(expectedSuccess, success); } private static object OptionalConvert(object expectedValue) { if (expectedValue is string s && s == "DBNullValue") { expectedValue = DBNull.Value; } return expectedValue; } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 && !NETSTANDARD1_5 namespace NLog.Internal { using System; using System.Net; using System.Net.Mail; /// <summary> /// Supports mocking of SMTP Client code. /// </summary> internal interface ISmtpClient : IDisposable { /// <summary> /// Specifies how outgoing email messages will be handled. /// </summary> SmtpDeliveryMethod DeliveryMethod { get; set; } /// <summary> /// Gets or sets the name or IP address of the host used for SMTP transactions. /// </summary> string Host { get; set; } /// <summary> /// Gets or sets the port used for SMTP transactions. /// </summary> int Port { get; set; } /// <summary> /// Gets or sets a value that specifies the amount of time after which a synchronous <see cref="Send">Send</see> call times out. /// </summary> int Timeout { get; set; } /// <summary> /// Gets or sets the credentials used to authenticate the sender. /// </summary> ICredentialsByHost Credentials { get; set; } bool EnableSsl { get; set; } /// <summary> /// Sends an e-mail message to an SMTP server for delivery. These methods block while the message is being transmitted. /// </summary> /// <param name="msg"> /// <typeparam>System.Net.Mail.MailMessage /// <name>MailMessage</name> /// </typeparam> A <see cref="MailMessage">MailMessage</see> that contains the message to send.</param> void Send(MailMessage msg); /// <summary> /// Gets or sets the folder where applications save mail messages to be processed by the local SMTP server. /// </summary> string PickupDirectoryLocation { get; set; } } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Collections.Generic; using System.Text; using Microsoft.Win32; using NLog.Common; using NLog.Config; using NLog.Layouts; /// <summary> /// A value from the Registry. /// </summary> [LayoutRenderer("registry")] public class RegistryLayoutRenderer : LayoutRenderer { /// <summary> /// Gets or sets the registry value name. /// </summary> /// <docgen category='Registry Options' order='10' /> public Layout Value { get; set; } /// <summary> /// Gets or sets the value to be output when the specified registry key or value is not found. /// </summary> /// <docgen category='Registry Options' order='10' /> public Layout DefaultValue { get; set; } /// <summary> /// Require escaping backward slashes in <see cref="DefaultValue"/>. Need to be backwards-compatible. /// /// When true: /// /// `\` in value should be configured as `\\` /// `\\` in value should be configured as `\\\\`. /// </summary> /// <remarks>Default value wasn't a Layout before and needed an escape of the slash</remarks> /// <docgen category='Registry Options' order='50' /> public bool RequireEscapingSlashesInDefaultValue { get; set; } = true; #if !NET35 /// <summary> /// Gets or sets the registry view (see: https://msdn.microsoft.com/de-de/library/microsoft.win32.registryview.aspx). /// Allowed values: Registry32, Registry64, Default /// </summary> /// <docgen category='Registry Options' order='10' /> public RegistryView View { get; set; } = RegistryView.Default; #endif /// <summary> /// Gets or sets the registry key. /// </summary> /// <example> /// HKCU\Software\NLogTest /// </example> /// <remarks> /// Possible keys: /// <ul> ///<li>HKEY_LOCAL_MACHINE</li> ///<li>HKLM</li> ///<li>HKEY_CURRENT_USER</li> ///<li>HKCU</li> ///<li>HKEY_CLASSES_ROOT</li> ///<li>HKEY_USERS</li> ///<li>HKEY_CURRENT_CONFIG</li> ///<li>HKEY_DYN_DATA</li> ///<li>HKEY_PERFORMANCE_DATA</li> /// </ul> /// </remarks> /// <docgen category='Registry Options' order='10' /> [RequiredParameter] public Layout Key { get; set; } /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { object registryValue = null; // Value = null is necessary for querying "unnamed values" string renderedValue = Value?.Render(logEvent); var parseResult = ParseKey(Key.Render(logEvent)); try { #if !NET35 using (RegistryKey rootKey = RegistryKey.OpenBaseKey(parseResult.Hive, View)) #else var rootKey = MapHiveToKey(parseResult.Hive); #endif { if (parseResult.HasSubKey) { using (RegistryKey registryKey = rootKey.OpenSubKey(parseResult.SubKey)) { if (registryKey != null) registryValue = registryKey.GetValue(renderedValue); } } else { registryValue = rootKey.GetValue(renderedValue); } } } catch (Exception ex) { if (LogManager.ThrowExceptions) throw; InternalLogger.Error(ex, "Error when reading from registry"); } string value = null; if (registryValue != null) // valid value returned from registry will never be null { value = Convert.ToString(registryValue, System.Globalization.CultureInfo.InvariantCulture); } else if (DefaultValue != null) { value = DefaultValue.Render(logEvent); if (RequireEscapingSlashesInDefaultValue) { //remove escape slash value = value.Replace("\\\\", "\\"); } } builder.Append(value); } private sealed class ParseResult { public string SubKey { get; set; } public RegistryHive Hive { get; set; } /// <summary> /// Has <see cref="SubKey"/>? /// </summary> public bool HasSubKey => !string.IsNullOrEmpty(SubKey); } /// <summary> /// Parse key to <see cref="RegistryHive"/> and subkey. /// </summary> /// <param name="key">full registry key name</param> /// <returns>Result of parsing, never <c>null</c>.</returns> private static ParseResult ParseKey(string key) { string hiveName; int pos = key.IndexOfAny(new char[] { '\\', '/' }); string subkey = null; if (pos >= 0) { hiveName = key.Substring(0, pos); //normalize slashes subkey = key.Substring(pos + 1).Replace('/', '\\'); //remove starting slashes subkey = subkey.TrimStart('\\'); //replace double slashes from pre-layout times subkey = subkey.Replace("\\\\", "\\"); } else { hiveName = key; } var hive = ParseHiveName(hiveName); return new ParseResult { SubKey = subkey, Hive = hive, }; } /// <summary> /// Aliases for the hives. See https://msdn.microsoft.com/en-us/library/ctb3kd86(v=vs.110).aspx /// </summary> private static readonly Dictionary<string, RegistryHive> HiveAliases = new Dictionary<string, RegistryHive>(StringComparer.OrdinalIgnoreCase) { {"HKEY_LOCAL_MACHINE", RegistryHive.LocalMachine}, {"HKLM", RegistryHive.LocalMachine}, {"HKEY_CURRENT_USER", RegistryHive.CurrentUser}, {"HKCU", RegistryHive.CurrentUser}, {"HKEY_CLASSES_ROOT", RegistryHive.ClassesRoot}, {"HKEY_USERS", RegistryHive.Users}, {"HKEY_CURRENT_CONFIG", RegistryHive.CurrentConfig}, #if !NETSTANDARD {"HKEY_DYN_DATA", RegistryHive.DynData}, #endif {"HKEY_PERFORMANCE_DATA", RegistryHive.PerformanceData}, }; private static RegistryHive ParseHiveName(string hiveName) { RegistryHive hive; if (HiveAliases.TryGetValue(hiveName, out hive)) { return hive; } //ArgumentException is consistent throw new ArgumentException($"Key name is not supported. Root hive '{hiveName}' not recognized."); } #if NET35 private static RegistryKey MapHiveToKey(RegistryHive hive) { switch (hive) { case RegistryHive.LocalMachine: return Registry.LocalMachine; case RegistryHive.CurrentUser: return Registry.CurrentUser; default: throw new ArgumentException("Only RegistryHive.LocalMachine and RegistryHive.CurrentUser are supported.", nameof(hive)); } } #endif } } <file_sep># API docs generation Generated docs for https://nlog-project.org/documentation/ ## How to run 1. Perhaps update the year. Search for `2004-` for in [NLog.shfbproj](NLog.shfbproj). 2. Run [BuildDoc.cmd](BuildDoc.cmd) 3. Copy the Doc folder to the documentation folder of nlog.github.io 4. Remove unneeded files: .config, .aspx. .php, WebKI.xml, WebTOC.xml and LastBuild.log <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using JetBrains.Annotations; namespace NLog.Internal { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; /// <summary> /// Reflection helpers. /// </summary> internal static class ReflectionHelpers { /// <summary> /// Is this a static class? /// </summary> /// <param name="type"></param> /// <returns></returns> /// <remarks>This is a work around, as Type doesn't have this property. /// From: https://stackoverflow.com/questions/1175888/determine-if-a-type-is-static /// </remarks> public static bool IsStaticClass(this Type type) { return type.IsClass() && type.IsAbstract() && type.IsSealed(); } /// <summary> /// Optimized delegate for calling MethodInfo /// </summary> /// <param name="target">Object instance, use null for static methods.</param> /// <param name="arguments">Complete list of parameters that matches the method, including optional/default parameters.</param> public delegate object LateBoundMethod(object target, object[] arguments); /// <summary> /// Optimized delegate for calling a constructor /// </summary> /// <param name="arguments">Complete list of parameters that matches the constructor, including optional/default parameters. Could be null for no parameters.</param> public delegate object LateBoundConstructor([CanBeNull] object[] arguments); /// <summary> /// Creates an optimized delegate for calling the MethodInfo using Expression-Trees /// </summary> /// <param name="methodInfo">Method to optimize</param> /// <returns>Optimized delegate for invoking the MethodInfo</returns> public static LateBoundMethod CreateLateBoundMethod(MethodInfo methodInfo) { var instanceParameter = Expression.Parameter(typeof(object), "instance"); var parametersParameter = Expression.Parameter(typeof(object[]), "parameters"); var parameterExpressions = BuildParameterList(methodInfo, parametersParameter); var methodCall = BuildMethodCall(methodInfo, instanceParameter, parameterExpressions); // ((TInstance)instance).Method((T0)parameters[0], (T1)parameters[1], ...) if (methodCall.Type == typeof(void)) { var lambda = Expression.Lambda<Action<object, object[]>>( methodCall, instanceParameter, parametersParameter); Action<object, object[]> execute = lambda.Compile(); return (instance, parameters) => { execute(instance, parameters); return null; // There is no return-type, so we return null-object }; } else { var castMethodCall = Expression.Convert(methodCall, typeof(object)); var lambda = Expression.Lambda<LateBoundMethod>( castMethodCall, instanceParameter, parametersParameter); return lambda.Compile(); } } /// <summary> /// Creates an optimized delegate for calling the constructors using Expression-Trees /// </summary> /// <param name="constructor">Constructor to optimize</param> /// <returns>Optimized delegate for invoking the constructor</returns> public static LateBoundConstructor CreateLateBoundConstructor(ConstructorInfo constructor) { var parametersParameter = Expression.Parameter(typeof(object[]), "parameters"); // build parameter list var parameterExpressions = BuildParameterList(constructor, parametersParameter); var ctorCall = Expression.New(constructor, parameterExpressions); var lambda = Expression.Lambda<LateBoundConstructor>(ctorCall, parametersParameter); return lambda.Compile(); } private static IEnumerable<Expression> BuildParameterList(MethodBase methodInfo, ParameterExpression parametersParameter) { var parameterExpressions = new List<Expression>(); var paramInfos = methodInfo.GetParameters(); for (int i = 0; i < paramInfos.Length; i++) { // (Ti)parameters[i] var valueObj = Expression.ArrayIndex(parametersParameter, Expression.Constant(i)); var valueCast = CreateParameterExpression(paramInfos[i], valueObj); parameterExpressions.Add(valueCast); } return parameterExpressions; } private static MethodCallExpression BuildMethodCall(MethodInfo methodInfo, ParameterExpression instanceParameter, IEnumerable<Expression> parameterExpressions) { // non-instance for static method, or ((TInstance)instance) var instanceCast = methodInfo.IsStatic ? null : Expression.Convert(instanceParameter, methodInfo.DeclaringType); // static invoke or ((TInstance)instance).Method var methodCall = Expression.Call(instanceCast, methodInfo, parameterExpressions); return methodCall; } private static UnaryExpression CreateParameterExpression(ParameterInfo parameterInfo, Expression expression) { Type parameterType = parameterInfo.ParameterType; if (parameterType.IsByRef) parameterType = parameterType.GetElementType(); var valueCast = Expression.Convert(expression, parameterType); return valueCast; } public static bool IsPublic(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.IsPublic; #else return type.GetTypeInfo().IsPublic; #endif } public static bool IsEnum(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.IsEnum; #else return type.GetTypeInfo().IsEnum; #endif } public static bool IsPrimitive(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.IsPrimitive; #else return type.GetTypeInfo().IsPrimitive; #endif } public static bool IsValueType(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.IsValueType; #else return type.GetTypeInfo().IsValueType; #endif } public static bool IsSealed(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.IsSealed; #else return type.GetTypeInfo().IsSealed; #endif } public static bool IsAbstract(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.IsAbstract; #else return type.GetTypeInfo().IsAbstract; #endif } public static bool IsClass(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.IsClass; #else return type.GetTypeInfo().IsClass; #endif } public static bool IsGenericType(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.IsGenericType; #else return type.GetTypeInfo().IsGenericType; #endif } [CanBeNull] public static TAttr GetFirstCustomAttribute<TAttr>(this Type type) where TAttr : Attribute { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return Attribute.GetCustomAttributes(type, typeof(TAttr)).FirstOrDefault() as TAttr; #else var typeInfo = type.GetTypeInfo(); return typeInfo.GetCustomAttributes<TAttr>().FirstOrDefault(); #endif } [CanBeNull] public static TAttr GetFirstCustomAttribute<TAttr>(this PropertyInfo info) where TAttr : Attribute { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return Attribute.GetCustomAttributes(info, typeof(TAttr)).FirstOrDefault() as TAttr; #else return info.GetCustomAttributes(typeof(TAttr), false).FirstOrDefault() as TAttr; #endif } [CanBeNull] public static TAttr GetFirstCustomAttribute<TAttr>(this Assembly assembly) where TAttr : Attribute { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return Attribute.GetCustomAttributes(assembly, typeof(TAttr)).FirstOrDefault() as TAttr; #else return assembly.GetCustomAttributes(typeof(TAttr)).FirstOrDefault() as TAttr; #endif } public static IEnumerable<TAttr> GetCustomAttributes<TAttr>(this Type type, bool inherit) where TAttr : Attribute { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return (TAttr[])type.GetCustomAttributes(typeof(TAttr), inherit); #else return type.GetTypeInfo().GetCustomAttributes<TAttr>(inherit); #endif } public static Assembly GetAssembly(this Type type) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return type.Assembly; #else var typeInfo = type.GetTypeInfo(); return typeInfo.Assembly; #endif } public static bool IsValidPublicProperty(this PropertyInfo p) { return p != null && p.CanRead && p.GetIndexParameters().Length == 0 && p.GetGetMethod() != null; } public static object GetPropertyValue(this PropertyInfo p, object instance) { #if !NET35 && !NET40 return p.GetValue(instance); #else return p.GetGetMethod().Invoke(instance, null); #endif } public static MethodInfo GetDelegateInfo(this Delegate method) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return method.Method; #else return System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(method); #endif } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal.FileAppenders { using Targets; /// <summary> /// Interface that provides parameters for create file function. /// </summary> internal interface ICreateFileParameters { /// <summary> /// Gets or sets the delay in milliseconds to wait before attempting to write to the file again. /// </summary> int FileOpenRetryCount { get; } /// <summary> /// Gets or sets the number of times the write is appended on the file before NLog /// discards the log message. /// </summary> int FileOpenRetryDelay { get; } /// <summary> /// Gets or sets a value indicating whether concurrent writes to the log file by multiple processes on the same host. /// </summary> /// <remarks> /// This makes multi-process logging possible. NLog uses a special technique /// that lets it keep the files open for writing. /// </remarks> bool ConcurrentWrites { get; } /// <summary> /// Gets or sets a value indicating whether to create directories if they do not exist. /// </summary> /// <remarks> /// Setting this to false may improve performance a bit, but you'll receive an error /// when attempting to write to a directory that's not present. /// </remarks> bool CreateDirs { get; } /// <summary> /// Gets or sets a value indicating whether to enable log file(s) to be deleted. /// </summary> bool EnableFileDelete { get; } /// <summary> /// Gets or sets the log file buffer size in bytes. /// </summary> int BufferSize { get; } /// <summary> /// Gets or set a value indicating whether a managed file stream is forced, instead of using the native implementation. /// </summary> bool ForceManaged { get; } /// <summary> /// Gets or sets the file attributes (Windows only). /// </summary> Win32FileAttributes FileAttributes { get; } /// <summary> /// Should archive mutex be created? /// </summary> bool IsArchivingEnabled { get; } /// <summary> /// Should manual simple detection of file deletion be enabled? /// </summary> bool EnableFileDeleteSimpleMonitor { get; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NET35 namespace NLog.Targets.Wrappers { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using NLog.Common; /// <summary> /// Concurrent Asynchronous request queue based on <see cref="ConcurrentQueue{T}"/> /// </summary> internal class ConcurrentRequestQueue : AsyncRequestQueueBase { private readonly ConcurrentQueue<AsyncLogEventInfo> _logEventInfoQueue = new ConcurrentQueue<AsyncLogEventInfo>(); /// <summary> /// Initializes a new instance of the AsyncRequestQueue class. /// </summary> /// <param name="requestLimit">Request limit.</param> /// <param name="overflowAction">The overflow action.</param> public ConcurrentRequestQueue(int requestLimit, AsyncTargetWrapperOverflowAction overflowAction) { RequestLimit = requestLimit; OnOverflow = overflowAction; } public override bool IsEmpty => _logEventInfoQueue.IsEmpty && Interlocked.Read(ref _count) == 0; /// <summary> /// Gets the number of requests currently in the queue. /// </summary> /// <remarks> /// Only for debugging purposes /// </remarks> public int Count => (int)_count; private long _count; /// <summary> /// Enqueues another item. If the queue is overflown the appropriate /// action is taken as specified by <see cref="AsyncRequestQueueBase.OnOverflow"/>. /// </summary> /// <param name="logEventInfo">The log event info.</param> /// <returns>Queue was empty before enqueue</returns> public override bool Enqueue(AsyncLogEventInfo logEventInfo) { long currentCount = Interlocked.Increment(ref _count); bool queueWasEmpty = currentCount == 1; // Inserted first item in empty queue if (currentCount > RequestLimit) { switch (OnOverflow) { case AsyncTargetWrapperOverflowAction.Discard: { queueWasEmpty = DequeueUntilBelowRequestLimit(); } break; case AsyncTargetWrapperOverflowAction.Block: { queueWasEmpty = WaitForBelowRequestLimit(); } break; case AsyncTargetWrapperOverflowAction.Grow: { InternalLogger.Debug("AsyncQueue - Growing the size of queue, because queue is full"); OnLogEventQueueGrows(currentCount); RequestLimit *= 2; } break; } } _logEventInfoQueue.Enqueue(logEventInfo); return queueWasEmpty; } private bool DequeueUntilBelowRequestLimit() { long currentCount; bool queueWasEmpty = false; do { if (_logEventInfoQueue.TryDequeue(out var lostItem)) { InternalLogger.Debug("AsyncQueue - Discarding single item, because queue is full"); queueWasEmpty = Interlocked.Decrement(ref _count) == 1 || queueWasEmpty; OnLogEventDropped(lostItem.LogEvent); break; } currentCount = Interlocked.Read(ref _count); queueWasEmpty = true; } while (currentCount > RequestLimit); return queueWasEmpty; } private bool WaitForBelowRequestLimit() { // Attempt to yield using SpinWait long currentCount = TrySpinWaitForLowerCount(); // If yield did not help, then wait on a lock if (currentCount > RequestLimit) { InternalLogger.Debug("AsyncQueue - Blocking until ready, because queue is full"); lock (_logEventInfoQueue) { InternalLogger.Trace("AsyncQueue - Entered critical section."); currentCount = Interlocked.Read(ref _count); while (currentCount > RequestLimit) { Interlocked.Decrement(ref _count); Monitor.Wait(_logEventInfoQueue); InternalLogger.Trace("AsyncQueue - Entered critical section."); currentCount = Interlocked.Increment(ref _count); } } } InternalLogger.Trace("AsyncQueue - Limit ok."); return true; } private long TrySpinWaitForLowerCount() { long currentCount = 0; bool firstYield = true; SpinWait spinWait = new SpinWait(); for (int i = 0; i <= 20; ++i) { if (spinWait.NextSpinWillYield) { if (firstYield) InternalLogger.Debug("AsyncQueue - Blocking with yield, because queue is full"); firstYield = false; } spinWait.SpinOnce(); currentCount = Interlocked.Read(ref _count); if (currentCount <= RequestLimit) break; } return currentCount; } /// <summary> /// Dequeues a maximum of <c>count</c> items from the queue /// and adds returns the list containing them. /// </summary> /// <param name="count">Maximum number of items to be dequeued</param> /// <returns>The array of log events.</returns> public override AsyncLogEventInfo[] DequeueBatch(int count) { if (_logEventInfoQueue.IsEmpty) return Internal.ArrayHelper.Empty<AsyncLogEventInfo>(); if (_count < count) count = Math.Min(count, Count); var resultEvents = new List<AsyncLogEventInfo>(count); DequeueBatch(count, resultEvents); if (resultEvents.Count == 0) return Internal.ArrayHelper.Empty<AsyncLogEventInfo>(); else return resultEvents.ToArray(); } /// <summary> /// Dequeues into a preallocated array, instead of allocating a new one /// </summary> /// <param name="count">Maximum number of items to be dequeued</param> /// <param name="result">Preallocated list</param> public override void DequeueBatch(int count, IList<AsyncLogEventInfo> result) { bool dequeueBatch = OnOverflow == AsyncTargetWrapperOverflowAction.Block; for (int i = 0; i < count; ++i) { if (_logEventInfoQueue.TryDequeue(out var item)) { if (!dequeueBatch) Interlocked.Decrement(ref _count); result.Add(item); } else { count = i; break; } } if (dequeueBatch) { lock (_logEventInfoQueue) { Interlocked.Add(ref _count, -count); Monitor.PulseAll(_logEventInfoQueue); } } } /// <summary> /// Clears the queue. /// </summary> public override void Clear() { while (!_logEventInfoQueue.IsEmpty) _logEventInfoQueue.TryDequeue(out var _); Interlocked.Exchange(ref _count, 0); if (OnOverflow == AsyncTargetWrapperOverflowAction.Block) { // Try to eject any threads, that are blocked in the RequestQueue lock (_logEventInfoQueue) { Monitor.PulseAll(_logEventInfoQueue); } } } } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using NLog.LayoutRenderers; using NLog.Config; using Xunit; namespace NLog.UnitTests.LayoutRenderers { public class FuncLayoutRendererTests : NLogTestBase { [Fact] public void RegisterCustomFuncLayoutRendererTest() { // Arrange var logFactory = new LogFactory().Setup().SetupExtensions(ext => ext.RegisterLayoutRenderer<MyFuncLayoutRenderer>("the-answer-new")) .LoadConfigurationFromXml(@"<nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout= 'TheAnswer=${the-answer-new:Format=D3}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; // Act var logger = logFactory.GetCurrentClassLogger(); logger.Debug("test1"); // Assert AssertDebugLastMessage("debug", "TheAnswer=042", logFactory); } [Fact] public void RegisterCustomFuncLayoutRendererTestOldStyle() { // Arrange var funcLayoutRenderer = new MyFuncLayoutRenderer("the-answer-new"); // Act var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterLayoutRenderer(funcLayoutRenderer)) .LoadConfigurationFromXml(@"<nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout= 'TheAnswer=${the-answer-new:Format=D3}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetCurrentClassLogger(); logger.Debug("test1"); // Assert AssertDebugLastMessage("debug", "TheAnswer=042", logFactory); } private class MyFuncLayoutRenderer : FuncLayoutRenderer { public MyFuncLayoutRenderer() : base(string.Empty) { } public MyFuncLayoutRenderer(string layoutRendererName) : base(layoutRendererName) { } /// <inheritdoc/> protected override object RenderValue(LogEventInfo logEvent) { return 42; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Layouts { using System; using NLog.Layouts; using Xunit; public class JsonArrayLayoutTests : NLogTestBase { [Fact] public void JsonArrayLayoutRendering() { var jsonLayout = new JsonArrayLayout() { Items = { new SimpleLayout("${longdate}"), new SimpleLayout("${level}"), new SimpleLayout("${message}"), } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello\n world", }; Assert.Equal("[ \"2010-01-01T12:34:56Z\", \"Info\", \"hello\\n world\" ]", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonArrayLayoutRenderingFromXml() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target type='Debug' name='Debug'> <layout type='JsonArrayLayout'> <item type='SimpleLayout' text='${longdate}' /> <item type='SimpleLayout' text='${level}' /> <item type='SimpleLayout' text='${message}' /> </layout> </target> </targets> <rules> <logger writeTo='Debug' /> </rules> </nlog> ").LogFactory; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello\n world", }; logFactory.GetCurrentClassLogger().Log(logEventInfo); logFactory.AssertDebugLastMessage("[ \"2010-01-01T12:34:56Z\", \"Info\", \"hello\\n world\" ]"); } [Fact] public void JsonArrayLayoutRenderingNoSpaces() { var jsonLayout = new JsonArrayLayout() { Items = { new SimpleLayout("${longdate}"), new SimpleLayout("${level}"), new SimpleLayout("${message}"), }, SuppressSpaces = true, }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello\n world", }; Assert.Equal("[\"2010-01-01T12:34:56Z\",\"Info\",\"hello\\n world\"]", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonArrayLayoutRenderingNotEmpty() { var jsonLayout = new JsonArrayLayout() { Items = { new JsonLayout() { IncludeEventProperties = true, RenderEmptyObject = false }, } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello\n world", }; Assert.Equal("[ ]", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonArrayLayoutRenderingEmpty() { var jsonLayout = new JsonArrayLayout() { Items = { new JsonLayout() { IncludeEventProperties = true, RenderEmptyObject = false }, }, RenderEmptyObject = false, }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello\n world", }; Assert.Equal("", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonArrayLayoutObjectRendering() { var jsonLayout = new JsonArrayLayout() { Items = { new JsonLayout() { Attributes = { new JsonAttribute("date", "${longdate}") } }, new JsonLayout() { Attributes = { new JsonAttribute("level", "${level}") } }, new JsonLayout() { Attributes = { new JsonAttribute("message", "${message}") } }, } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello\n world", }; Assert.Equal("[ { \"date\": \"2010-01-01 12:34:56.0000\" }, { \"level\": \"Info\" }, { \"message\": \"hello\\n world\" } ]", jsonLayout.Render(logEventInfo)); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using System; using NLog.Common; using NLog.Layouts; /// <summary> /// Limits the number of messages written per timespan to the wrapped target. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/LimitingWrappers-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/NLog/NLog/wiki/LimitingWrapper-target">Documentation on NLog Wiki</seealso> [Target("LimitingWrapper", IsWrapper = true)] public class LimitingTargetWrapper : WrapperTargetBase { private DateTime _firstWriteInInterval; /// <summary> /// Initializes a new instance of the <see cref="LimitingTargetWrapper" /> class. /// </summary> public LimitingTargetWrapper():this(null) { } /// <summary> /// Initializes a new instance of the <see cref="LimitingTargetWrapper" /> class. /// </summary> /// <param name="name">The name of the target.</param> /// <param name="wrappedTarget">The wrapped target.</param> public LimitingTargetWrapper(string name, Target wrappedTarget) : this(wrappedTarget, 1000, TimeSpan.FromHours(1)) { Name = name ?? Name; } /// <summary> /// Initializes a new instance of the <see cref="LimitingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> public LimitingTargetWrapper(Target wrappedTarget) : this(wrappedTarget, 1000, TimeSpan.FromHours(1)) { } /// <summary> /// Initializes a new instance of the <see cref="LimitingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="messageLimit">Maximum number of messages written per interval.</param> /// <param name="interval">Interval in which the maximum number of messages can be written.</param> public LimitingTargetWrapper(Target wrappedTarget, int messageLimit, TimeSpan interval) { Name = string.IsNullOrEmpty(wrappedTarget?.Name) ? Name : (wrappedTarget.Name + "_wrapped"); WrappedTarget = wrappedTarget; MessageLimit = messageLimit; Interval = interval; } /// <summary> /// Gets or sets the maximum allowed number of messages written per <see cref="Interval"/>. /// </summary> /// <remarks> /// Messages received after <see cref="MessageLimit"/> has been reached in the current <see cref="Interval"/> will be discarded. /// </remarks> /// <docgen category='General Options' order='10' /> public Layout<int> MessageLimit { get; set; } /// <summary> /// Gets or sets the interval in which messages will be written up to the <see cref="MessageLimit"/> number of messages. /// </summary> /// <remarks> /// Messages received after <see cref="MessageLimit"/> has been reached in the current <see cref="Interval"/> will be discarded. /// </remarks> /// <docgen category='General Options' order='10' /> public Layout<TimeSpan> Interval { get; set; } /// <summary> /// Gets the number of <see cref="AsyncLogEventInfo"/> written in the current <see cref="Interval"/>. /// </summary> /// <docgen category='General Options' order='10' /> public int MessagesWrittenCount { get; private set; } /// <summary> /// Initializes the target and resets the current Interval and <see cref="MessagesWrittenCount"/>. /// </summary> protected override void InitializeTarget() { if (MessageLimit.IsFixed && MessageLimit.FixedValue <= 0) throw new NLogConfigurationException("The LimitingTargetWrapper\'s MessageLimit property must be > 0."); if (Interval.IsFixed && Interval.FixedValue <= TimeSpan.Zero) throw new NLogConfigurationException("The LimitingTargetWrapper\'s property Interval must be > 0."); base.InitializeTarget(); ResetInterval(DateTime.MinValue); InternalLogger.Trace("{0}: Initialized with MessageLimit={1} and Interval={2}.", this, MessageLimit, Interval); } /// <summary> /// Writes log event to the wrapped target if the current <see cref="MessagesWrittenCount"/> is lower than <see cref="MessageLimit"/>. /// If the <see cref="MessageLimit"/> is already reached, no log event will be written to the wrapped target. /// <see cref="MessagesWrittenCount"/> resets when the current <see cref="Interval"/> is expired. /// </summary> /// <param name="logEvent">Log event to be written out.</param> protected override void Write(AsyncLogEventInfo logEvent) { var messageLimit = RenderLogEvent(MessageLimit, logEvent.LogEvent); var interval = RenderLogEvent(Interval, logEvent.LogEvent); if ((logEvent.LogEvent.TimeStamp - _firstWriteInInterval) > interval) { ResetInterval(logEvent.LogEvent.TimeStamp); InternalLogger.Debug("{0}: New interval of '{1}' started.", this, interval); } if (messageLimit <= 0 || MessagesWrittenCount < messageLimit) { WrappedTarget.WriteAsyncLogEvent(logEvent); MessagesWrittenCount++; } else { logEvent.Continuation(null); InternalLogger.Trace("{0}: Discarded event, because MessageLimit of '{1}' was reached.", this, messageLimit); } } private void ResetInterval(DateTime timestamp) { _firstWriteInInterval = timestamp; MessagesWrittenCount = 0; } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LayoutRenderers { using System; using System.Reflection; using NLog.Config; using NLog.LayoutRenderers; using Xunit; using Xunit.Abstractions; public class AssemblyVersionTests : NLogTestBase { private readonly ITestOutputHelper _testOutputHelper; #if !NETSTANDARD private static Lazy<Assembly> TestAssembly = new Lazy<Assembly>(() => GenerateTestAssembly()); #endif public AssemblyVersionTests(ITestOutputHelper testOutputHelper) { _testOutputHelper = testOutputHelper; } [Fact] public void EntryAssemblyVersionTest() { var assembly = Assembly.GetEntryAssembly(); var assemblyVersion = assembly is null ? $"Could not find value for entry assembly and version type {nameof(AssemblyVersionType.Assembly)}" : assembly.GetName().Version.ToString(); AssertLayoutRendererOutput("${assembly-version}", assemblyVersion); } [Fact] public void EntryAssemblyVersionDefaultTest() { var assembly = Assembly.GetEntryAssembly(); var assemblyVersion = assembly is null ? "1.2.3.4" : assembly.GetName().Version.ToString(); AssertLayoutRendererOutput("${assembly-version:default=1.2.3.4}", assemblyVersion); } [Fact] public void AssemblyNameVersionTest() { AssertLayoutRendererOutput("${assembly-version:NLogAutoLoadExtension}", "2.0.0.0"); } [Fact] public void AssemblyNameUnknownVersionTest() { using (new NoThrowNLogExceptions()) AssertLayoutRendererOutput("${assembly-version:FooBar:default=1.2.3.4}", "1.2.3.4"); } [Fact] public void AssemblyNameVersionTypeTest() { AssertLayoutRendererOutput("${assembly-version:name=NLogAutoLoadExtension:type=assembly}", "2.0.0.0"); AssertLayoutRendererOutput("${assembly-version:name=NLogAutoLoadExtension:type=file}", "2.0.0.1"); AssertLayoutRendererOutput("${assembly-version:name=NLogAutoLoadExtension:type=informational}", "2.0.0.2"); } [Theory] [InlineData("Major", "2")] [InlineData("Major.Minor", "2.0")] [InlineData("Major.Minor.Build", "2.0.0")] [InlineData("Major.Minor.Build.Revision", "2.0.0.0")] [InlineData("Revision.Build.Minor.Major", "0.0.0.2")] [InlineData("Major.MINOR.Build.Revision", "2.0.0.0")] [InlineData("Major.Minor.BuILD.Revision", "2.0.0.0")] [InlineData("MAJOR.Minor.BUILD.Revision", "2.0.0.0")] public void AssemblyVersionFormatTest(string format, string expected) { AssertLayoutRendererOutput($"${{assembly-version:name=NLogAutoLoadExtension:format={format}}}", expected); } #if !NETSTANDARD private const string AssemblyVersionTest = "1.2.3.4"; private const string AssemblyFileVersionTest = "1.1.1.2"; private const string AssemblyInformationalVersionTest = "Version 1"; [Theory] [InlineData(AssemblyVersionType.Assembly, AssemblyVersionTest)] [InlineData(AssemblyVersionType.File, AssemblyFileVersionTest)] [InlineData(AssemblyVersionType.Informational, AssemblyInformationalVersionTest)] public void AssemblyVersionTypeTest(AssemblyVersionType type, string expected) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message:withException=true}|${assembly-version:type=" + type.ToString().ToLower() + @"}' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"); var logger = LogManager.GetLogger("SomeLogger"); var compiledAssembly = TestAssembly.Value; var testLoggerType = compiledAssembly.GetType("LogTester.LoggerTest"); var logMethod = testLoggerType.GetMethod("TestLog"); var testLoggerInstance = Activator.CreateInstance(testLoggerType); logMethod.Invoke(testLoggerInstance, new object[] { logger, compiledAssembly }); var lastMessage = GetDebugLastMessage("debug"); var messageParts = lastMessage.Split('|'); var logMessage = messageParts[0]; var logVersion = messageParts[1]; if (logMessage.StartsWith("Skip:")) { _testOutputHelper.WriteLine(logMessage); } else { Assert.StartsWith("Pass:", logMessage); Assert.Equal(expected, logVersion); } } [Theory] [InlineData(AssemblyVersionType.Assembly, "Major", "1")] [InlineData(AssemblyVersionType.Assembly, "Major.Minor", "1.2")] [InlineData(AssemblyVersionType.Assembly, "Major.Minor.Build", "1.2.3")] [InlineData(AssemblyVersionType.Assembly, "Major.Minor.Build.Revision", "1.2.3.4")] [InlineData(AssemblyVersionType.Assembly, "Revision.Build.Minor.Major", "4.3.2.1")] [InlineData(AssemblyVersionType.Assembly, "Build.Major", "3.1")] [InlineData(AssemblyVersionType.File, "Major", "1")] [InlineData(AssemblyVersionType.File, "Major.Minor", "1.1")] [InlineData(AssemblyVersionType.File, "Major.Minor.Build", "1.1.1")] [InlineData(AssemblyVersionType.File, "Major.Minor.Build.Revision", "1.1.1.2")] [InlineData(AssemblyVersionType.File, "Revision.Build.Minor.Major", "2.1.1.1")] [InlineData(AssemblyVersionType.File, "Build.Major", "1.1")] [InlineData(AssemblyVersionType.Informational, "Major", "Version 1")] [InlineData(AssemblyVersionType.Informational, "Major.Minor", "Version 1.0")] [InlineData(AssemblyVersionType.Informational, "Major.Minor.Build", "Version 1.0.0")] [InlineData(AssemblyVersionType.Informational, "Major.Minor.Build.Revision", "Version 1")] [InlineData(AssemblyVersionType.Informational, "Revision.Build.Minor.Major", "0.0.0.Version 1")] [InlineData(AssemblyVersionType.Informational, "Build.Major", "0.Version 1")] public void AssemblyVersionFormatAndTypeTest(AssemblyVersionType type, string format, string expected) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message:withException=true}|${assembly-version:type=" + type.ToString().ToLower() + @":format=" + format + @"}' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"); var logger = LogManager.GetLogger("SomeLogger"); var compiledAssembly = TestAssembly.Value; var testLoggerType = compiledAssembly.GetType("LogTester.LoggerTest"); var logMethod = testLoggerType.GetMethod("TestLog"); var testLoggerInstance = Activator.CreateInstance(testLoggerType); logMethod.Invoke(testLoggerInstance, new object[] { logger, compiledAssembly }); var lastMessage = GetDebugLastMessage("debug"); var messageParts = lastMessage.Split('|'); var logMessage = messageParts[0]; var logVersion = messageParts[1]; if (logMessage.StartsWith("Skip:")) { _testOutputHelper.WriteLine(logMessage); } else { Assert.StartsWith("Pass:", logMessage); Assert.Equal(expected, logVersion); } } private static Assembly GenerateTestAssembly() { const string code = @" using System; using System.Reflection; [assembly: AssemblyVersion(""" + AssemblyVersionTest + @""")] [assembly: AssemblyFileVersion(""" + AssemblyFileVersionTest + @""")] [assembly: AssemblyInformationalVersion(""" + AssemblyInformationalVersionTest + @""")] namespace LogTester { public class LoggerTest { public void TestLog(NLog.Logger logger, Assembly assembly) { if (System.Reflection.Assembly.GetEntryAssembly() == null) { // In some unit testing scenarios we cannot find the entry assembly // So we attempt to force this to be set, which can also still fail // This is not expected to be necessary in Visual Studio // See https://github.com/Microsoft/vstest/issues/649 try { SetEntryAssembly(assembly); } catch (InvalidOperationException ioex) { logger.Debug(ioex, ""Skip: No entry assembly""); return; } } logger.Debug(""Pass: Test fully executed""); } private static void SetEntryAssembly(Assembly assembly) { var manager = new AppDomainManager(); var domain = AppDomain.CurrentDomain; if (domain == null) throw new InvalidOperationException(""Current app domain is null""); var entryAssemblyField = manager.GetType().GetField(""m_entryAssembly"", BindingFlags.Instance | BindingFlags.NonPublic); if (entryAssemblyField == null) throw new InvalidOperationException(""Unable to find field m_entryAssembly""); entryAssemblyField.SetValue(manager, assembly); var domainManagerField = domain.GetType().GetField(""_domainManager"", BindingFlags.Instance | BindingFlags.NonPublic); if (domainManagerField == null) throw new InvalidOperationException(""Unable to find field _domainManager""); domainManagerField.SetValue(domain, manager); } } }"; var provider = new Microsoft.CSharp.CSharpCodeProvider(); var parameters = new System.CodeDom.Compiler.CompilerParameters { GenerateInMemory = true, GenerateExecutable = false, ReferencedAssemblies = { "NLog.dll" } }; System.CodeDom.Compiler.CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); var compiledAssembly = results.CompiledAssembly; return compiledAssembly; } #endif } }<file_sep>using System; using NLog; using NLog.Targets; using NLog.Targets.Wrappers; using System.Diagnostics; class Example { static void Main(string[] args) { FileTarget wrappedTarget = new FileTarget(); wrappedTarget.FileName = "${basedir}/file.txt"; FilteringTargetWrapper filteringTarget = new FilteringTargetWrapper(); filteringTarget.WrappedTarget = wrappedTarget; filteringTarget.Condition = "contains('${message}','1')"; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(filteringTarget, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message 0"); logger.Debug("log message 1"); logger.Debug("log message 2"); logger.Debug("log message 11"); } } <file_sep>--- name: Feature request about: Suggest an idea for this project --- Hi! Thanks for reporting this feature! Please keep / fill in the relevant info from this template so that we can help you as best as possible. **NLog version**: (e.g. 4.4.13) **Platform**: .Net 3.5 / .Net 4.0 / .Net 4.5 / Mono 4 / Xamarin Android / Xamarin iOS / .NET Core / .NET5 / .NET6 **Current NLog config** (xml or C#, if relevant) ```xml <nlog> <targets> </targets> <rules> </rules> </nlog> ``` - Why do we need it? - An example of the XML config, if relevant. <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Reflection; using NLog.Common; using NLog.Internal; using NLog.LayoutRenderers; /// <summary> /// Factory for class-based items. /// </summary> /// <typeparam name="TBaseType">The base type of each item.</typeparam> /// <typeparam name="TAttributeType">The type of the attribute used to annotate items.</typeparam> internal class Factory<TBaseType, TAttributeType> : IFactory, IFactory<TBaseType> #pragma warning disable CS0618 // Type or member is obsolete ,INamedItemFactory<TBaseType, Type> #pragma warning restore CS0618 // Type or member is obsolete where TBaseType : class where TAttributeType : NameBaseAttribute { private struct ItemFactory { public readonly GetTypeDelegate ItemType; public readonly Func<TBaseType> ItemCreator; public ItemFactory(GetTypeDelegate type, Func<TBaseType> itemCreator) { ItemType = type; ItemCreator = itemCreator; } } private readonly Dictionary<string, ItemFactory> _items; private readonly ConfigurationItemFactory _parentFactory; private readonly Factory<TBaseType, TAttributeType> _globalDefaultFactory; internal Factory(ConfigurationItemFactory parentFactory, Factory<TBaseType, TAttributeType> globalDefaultFactory) { _parentFactory = parentFactory; _globalDefaultFactory = globalDefaultFactory; _items = new Dictionary<string, ItemFactory>(globalDefaultFactory is null ? 16 : 0, StringComparer.OrdinalIgnoreCase); } private delegate Type GetTypeDelegate(); /// <summary> /// Scans the assembly. /// </summary> /// <param name="types">The types to scan.</param> /// <param name="assemblyName">The assembly name for the types.</param> /// <param name="itemNamePrefix">The prefix.</param> [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2072")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2062")] public void ScanTypes(Type[] types, string assemblyName, string itemNamePrefix) { foreach (Type t in types) { try { RegisterType(t, itemNamePrefix); } catch (Exception exception) { InternalLogger.Error(exception, "Failed to add type '{0}'.", t.FullName); if (exception.MustBeRethrown()) { throw; } } } } /// <summary> /// Registers the type. /// </summary> /// <param name="type">The type to register.</param> /// <param name="itemNamePrefix">The item name prefix.</param> public void RegisterType([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicMethods)] Type type, string itemNamePrefix) { if (typeof(TBaseType).IsAssignableFrom(type)) { IEnumerable<TAttributeType> attributes = type.GetCustomAttributes<TAttributeType>(false); if (attributes != null) { foreach (var attr in attributes) { RegisterDefinition(type, attr.Name, itemNamePrefix); } } } } /// <summary> /// Registers the item based on a type name. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="typeName">Name of the type.</param> [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2072")] public void RegisterNamedType(string itemName, string typeName) { itemName = FactoryExtensions.NormalizeName(itemName); Type itemType = null; GetTypeDelegate typeLookup = () => { if (itemType is null) { InternalLogger.Debug("Object reflection needed to resolve type: {0}", typeName); itemType = PropertyTypeConverter.ConvertToType(typeName, false); } return itemType; }; Func<TBaseType> typeCreator = () => { var type = typeLookup(); return type != null ? (TBaseType)Activator.CreateInstance(type) : null; }; lock (ConfigurationItemFactory.SyncRoot) { _items[itemName] = new ItemFactory(typeLookup, typeCreator); } } /// <summary> /// Clears the contents of the factory. /// </summary> public virtual void Clear() { lock (ConfigurationItemFactory.SyncRoot) { _items.Clear(); } } /// <inheritdoc/> [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2067")] void INamedItemFactory<TBaseType, Type>.RegisterDefinition(string itemName, Type itemDefinition) { if (string.IsNullOrEmpty(itemName)) throw new ArgumentException($"Missing NLog {typeof(TBaseType).Name} type-alias", nameof(itemName)); if (!typeof(TBaseType).IsAssignableFrom(itemDefinition)) throw new ArgumentException($"Not of type NLog {typeof(TBaseType).Name}", nameof(itemDefinition)); RegisterDefinition(itemDefinition, itemName, string.Empty); } public void RegisterDefinition(string typeAlias, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type itemType) { if (string.IsNullOrEmpty(typeAlias)) throw new ArgumentException($"Missing NLog {typeof(TBaseType).Name} type-alias", nameof(typeAlias)); if (!typeof(TBaseType).IsAssignableFrom(itemType)) throw new ArgumentException($"Not of type NLog {typeof(TBaseType).Name}", nameof(itemType)); RegisterDefinition(itemType, typeAlias, string.Empty); } private void RegisterDefinition([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type itemType, string typeAlias, string itemNamePrefix) { typeAlias = FactoryExtensions.NormalizeName(typeAlias); Func<TBaseType> itemCreator = () => (TBaseType)Activator.CreateInstance(itemType); var itemFactory = new ItemFactory(() => itemType, itemCreator); lock (ConfigurationItemFactory.SyncRoot) { _parentFactory.RegisterTypeProperties(itemType, () => itemCreator.Invoke()); _items[itemNamePrefix + typeAlias] = itemFactory; } } public void RegisterType<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] TType>(string typeAlias) where TType : TBaseType, new() { typeAlias = FactoryExtensions.NormalizeName(typeAlias); var itemFactory = new ItemFactory(() => typeof(TType), () => new TType()); lock (ConfigurationItemFactory.SyncRoot) { _parentFactory.RegisterTypeProperties<TType>(() => new TType()); _items[typeAlias] = itemFactory; } } public void RegisterType<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] TType>(string typeAlias, Func<TType> itemCreator) where TType : TBaseType { typeAlias = FactoryExtensions.NormalizeName(typeAlias); var itemFactory = new ItemFactory(() => typeof(TType), () => itemCreator()); lock (ConfigurationItemFactory.SyncRoot) { _parentFactory.RegisterTypeProperties<TType>(() => itemCreator()); _items[typeAlias] = itemFactory; } } /// <inheritdoc/> [Obsolete("Use TryCreateInstance instead. Marked obsolete with NLog v5.2")] public bool TryGetDefinition(string itemName, out Type result) { itemName = FactoryExtensions.NormalizeName(itemName); if (!TryGetItemFactory(itemName, out var itemFactory) || itemFactory.ItemType is null) { if (_globalDefaultFactory != null && _globalDefaultFactory.TryGetDefinition(itemName, out result)) { return true; } result = null; return false; } try { result = itemFactory.ItemType.Invoke(); return result != null; } catch (Exception ex) { if (ex.MustBeRethrown()) { throw; } // delegate invocation failed - type is not available result = null; return false; } } private bool TryGetItemFactory(string itemName, out ItemFactory itemFactory) { lock (ConfigurationItemFactory.SyncRoot) { return _items.TryGetValue(itemName, out itemFactory); } } /// <inheritdoc/> public virtual bool TryCreateInstance(string itemName, out TBaseType result) { #pragma warning disable CS0618 // Type or member is obsolete if (TryCreateInstanceLegacy(itemName, out result)) return true; #pragma warning restore CS0618 // Type or member is obsolete itemName = FactoryExtensions.NormalizeName(itemName); if (!TryGetItemFactory(itemName, out var itemFactory) || itemFactory.ItemCreator is null) { result = null; return false; } result = itemFactory.ItemCreator.Invoke(); return !(result is null); } [Obsolete("Use TryCreateInstance instead. Marked obsolete with NLog v5.2")] private bool TryCreateInstanceLegacy(string itemName, out TBaseType result) { if (!ReferenceEquals(_parentFactory.CreateInstance, FactoryHelper.CreateInstance)) { if (TryGetDefinition(itemName, out var itemType)) { result = (TBaseType)_parentFactory.CreateInstance(itemType); return true; } } result = null; return false; } /// <inheritdoc/> [Obsolete("Use TryCreateInstance instead. Marked obsolete with NLog v5.2")] TBaseType INamedItemFactory<TBaseType, Type>.CreateInstance(string itemName) { return FactoryExtensions.CreateInstance(this, itemName); } } internal static class FactoryExtensions { public static TBaseType CreateInstance<TBaseType>(this IFactory<TBaseType> factory, string typeAlias) where TBaseType : class { if (factory.TryCreateInstance(typeAlias, out TBaseType result)) { return result; } var normalName = NormalizeName(typeAlias); var message = typeof(TBaseType).Name + " type-alias is unknown: '" + typeAlias + "'"; if (normalName != null && (normalName.StartsWith("aspnet", StringComparison.OrdinalIgnoreCase) || normalName.StartsWith("iis", StringComparison.OrdinalIgnoreCase))) { #if NETSTANDARD message += ". Extension NLog.Web.AspNetCore not included?"; #else message += ". Extension NLog.Web not included?"; #endif } else if (normalName?.StartsWith("database", StringComparison.OrdinalIgnoreCase) == true) { message += ". Extension NLog.Database not included?"; } else if (normalName?.StartsWith("eventlog", StringComparison.OrdinalIgnoreCase) == true) { message += ". Extension NLog.WindowsEventLog not included?"; } else if (normalName?.StartsWith("windowsidentity", StringComparison.OrdinalIgnoreCase) == true) { message += ". Extension NLog.WindowsIdentity not included?"; } else if (normalName?.StartsWith("outputdebugstring", StringComparison.OrdinalIgnoreCase) == true) { message += ". Extension NLog.OutputDebugString not included?"; } else if (normalName?.StartsWith("performancecounter", StringComparison.OrdinalIgnoreCase) == true) { message += ". Extension NLog.PerformanceCounter not included?"; } throw new ArgumentException(message); } public static string NormalizeName(string itemName) { if (itemName is null) { return string.Empty; } var delimitIndex = itemName.IndexOf('-'); if (delimitIndex < 0) { return itemName; } // Only for the first comma var commaIndex = itemName.IndexOf(','); if (commaIndex >= 0) { var left = itemName.Substring(0, commaIndex).Replace("-", string.Empty); var right = itemName.Substring(commaIndex); return left + right; } return itemName.Replace("-", string.Empty); } } /// <summary> /// Factory specialized for <see cref="LayoutRenderer"/>s. /// </summary> internal sealed class LayoutRendererFactory : Factory<LayoutRenderer, LayoutRendererAttribute> { private readonly Dictionary<string, FuncLayoutRenderer> _funcRenderers = new Dictionary<string, FuncLayoutRenderer>(StringComparer.OrdinalIgnoreCase); private readonly LayoutRendererFactory _globalDefaultFactory; public LayoutRendererFactory(ConfigurationItemFactory parentFactory, LayoutRendererFactory globalDefaultFactory) : base(parentFactory, globalDefaultFactory) { _globalDefaultFactory = globalDefaultFactory; } /// <inheritdoc/> public override void Clear() { _funcRenderers.Clear(); base.Clear(); } /// <summary> /// Register a layout renderer with a callback function. /// </summary> /// <param name="itemName">Name of the layoutrenderer, without ${}.</param> /// <param name="renderer">the renderer that renders the value.</param> public void RegisterFuncLayout(string itemName, FuncLayoutRenderer renderer) { itemName = FactoryExtensions.NormalizeName(itemName); lock (ConfigurationItemFactory.SyncRoot) { _funcRenderers[itemName] = renderer; } } /// <summary> /// Tries to create an item instance. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="result">The result.</param> /// <returns>True if instance was created successfully, false otherwise.</returns> public override bool TryCreateInstance(string itemName, out LayoutRenderer result) { //first try func renderers, as they should have the possibility to overwrite a current one. FuncLayoutRenderer funcResult; itemName = FactoryExtensions.NormalizeName(itemName); if (_funcRenderers.Count > 0) { lock (ConfigurationItemFactory.SyncRoot) { if (_funcRenderers.TryGetValue(itemName, out funcResult)) { result = funcResult; return true; } } } if (_globalDefaultFactory?._funcRenderers?.Count > 0) { lock (ConfigurationItemFactory.SyncRoot) { if (_globalDefaultFactory._funcRenderers.TryGetValue(itemName, out funcResult)) { result = funcResult; return true; } } } return base.TryCreateInstance(itemName, out result); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Collections.Generic; namespace NLog.Internal { /// <summary> /// Most-Recently-Used-Cache, that discards less frequently used items on overflow /// </summary> internal class MruCache<TKey, TValue> { private readonly Dictionary<TKey, MruCacheItem> _dictionary; private readonly int _maxCapacity; private long _currentVersion; /// <summary> /// Constructor /// </summary> /// <param name="maxCapacity">Maximum number of items the cache will hold before discarding.</param> public MruCache(int maxCapacity) { _maxCapacity = maxCapacity; _dictionary = new Dictionary<TKey, MruCacheItem>(_maxCapacity / 4); _currentVersion = 1; } /// <summary> /// Attempt to insert item into cache. /// </summary> /// <param name="key">Key of the item to be inserted in the cache.</param> /// <param name="value">Value of the item to be inserted in the cache.</param> /// <returns><c>true</c> when the key does not already exist in the cache, <c>false</c> otherwise.</returns> public bool TryAddValue(TKey key, TValue value) { lock (_dictionary) { MruCacheItem item; if (_dictionary.TryGetValue(key, out item)) { var version = _currentVersion; if (item.Version != version || !EqualityComparer<TValue>.Default.Equals(value, item.Value)) { _dictionary[key] = new MruCacheItem(value, version, false); } return false; // Already exists } else { if (_dictionary.Count >= _maxCapacity) { ++_currentVersion; PruneCache(); } _dictionary.Add(key, new MruCacheItem(value, _currentVersion, true)); return true; } } } private void PruneCache() { // There 3 priorities: // - High Priority - Non-Virgins with version very close to _currentVersion // - Medium Priority - Version close to _currentVersion // - Low Priority - Old-Virgins // Make 3 sweeps: // - Kill all the old ones // - Kill all the virgins // - Slaughterhouse long latestGeneration = _currentVersion - 2; long oldestGeneration = 1; var pruneKeys = new List<TKey>((int)(_dictionary.Count / 2.5)); for (int i = 0; i < 3; ++i) { long oldGeneration = _currentVersion - 5; switch (i) { case 0: oldGeneration = _currentVersion - (int)(_maxCapacity / 1.5); break; case 1: oldGeneration = _currentVersion - 10; break; } if (oldGeneration < oldestGeneration) oldGeneration = oldestGeneration; oldestGeneration = long.MaxValue; long elementGeneration; foreach (var element in _dictionary) { elementGeneration = element.Value.Version; if (elementGeneration <= oldGeneration || (element.Value.Virgin && (i != 0 || elementGeneration < latestGeneration))) { pruneKeys.Add(element.Key); if (_dictionary.Count - pruneKeys.Count < _maxCapacity / 1.5) { i = 3; break; // Do not clear the entire cache } } else if (elementGeneration < oldestGeneration) { oldestGeneration = elementGeneration; } } } foreach (var pruneKey in pruneKeys) { _dictionary.Remove(pruneKey); } if (_dictionary.Count >= _maxCapacity) { _dictionary.Clear(); // Failed to perform sweep, fallback to fail safe } } /// <summary> /// Lookup existing item in cache. /// </summary> /// <param name="key">Key of the item to be searched in the cache.</param> /// <param name="value">Output value of the item found in the cache.</param> /// <returns><c>True</c> when the key is found in the cache, <c>false</c> otherwise.</returns> public bool TryGetValue(TKey key, out TValue value) { MruCacheItem item; try { if (!_dictionary.TryGetValue(key, out item)) { value = default(TValue); return false; } } catch { item = default(MruCacheItem); // Too many people in the same room } if (item.Version != _currentVersion || item.Virgin) { // Update item version to mark as recently used lock (_dictionary) { var version = _currentVersion; if (_dictionary.TryGetValue(key, out item)) { if (item.Version != version || item.Virgin) { if (item.Virgin) { version = ++_currentVersion; } _dictionary[key] = new MruCacheItem(item.Value, version, false); } } else { value = default(TValue); return false; } } } value = item.Value; return true; } struct MruCacheItem { public readonly TValue Value; public readonly long Version; public readonly bool Virgin; public MruCacheItem(TValue value, long version, bool virgin) { Value = value; Version = version; Virgin = virgin; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Common { using JetBrains.Annotations; using System; using System.ComponentModel; public static partial class InternalLogger { /// <summary> /// Gets a value indicating whether internal log includes Trace messages. /// </summary> public static bool IsTraceEnabled => IsLogLevelEnabled(LogLevel.Trace); /// <summary> /// Gets a value indicating whether internal log includes Debug messages. /// </summary> public static bool IsDebugEnabled => IsLogLevelEnabled(LogLevel.Debug); /// <summary> /// Gets a value indicating whether internal log includes Info messages. /// </summary> public static bool IsInfoEnabled => IsLogLevelEnabled(LogLevel.Info); /// <summary> /// Gets a value indicating whether internal log includes Warn messages. /// </summary> public static bool IsWarnEnabled => IsLogLevelEnabled(LogLevel.Warn); /// <summary> /// Gets a value indicating whether internal log includes Error messages. /// </summary> public static bool IsErrorEnabled => IsLogLevelEnabled(LogLevel.Error); /// <summary> /// Gets a value indicating whether internal log includes Fatal messages. /// </summary> public static bool IsFatalEnabled => IsLogLevelEnabled(LogLevel.Fatal); /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Trace([Localizable(false)] string message, params object[] args) { Write(null, LogLevel.Trace, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <param name="message">Log message.</param> public static void Trace([Localizable(false)] string message) { Write(null, LogLevel.Trace, message, null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Trace. /// </summary> /// <param name="messageFunc">Function that returns the log message.</param> public static void Trace([Localizable(false)] Func<string> messageFunc) { if (IsTraceEnabled) Write(null, LogLevel.Trace, messageFunc(), null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Trace level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Trace(Exception ex, [Localizable(false)] string message, params object[] args) { Write(ex, LogLevel.Trace, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> [StringFormatMethod("message")] public static void Trace<TArgument1>([Localizable(false)] string message, TArgument1 arg0) { if (IsTraceEnabled) Log(null, LogLevel.Trace, message, arg0); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> [StringFormatMethod("message")] public static void Trace<TArgument1, TArgument2>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1) { if (IsTraceEnabled) Log(null, LogLevel.Trace, message, arg0, arg1); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> /// <param name="arg2">Argument {2} to the message.</param> [StringFormatMethod("message")] public static void Trace<TArgument1, TArgument2, TArgument3>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1, TArgument3 arg2) { if (IsTraceEnabled) Log(null, LogLevel.Trace, message, arg0, arg1, arg2); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Trace level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Log message.</param> public static void Trace(Exception ex, [Localizable(false)] string message) { Write(ex, LogLevel.Trace, message, null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Trace level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Trace. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="messageFunc">Function that returns the log message.</param> public static void Trace(Exception ex, [Localizable(false)] Func<string> messageFunc) { if (IsTraceEnabled) Write(ex, LogLevel.Trace, messageFunc(), null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Debug level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Debug([Localizable(false)] string message, params object[] args) { Write(null, LogLevel.Debug, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Debug level. /// </summary> /// <param name="message">Log message.</param> public static void Debug([Localizable(false)] string message) { Write(null, LogLevel.Debug, message, null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Debug level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Debug. /// </summary> /// <param name="messageFunc">Function that returns the log message.</param> public static void Debug([Localizable(false)] Func<string> messageFunc) { if (IsDebugEnabled) Write(null, LogLevel.Debug, messageFunc(), null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Debug level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Debug(Exception ex, [Localizable(false)] string message, params object[] args) { Write(ex, LogLevel.Debug, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> [StringFormatMethod("message")] public static void Debug<TArgument1>([Localizable(false)] string message, TArgument1 arg0) { if (IsDebugEnabled) Log(null, LogLevel.Debug, message, arg0); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> [StringFormatMethod("message")] public static void Debug<TArgument1, TArgument2>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1) { if (IsDebugEnabled) Log(null, LogLevel.Debug, message, arg0, arg1); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> /// <param name="arg2">Argument {2} to the message.</param> [StringFormatMethod("message")] public static void Debug<TArgument1, TArgument2, TArgument3>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1, TArgument3 arg2) { if (IsDebugEnabled) Log(null, LogLevel.Debug, message, arg0, arg1, arg2); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Debug level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Log message.</param> public static void Debug(Exception ex, [Localizable(false)] string message) { Write(ex, LogLevel.Debug, message, null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Debug level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Debug. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="messageFunc">Function that returns the log message.</param> public static void Debug(Exception ex, [Localizable(false)] Func<string> messageFunc) { if (IsDebugEnabled) Write(ex, LogLevel.Debug, messageFunc(), null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Info level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Info([Localizable(false)] string message, params object[] args) { Write(null, LogLevel.Info, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Info level. /// </summary> /// <param name="message">Log message.</param> public static void Info([Localizable(false)] string message) { Write(null, LogLevel.Info, message, null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Info level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Info. /// </summary> /// <param name="messageFunc">Function that returns the log message.</param> public static void Info([Localizable(false)] Func<string> messageFunc) { if (IsInfoEnabled) Write(null, LogLevel.Info, messageFunc(), null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Info level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Info(Exception ex, [Localizable(false)] string message, params object[] args) { Write(ex, LogLevel.Info, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> [StringFormatMethod("message")] public static void Info<TArgument1>([Localizable(false)] string message, TArgument1 arg0) { if (IsInfoEnabled) Log(null, LogLevel.Info, message, arg0); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> [StringFormatMethod("message")] public static void Info<TArgument1, TArgument2>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1) { if (IsInfoEnabled) Log(null, LogLevel.Info, message, arg0, arg1); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> /// <param name="arg2">Argument {2} to the message.</param> [StringFormatMethod("message")] public static void Info<TArgument1, TArgument2, TArgument3>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1, TArgument3 arg2) { if (IsInfoEnabled) Log(null, LogLevel.Info, message, arg0, arg1, arg2); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Info level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Log message.</param> public static void Info(Exception ex, [Localizable(false)] string message) { Write(ex, LogLevel.Info, message, null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Info level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Info. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="messageFunc">Function that returns the log message.</param> public static void Info(Exception ex, [Localizable(false)] Func<string> messageFunc) { if (IsInfoEnabled) Write(ex, LogLevel.Info, messageFunc(), null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Warn level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Warn([Localizable(false)] string message, params object[] args) { Write(null, LogLevel.Warn, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Warn level. /// </summary> /// <param name="message">Log message.</param> public static void Warn([Localizable(false)] string message) { Write(null, LogLevel.Warn, message, null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Warn level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Warn. /// </summary> /// <param name="messageFunc">Function that returns the log message.</param> public static void Warn([Localizable(false)] Func<string> messageFunc) { if (IsWarnEnabled) Write(null, LogLevel.Warn, messageFunc(), null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Warn level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Warn(Exception ex, [Localizable(false)] string message, params object[] args) { Write(ex, LogLevel.Warn, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> [StringFormatMethod("message")] public static void Warn<TArgument1>([Localizable(false)] string message, TArgument1 arg0) { if (IsWarnEnabled) Log(null, LogLevel.Warn, message, arg0); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> [StringFormatMethod("message")] public static void Warn<TArgument1, TArgument2>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1) { if (IsWarnEnabled) Log(null, LogLevel.Warn, message, arg0, arg1); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> /// <param name="arg2">Argument {2} to the message.</param> [StringFormatMethod("message")] public static void Warn<TArgument1, TArgument2, TArgument3>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1, TArgument3 arg2) { if (IsWarnEnabled) Log(null, LogLevel.Warn, message, arg0, arg1, arg2); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Warn level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Log message.</param> public static void Warn(Exception ex, [Localizable(false)] string message) { Write(ex, LogLevel.Warn, message, null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Warn level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Warn. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="messageFunc">Function that returns the log message.</param> public static void Warn(Exception ex, [Localizable(false)] Func<string> messageFunc) { if (IsWarnEnabled) Write(ex, LogLevel.Warn, messageFunc(), null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Error level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Error([Localizable(false)] string message, params object[] args) { Write(null, LogLevel.Error, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Error level. /// </summary> /// <param name="message">Log message.</param> public static void Error([Localizable(false)] string message) { Write(null, LogLevel.Error, message, null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Error level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Error. /// </summary> /// <param name="messageFunc">Function that returns the log message.</param> public static void Error([Localizable(false)] Func<string> messageFunc) { if (IsErrorEnabled) Write(null, LogLevel.Error, messageFunc(), null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Error level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Error(Exception ex, [Localizable(false)] string message, params object[] args) { Write(ex, LogLevel.Error, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> [StringFormatMethod("message")] public static void Error<TArgument1>([Localizable(false)] string message, TArgument1 arg0) { if (IsErrorEnabled) Log(null, LogLevel.Error, message, arg0); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> [StringFormatMethod("message")] public static void Error<TArgument1, TArgument2>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1) { if (IsErrorEnabled) Log(null, LogLevel.Error, message, arg0, arg1); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> /// <param name="arg2">Argument {2} to the message.</param> [StringFormatMethod("message")] public static void Error<TArgument1, TArgument2, TArgument3>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1, TArgument3 arg2) { if (IsErrorEnabled) Log(null, LogLevel.Error, message, arg0, arg1, arg2); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Error level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Log message.</param> public static void Error(Exception ex, [Localizable(false)] string message) { Write(ex, LogLevel.Error, message, null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Error level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Error. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="messageFunc">Function that returns the log message.</param> public static void Error(Exception ex, [Localizable(false)] Func<string> messageFunc) { if (IsErrorEnabled) Write(ex, LogLevel.Error, messageFunc(), null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Fatal level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Fatal([Localizable(false)] string message, params object[] args) { Write(null, LogLevel.Fatal, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Fatal level. /// </summary> /// <param name="message">Log message.</param> public static void Fatal([Localizable(false)] string message) { Write(null, LogLevel.Fatal, message, null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Fatal level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Fatal. /// </summary> /// <param name="messageFunc">Function that returns the log message.</param> public static void Fatal([Localizable(false)] Func<string> messageFunc) { if (IsFatalEnabled) Write(null, LogLevel.Fatal, messageFunc(), null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Fatal level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Fatal(Exception ex, [Localizable(false)] string message, params object[] args) { Write(ex, LogLevel.Fatal, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> [StringFormatMethod("message")] public static void Fatal<TArgument1>([Localizable(false)] string message, TArgument1 arg0) { if (IsFatalEnabled) Log(null, LogLevel.Fatal, message, arg0); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> [StringFormatMethod("message")] public static void Fatal<TArgument1, TArgument2>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1) { if (IsFatalEnabled) Log(null, LogLevel.Fatal, message, arg0, arg1); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> /// <param name="arg2">Argument {2} to the message.</param> [StringFormatMethod("message")] public static void Fatal<TArgument1, TArgument2, TArgument3>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1, TArgument3 arg2) { if (IsFatalEnabled) Log(null, LogLevel.Fatal, message, arg0, arg1, arg2); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Fatal level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Log message.</param> public static void Fatal(Exception ex, [Localizable(false)] string message) { Write(ex, LogLevel.Fatal, message, null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Fatal level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Fatal. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="messageFunc">Function that returns the log message.</param> public static void Fatal(Exception ex, [Localizable(false)] Func<string> messageFunc) { if (IsFatalEnabled) Write(ex, LogLevel.Fatal, messageFunc(), null); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Linq; namespace NLog.UnitTests { using System; using System.Text; using System.Collections.Generic; using System.Reflection; using NLog.Config; using Xunit; /// <summary> /// Test the characteristics of the API. Config of the API is tested in <see cref="NLog.UnitTests.Config.ConfigApiTests"/> /// </summary> public class ApiTests : NLogTestBase { private Type[] allTypes; private Assembly nlogAssembly = typeof(LogManager).Assembly; private readonly Dictionary<Type, int> typeUsageCount = new Dictionary<Type, int>(); public ApiTests() { allTypes = typeof(LogManager).Assembly.GetTypes(); } [Fact] public void PublicEnumsTest() { foreach (Type type in allTypes) { if (!type.IsPublic) { continue; } if (type.IsEnum || type.IsInterface) { typeUsageCount[type] = 0; } } typeUsageCount[typeof(IInstallable)] = 1; foreach (Type type in allTypes) { if (type.IsGenericTypeDefinition) { continue; } if (type.BaseType != null) { IncrementUsageCount(type.BaseType); } foreach (var iface in type.GetInterfaces()) { IncrementUsageCount(iface); } foreach (var method in type.GetMethods()) { if (method.IsGenericMethodDefinition) { continue; } // Console.WriteLine(" {0}", method.Name); try { IncrementUsageCount(method.ReturnType); foreach (var p in method.GetParameters()) { IncrementUsageCount(p.ParameterType); } } catch (Exception ex) { // this sometimes throws on .NET Compact Framework, but is not fatal Console.WriteLine("EXCEPTION {0}", ex); } } } var unusedTypes = new List<Type>(); StringBuilder sb = new StringBuilder(); foreach (var kvp in typeUsageCount) { if (kvp.Value == 0) { Console.WriteLine("Type '{0}' is not used.", kvp.Key); unusedTypes.Add(kvp.Key); sb.Append(kvp.Key.FullName).Append('\n'); } } Assert.Empty(unusedTypes); } [Fact] public void TypesInInternalNamespaceShouldBeInternalTest() { var excludes = new HashSet<Type> { typeof(NLog.Internal.Xamarin.PreserveAttribute), #pragma warning disable CS0618 // Type or member is obsolete typeof(NLog.Internal.Fakeables.IAppDomain), // TODO NLog 5 - handle IAppDomain #pragma warning restore CS0618 // Type or member is obsolete }; var notInternalTypes = allTypes .Where(t => t.Namespace != null && t.Namespace.Contains(".Internal")) .Where(t => !t.IsNested && (t.IsVisible || t.IsPublic)) .Where(n => !excludes.Contains(n)) .Select(t => t.FullName) .ToList(); Assert.Empty(notInternalTypes); } private void IncrementUsageCount(Type type) { if (type.IsArray) { type = type.GetElementType(); } if (type.IsGenericType && !type.IsGenericTypeDefinition) { IncrementUsageCount(type.GetGenericTypeDefinition()); foreach (var parm in type.GetGenericArguments()) { IncrementUsageCount(parm); } return; } if (type.Assembly != nlogAssembly) { return; } if (typeUsageCount.ContainsKey(type)) { typeUsageCount[type]++; } } [Fact] public void TryGetRawValue_ThreadAgnostic_Attribute_Required() { foreach (Type type in allTypes) { if (typeof(NLog.Internal.IRawValue).IsAssignableFrom(type) && !type.IsInterface) { var threadAgnosticAttribute = type.GetCustomAttribute<ThreadAgnosticAttribute>(); Assert.True(!(threadAgnosticAttribute is null), $"{type.ToString()} cannot implement IRawValue"); } } } [Fact] public void IStringValueRenderer_AppDomainFixedOutput_Attribute_NotRequired() { foreach (Type type in allTypes) { if (typeof(NLog.Internal.IStringValueRenderer).IsAssignableFrom(type) && !type.IsInterface) { var appDomainFixedOutputAttribute = type.GetCustomAttribute<AppDomainFixedOutputAttribute>(); Assert.True(appDomainFixedOutputAttribute is null, $"{type.ToString()} should not implement IStringValueRenderer"); } } } [Fact] public void RequiredConfigOptionMustBeClass() { foreach (Type type in allTypes) { var properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); foreach (var prop in properties) { var requiredParameter = prop.GetCustomAttribute<NLog.Config.RequiredParameterAttribute>(); if (requiredParameter != null) { Assert.True(prop.PropertyType.IsClass, type.Name); } } } } [Fact] public void SingleDefaultConfigOption() { string prevDefaultPropertyName = null; foreach (Type type in allTypes) { prevDefaultPropertyName = null; var properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); foreach (var prop in properties) { var defaultParameter = prop.GetCustomAttribute<DefaultParameterAttribute>(); if (defaultParameter != null) { Assert.True(prevDefaultPropertyName == null, prevDefaultPropertyName?.ToString()); prevDefaultPropertyName = prop.Name; Assert.True(type.IsSubclassOf(typeof(NLog.LayoutRenderers.LayoutRenderer)), type.ToString()); } } } } [Fact] public void AppDomainFixedOutput_Attribute_EnsureThreadAgnostic() { foreach (Type type in allTypes) { var appDomainFixedOutputAttribute = type.GetCustomAttribute<AppDomainFixedOutputAttribute>(); if (appDomainFixedOutputAttribute != null) { var threadAgnosticAttribute = type.GetCustomAttribute<ThreadAgnosticAttribute>(); Assert.True(!(threadAgnosticAttribute is null), $"{type.ToString()} should also have [ThreadAgnostic]"); } } } [Fact] public void WrapperLayoutRenderer_EnsureThreadAgnostic() { foreach (Type type in allTypes) { if (typeof(NLog.LayoutRenderers.Wrappers.WrapperLayoutRendererBase).IsAssignableFrom(type)) { if (type.IsAbstract || !type.IsPublic) continue; // skip non-concrete types, enumerations, and private nested types Assert.True(type.IsDefined(typeof(ThreadAgnosticAttribute), true), $"{type.ToString()} is missing [ThreadAgnostic] attribute."); } } } [Fact] public void ValidateLayoutRendererTypeAlias() { // These class-names should be repaired with next major version bump // Do NOT add more incorrect class-names to this exlusion-list HashSet<string> oldFaultyClassNames = new HashSet<string>() { "GarbageCollectorInfoLayoutRenderer", "ScopeContextNestedStatesLayoutRenderer", "ScopeContextPropertyLayoutRenderer", "ScopeContextTimingLayoutRenderer", "ScopeContextIndentLayoutRenderer", "TraceActivityIdLayoutRenderer", "SpecialFolderApplicationDataLayoutRenderer", "SpecialFolderCommonApplicationDataLayoutRenderer", "SpecialFolderLocalApplicationDataLayoutRenderer", "DirectorySeparatorLayoutRenderer", "LiteralWithRawValueLayoutRenderer", "LocalIpAddressLayoutRenderer", "VariableLayoutRenderer", "ObjectPathRendererWrapper", "PaddingLayoutRendererWrapper", }; foreach (Type type in allTypes) { if (type.IsSubclassOf(typeof(NLog.LayoutRenderers.LayoutRenderer))) { var layoutRendererAttributes = type.GetCustomAttributes<NLog.LayoutRenderers.LayoutRendererAttribute>()?.ToArray() ?? NLog.Internal.ArrayHelper.Empty<NLog.LayoutRenderers.LayoutRendererAttribute>(); if (layoutRendererAttributes.Length == 0) { if (type != typeof(NLog.LayoutRenderers.FuncLayoutRenderer) && type != typeof(NLog.LayoutRenderers.FuncThreadAgnosticLayoutRenderer)) { Assert.True(type.IsAbstract, $"{type} without LayoutRendererAttribute must be abstract"); } } else { Assert.False(type.IsAbstract, $"{type} with LayoutRendererAttribute cannot be abstract"); if (!oldFaultyClassNames.Contains(type.Name)) { if (type.IsSubclassOf(typeof(NLog.LayoutRenderers.Wrappers.WrapperLayoutRendererBase))) { var typeAlias = layoutRendererAttributes.First().Name.Replace("-", ""); Assert.Equal(typeAlias + "LayoutRendererWrapper", type.Name, StringComparer.OrdinalIgnoreCase); } else { var typeAlias = layoutRendererAttributes.First().Name.Replace("-", ""); Assert.Equal(typeAlias + "LayoutRenderer", type.Name, StringComparer.OrdinalIgnoreCase); } } } } } } [Fact] public void ValidateConfigurationItemFactory() { ConfigurationItemFactory.Default = null; // Reset var missingTypes = new List<string>(); foreach (Type type in allTypes) { if (!type.IsPublic || !type.IsClass || type.IsAbstract) continue; if (typeof(NLog.Targets.Target).IsAssignableFrom(type)) { var configAttribs = type.GetCustomAttributes<NLog.Targets.TargetAttribute>(false); Assert.NotEmpty(configAttribs); foreach (var configName in configAttribs) { if (!ConfigurationItemFactory.Default.TargetFactory.TryCreateInstance(configName.Name, out var target)) { Console.WriteLine(configName.Name); missingTypes.Add(configName.Name); } else if (type != target.GetType()) { Console.WriteLine(type.Name); missingTypes.Add(type.Name); } } } else if (typeof(NLog.Layouts.Layout).IsAssignableFrom(type)) { if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(NLog.Layouts.Layout<>))) continue; if (type == typeof(NLog.Layouts.XmlElement)) continue; var configAttribs = type.GetCustomAttributes<NLog.Layouts.LayoutAttribute>(false); Assert.NotEmpty(configAttribs); foreach (var configName in configAttribs) { if (!ConfigurationItemFactory.Default.LayoutFactory.TryCreateInstance(configName.Name, out var layout)) { Console.WriteLine(configName.Name); missingTypes.Add(configName.Name); } else if (type != layout.GetType()) { Console.WriteLine(type.Name); missingTypes.Add(type.Name); } } } else if (typeof(NLog.LayoutRenderers.LayoutRenderer).IsAssignableFrom(type)) { if (type == typeof(NLog.LayoutRenderers.FuncLayoutRenderer) || type == typeof(NLog.LayoutRenderers.FuncThreadAgnosticLayoutRenderer)) continue; var configAttribs = type.GetCustomAttributes<NLog.LayoutRenderers.LayoutRendererAttribute>(false); Assert.NotEmpty(configAttribs); foreach (var configName in configAttribs) { if (!ConfigurationItemFactory.Default.LayoutRendererFactory.TryCreateInstance(configName.Name, out var layoutRenderer)) { Console.WriteLine(configName.Name); missingTypes.Add(configName.Name); } else if (type != layoutRenderer.GetType()) { Console.WriteLine(type.Name); missingTypes.Add(type.Name); } } if (typeof(NLog.LayoutRenderers.Wrappers.WrapperLayoutRendererBase).IsAssignableFrom(type)) { var wrapperAttribs = type.GetCustomAttributes<NLog.LayoutRenderers.AmbientPropertyAttribute>(false); if (wrapperAttribs?.Any() == true) { foreach (var ambientName in wrapperAttribs) { if (!ConfigurationItemFactory.Default.AmbientRendererFactory.TryCreateInstance(ambientName.Name, out var layoutRenderer)) { Console.WriteLine(ambientName.Name); missingTypes.Add(ambientName.Name); } else if (type != layoutRenderer.GetType()) { Console.WriteLine(type.Name); missingTypes.Add(type.Name); } } } } } else if (typeof(NLog.Filters.Filter).IsAssignableFrom(type)) { if (type == typeof(NLog.Filters.WhenMethodFilter)) continue; var configAttribs = type.GetCustomAttributes<NLog.Filters.FilterAttribute>(false); Assert.NotEmpty(configAttribs); foreach (var configName in configAttribs) { if (!ConfigurationItemFactory.Default.FilterFactory.TryCreateInstance(configName.Name, out var filter)) { Console.WriteLine(configName.Name); missingTypes.Add(configName.Name); } else if (type != filter.GetType()) { Console.WriteLine(type.Name); missingTypes.Add(type.Name); } } } else if (typeof(NLog.Time.TimeSource).IsAssignableFrom(type)) { var configAttribs = type.GetCustomAttributes<NLog.Time.TimeSourceAttribute>(false); Assert.NotEmpty(configAttribs); foreach (var configName in configAttribs) { if (!ConfigurationItemFactory.Default.TimeSourceFactory.TryCreateInstance(configName.Name, out var timeSource)) { Console.WriteLine(configName.Name); missingTypes.Add(configName.Name); } else if (type != timeSource.GetType()) { Console.WriteLine(type.Name); missingTypes.Add(type.Name); } } } } Assert.Empty(missingTypes); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Linq; using System.Security.Authentication; using NLog.Config; using NLog.Internal.NetworkSenders; using NLog.Targets; using NLog.UnitTests.Mocks; using NSubstitute; using Xunit; namespace NLog.UnitTests.Internal.NetworkSenders { public class HttpNetworkSenderTests : NLogTestBase { /// <summary> /// Test <see cref="HttpNetworkSender"/> via <see cref="NetworkTarget"/> /// </summary> [Fact] [Obsolete("WebRequest is obsolete. Use HttpClient instead.")] public void HttpNetworkSenderViaNetworkTargetTest() { // Arrange var networkTarget = new NetworkTarget("target1") { Address = "http://test.with.mock", Layout = "${logger}|${message}|${exception}", MaxQueueSize = 1234, OnQueueOverflow = NetworkTargetQueueOverflowAction.Block, MaxMessageSize = 0, }; var webRequestMock = new WebRequestMock(); var networkSenderFactoryMock = CreateNetworkSenderFactoryMock(webRequestMock); networkTarget.SenderFactory = networkSenderFactoryMock; var logFactory = new LogFactory(); var config = new LoggingConfiguration(logFactory); config.AddRuleForAllLevels(networkTarget); logFactory.Configuration = config; var logger = logFactory.GetLogger("HttpHappyPathTestLogger"); // Act logger.Info("test message1"); logFactory.Flush(); // Assert var mock = webRequestMock; var requestedString = mock.GetRequestContentAsString(); Assert.Equal("http://test.with.mock/", mock.RequestedAddress.ToString()); Assert.Equal("HttpHappyPathTestLogger|test message1|", requestedString); Assert.Equal("POST", mock.Method); networkSenderFactoryMock.Received(1).Create("http://test.with.mock", 1234, NetworkTargetQueueOverflowAction.Block, 0, SslProtocols.None, new TimeSpan()); // Cleanup mock.Dispose(); } [Fact] [Obsolete("WebRequest is obsolete. Use HttpClient instead.")] public void HttpNetworkSenderViaNetworkTargetRecoveryTest() { // Arrange var networkTarget = new NetworkTarget("target1") { Address = "http://test.with.mock", Layout = "${logger}|${message}|${exception}", MaxQueueSize = 1234, OnQueueOverflow = NetworkTargetQueueOverflowAction.Block, MaxMessageSize = 0, }; var webRequestMock = new WebRequestMock(); webRequestMock.FirstRequestMustFail = true; var networkSenderFactoryMock = CreateNetworkSenderFactoryMock(webRequestMock); networkTarget.SenderFactory = networkSenderFactoryMock; var logFactory = new LogFactory(); var config = new LoggingConfiguration(logFactory); config.AddRuleForAllLevels(networkTarget); logFactory.Configuration = config; var logger = logFactory.GetLogger("HttpHappyPathTestLogger"); // Act logger.Info("test message1"); // Will fail after short delay logger.Info("test message2"); // Will be queued and sent after short delay logFactory.Flush(); // Assert var mock = webRequestMock; var requestedString = mock.GetRequestContentAsString(); Assert.Equal("http://test.with.mock/", mock.RequestedAddress.ToString()); Assert.Equal("HttpHappyPathTestLogger|test message2|", requestedString); Assert.Equal("POST", mock.Method); networkSenderFactoryMock.Received(1).Create("http://test.with.mock", 1234, NetworkTargetQueueOverflowAction.Block, 0, SslProtocols.None, new TimeSpan()); // Only created one HttpNetworkSender // Cleanup mock.Dispose(); } [Obsolete("WebRequest is obsolete. Use HttpClient instead.")] private static INetworkSenderFactory CreateNetworkSenderFactoryMock(WebRequestMock webRequestMock) { var networkSenderFactoryMock = Substitute.For<INetworkSenderFactory>(); networkSenderFactoryMock.Create(Arg.Any<string>(), Arg.Any<int>(), Arg.Any<NetworkTargetQueueOverflowAction>(), Arg.Any<int>(), Arg.Any<SslProtocols>(), Arg.Any<TimeSpan>()) .Returns(url => new HttpNetworkSender(url.Arg<string>()) { HttpRequestFactory = new WebRequestFactoryMock(webRequestMock) }); return networkSenderFactoryMock; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 namespace NLog.Targets { using System; using System.Collections.Generic; using System.IO; using System.Text; /// <summary> /// Controls the text and color formatting for <see cref="ColoredConsoleTarget"/> /// </summary> internal interface IColoredConsolePrinter { /// <summary> /// Creates a TextWriter for the console to start building a colored text message /// </summary> /// <param name="consoleStream">Active console stream</param> /// <param name="reusableBuilder">Optional StringBuilder to optimize performance</param> /// <returns>TextWriter for the console</returns> TextWriter AcquireTextWriter(TextWriter consoleStream, StringBuilder reusableBuilder); /// <summary> /// Releases the TextWriter for the console after having built a colored text message (Restores console colors) /// </summary> /// <param name="consoleWriter">Colored TextWriter</param> /// <param name="consoleStream">Active console stream</param> /// <param name="oldForegroundColor">Original foreground color for console (If changed)</param> /// <param name="oldBackgroundColor">Original background color for console (If changed)</param> /// <param name="flush">Flush TextWriter</param> void ReleaseTextWriter(TextWriter consoleWriter, TextWriter consoleStream, ConsoleColor? oldForegroundColor, ConsoleColor? oldBackgroundColor, bool flush); /// <summary> /// Changes foreground color for the Colored TextWriter /// </summary> /// <param name="consoleWriter">Colored TextWriter</param> /// <param name="foregroundColor">New foreground color for the console</param> /// <param name="oldForegroundColor">Old previous backgroundColor color for the console</param> /// <returns>Old foreground color for the console</returns> ConsoleColor? ChangeForegroundColor(TextWriter consoleWriter, ConsoleColor? foregroundColor, ConsoleColor? oldForegroundColor = null); /// <summary> /// Changes backgroundColor color for the Colored TextWriter /// </summary> /// <param name="consoleWriter">Colored TextWriter</param> /// <param name="backgroundColor">New backgroundColor color for the console</param> /// <param name="oldBackgroundColor">Old previous backgroundColor color for the console</param> /// <returns>Old backgroundColor color for the console</returns> ConsoleColor? ChangeBackgroundColor(TextWriter consoleWriter, ConsoleColor? backgroundColor, ConsoleColor? oldBackgroundColor = null); /// <summary> /// Restores console colors back to their original state /// </summary> /// <param name="consoleWriter">Colored TextWriter</param> /// <param name="foregroundColor">Original foregroundColor color for the console</param> /// <param name="backgroundColor">Original backgroundColor color for the console</param> void ResetDefaultColors(TextWriter consoleWriter, ConsoleColor? foregroundColor, ConsoleColor? backgroundColor); /// <summary> /// Writes multiple characters to console in one operation (faster) /// </summary> /// <param name="consoleWriter">Colored TextWriter</param> /// <param name="text">Output Text</param> /// <param name="index">Start Index</param> /// <param name="endIndex">End Index</param> void WriteSubString(TextWriter consoleWriter, string text, int index, int endIndex); /// <summary> /// Writes single character to console /// </summary> /// <param name="consoleWriter">Colored TextWriter</param> /// <param name="text">Output Text</param> void WriteChar(TextWriter consoleWriter, char text); /// <summary> /// Writes whole string and completes with newline /// </summary> /// <param name="consoleWriter">Colored TextWriter</param> /// <param name="text">Output Text</param> void WriteLine(TextWriter consoleWriter, string text); /// <summary> /// Default row highlight rules for the console printer /// </summary> IList<ConsoleRowHighlightingRule> DefaultConsoleRowHighlightingRules { get; } } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using NLog.Config; /// <summary> /// Extension methods to setup general option before loading NLog LoggingConfiguration /// </summary> public static class SetupLogFactoryBuilderExtensions { /// <summary> /// Configures the global time-source used for all logevents /// </summary> /// <remarks> /// Available by default: <see cref="NLog.Time.AccurateLocalTimeSource"/>, <see cref="NLog.Time.AccurateUtcTimeSource"/>, <see cref="NLog.Time.FastLocalTimeSource"/>, <see cref="NLog.Time.FastUtcTimeSource"/> /// </remarks> public static ISetupLogFactoryBuilder SetTimeSource(this ISetupLogFactoryBuilder configBuilder, NLog.Time.TimeSource timeSource) { NLog.Time.TimeSource.Current = timeSource; return configBuilder; } /// <summary> /// Configures the global time-source used for all logevents to use <see cref="NLog.Time.AccurateUtcTimeSource"/> /// </summary> public static ISetupLogFactoryBuilder SetTimeSourcAccurateUtc(this ISetupLogFactoryBuilder configBuilder) { return configBuilder.SetTimeSource(NLog.Time.AccurateUtcTimeSource.Current); } /// <summary> /// Configures the global time-source used for all logevents to use <see cref="NLog.Time.AccurateLocalTimeSource"/> /// </summary> public static ISetupLogFactoryBuilder SetTimeSourcAccurateLocal(this ISetupLogFactoryBuilder configBuilder) { return configBuilder.SetTimeSource(NLog.Time.AccurateLocalTimeSource.Current); } /// <summary> /// Updates the dictionary <see cref="GlobalDiagnosticsContext"/> ${gdc:item=} with the name-value-pair /// </summary> public static ISetupLogFactoryBuilder SetGlobalContextProperty(this ISetupLogFactoryBuilder configBuilder, string name, object value) { GlobalDiagnosticsContext.Set(name, value); return configBuilder; } /// <summary> /// Sets whether to automatically call <see cref="LogFactory.Shutdown"/> on AppDomain.Unload or AppDomain.ProcessExit /// </summary> public static ISetupLogFactoryBuilder SetAutoShutdown(this ISetupLogFactoryBuilder configBuilder, bool enabled) { configBuilder.LogFactory.AutoShutdown = enabled; return configBuilder; } /// <summary> /// Sets the default culture info to use as <see cref="LogEventInfo.FormatProvider"/>. /// </summary> public static ISetupLogFactoryBuilder SetDefaultCultureInfo(this ISetupLogFactoryBuilder configBuilder, System.Globalization.CultureInfo cultureInfo) { configBuilder.LogFactory.DefaultCultureInfo = cultureInfo; return configBuilder; } /// <summary> /// Sets the global log level threshold. Log events below this threshold are not logged. /// </summary> public static ISetupLogFactoryBuilder SetGlobalThreshold(this ISetupLogFactoryBuilder configBuilder, LogLevel logLevel) { configBuilder.LogFactory.GlobalThreshold = logLevel; return configBuilder; } /// <summary> /// Gets or sets a value indicating whether <see cref="NLogConfigurationException"/> should be thrown on configuration errors /// </summary> public static ISetupLogFactoryBuilder SetThrowConfigExceptions(this ISetupLogFactoryBuilder configBuilder, bool enabled) { configBuilder.LogFactory.ThrowConfigExceptions = enabled; return configBuilder; } /// <summary> /// Mark Assembly as hidden, so Assembly methods are excluded when resolving ${callsite} from StackTrace /// </summary> public static ISetupLogFactoryBuilder AddCallSiteHiddenAssembly(this ISetupLogFactoryBuilder configBuilder, System.Reflection.Assembly assembly) { LogManager.AddHiddenAssembly(assembly); return configBuilder; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System.Diagnostics; using System.Text; using NLog.Config; using NLog.Internal; using NLog.Layouts; /// <summary> /// Stack trace renderer. /// </summary> [LayoutRenderer("stacktrace")] [ThreadAgnostic] public class StackTraceLayoutRenderer : LayoutRenderer, IUsesStackTrace { /// <summary> /// Gets or sets the output format of the stack trace. /// </summary> /// <docgen category='Layout Options' order='10' /> public StackTraceFormat Format { get; set; } = StackTraceFormat.Flat; /// <summary> /// Gets or sets the number of top stack frames to be rendered. /// </summary> /// <docgen category='Layout Options' order='10' /> public int TopFrames { get; set; } = 3; /// <summary> /// Gets or sets the number of frames to skip. /// </summary> /// <docgen category='Layout Options' order='10' /> public int SkipFrames { get; set; } /// <summary> /// Gets or sets the stack frame separator string. /// </summary> /// <docgen category='Layout Options' order='10' /> public string Separator { get => _separator?.OriginalText; set => _separator = new SimpleLayout(value ?? ""); } private SimpleLayout _separator = new SimpleLayout(" => "); /// <summary> /// Logger should capture StackTrace, if it was not provided manually /// </summary> /// <docgen category='Layout Options' order='10' /> public bool CaptureStackTrace { get; set; } = true; /// <summary> /// Gets or sets whether to render StackFrames in reverse order /// </summary> /// <docgen category='Layout Options' order='10' /> public bool Reverse { get; set; } /// <inheritdoc/> StackTraceUsage IUsesStackTrace.StackTraceUsage { get { if (!CaptureStackTrace) return StackTraceUsage.None; if (Format == StackTraceFormat.Raw) return StackTraceUsage.Max; return StackTraceUsage.WithStackTrace; } } /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (logEvent.StackTrace is null) return; int startingFrame = logEvent.UserStackFrameNumber + TopFrames - 1; if (startingFrame >= logEvent.StackTrace.GetFrameCount()) { startingFrame = logEvent.StackTrace.GetFrameCount() - 1; } int endingFrame = logEvent.UserStackFrameNumber + SkipFrames; StackFrameList stackFrameList = new StackFrameList(logEvent.StackTrace, startingFrame, endingFrame, Reverse); switch (Format) { case StackTraceFormat.Raw: AppendRaw(builder, stackFrameList, logEvent); break; case StackTraceFormat.Flat: AppendFlat(builder, stackFrameList, logEvent); break; case StackTraceFormat.DetailedFlat: AppendDetailedFlat(builder, stackFrameList, logEvent); break; } } private struct StackFrameList { private readonly StackTrace _stackTrace; private readonly int _startingFrame; private readonly int _endingFrame; private readonly bool _reverse; public int Count => _startingFrame - _endingFrame; public StackFrame this[int index] { get { int orderedIndex = _reverse ? _endingFrame + index + 1 : _startingFrame - index; return _stackTrace.GetFrame(orderedIndex); } } public StackFrameList(StackTrace stackTrace, int startingFrame, int endingFrame, bool reverse) { _stackTrace = stackTrace; _startingFrame = startingFrame; _endingFrame = endingFrame - 1; _reverse = reverse; } } private void AppendRaw(StringBuilder builder, StackFrameList stackFrameList, LogEventInfo logEvent) { string separator = null; for (int i = 0; i < stackFrameList.Count; ++i) { builder.Append(separator); StackFrame f = stackFrameList[i]; builder.Append(f.ToString()); separator = separator ?? _separator?.Render(logEvent) ?? string.Empty; } } private void AppendFlat(StringBuilder builder, StackFrameList stackFrameList, LogEventInfo logEvent) { string separator = null; bool first = true; for (int i = 0; i < stackFrameList.Count; ++i) { var method = StackTraceUsageUtils.GetStackMethod(stackFrameList[i]); if (method is null) { continue; // Net Native can have StackFrames without managed methods } if (!first) { separator = separator ?? _separator?.Render(logEvent) ?? string.Empty; builder.Append(separator); } var type = method.DeclaringType; if (type is null) { builder.Append("<no type>"); } else { builder.Append(type.Name); } builder.Append('.'); builder.Append(method.Name); first = false; } } private void AppendDetailedFlat(StringBuilder builder, StackFrameList stackFrameList, LogEventInfo logEvent) { string separator = null; bool first = true; for (int i = 0; i < stackFrameList.Count; ++i) { var method = StackTraceUsageUtils.GetStackMethod(stackFrameList[i]); if (method is null) { continue; // Net Native can have StackFrames without managed methods } if (!first) { separator = separator ?? _separator?.Render(logEvent) ?? string.Empty; builder.Append(separator); } builder.Append('['); builder.Append(method); builder.Append(']'); first = false; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Internal.NetworkSenders { using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using NLog.Internal.NetworkSenders; using Xunit; public class TcpNetworkSenderTests : NLogTestBase { [Fact] public void TcpHappyPathTest() { foreach (bool async in new[] { false, true }) { var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified) { Async = async, }; sender.Initialize(); byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog"); var exceptions = new List<Exception>(); for (int i = 1; i < 8; i *= 2) { sender.Send( buffer, 0, i, ex => { lock (exceptions) exceptions.Add(ex); }); } var mre = new ManualResetEvent(false); sender.FlushAsync(ex => { lock (exceptions) { exceptions.Add(ex); } mre.Set(); }); Assert.True(mre.WaitOne(10000), "Network Flush not completed"); var actual = sender.Log.ToString(); Assert.Contains("Parse endpoint address tcp://hostname:123/ Unspecified", actual); Assert.Contains("create socket InterNetwork Stream Tcp", actual); Assert.Contains("connect async to 0.0.0.0:123", actual); Assert.Contains("send async 0 1 'q'", actual); Assert.Contains("send async 0 2 'qu'", actual); Assert.Contains("send async 0 4 'quic'", actual); mre.Reset(); for (int i = 1; i < 8; i *= 2) { sender.Send( buffer, 0, i, ex => { lock (exceptions) exceptions.Add(ex); }); } sender.Close(ex => { lock (exceptions) { exceptions.Add(ex); } mre.Set(); }); Assert.True(mre.WaitOne(10000), "Network Close not completed"); actual = sender.Log.ToString(); Assert.Contains("Parse endpoint address tcp://hostname:123/ Unspecified", actual); Assert.Contains("create socket InterNetwork Stream Tcp", actual); Assert.Contains("connect async to 0.0.0.0:123", actual); Assert.Contains("send async 0 1 'q'", actual); Assert.Contains("send async 0 2 'qu'", actual); Assert.Contains("send async 0 4 'quic'", actual); Assert.Contains("send async 0 1 'q'", actual); Assert.Contains("send async 0 2 'qu'", actual); Assert.Contains("send async 0 4 'quic'", actual); Assert.Contains("close", actual); foreach (var ex in exceptions) { Assert.Null(ex); } } } [Fact] public void TcpProxyTest() { var sender = new TcpNetworkSender("tcp://foo:1234", AddressFamily.Unspecified); var socket = sender.CreateSocket("foo", AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Assert.IsType<SocketProxy>(socket); } [Fact] public void TcpConnectFailureTest() { var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified) { ConnectFailure = 1, Async = true, }; sender.Initialize(); byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog"); var exceptions = new List<Exception>(); var allSent = new ManualResetEvent(false); for (int i = 1; i < 8; i++) { sender.Send( buffer, 0, i, ex => { lock (exceptions) { exceptions.Add(ex); if (exceptions.Count == 7) { allSent.Set(); } } }); } Assert.True(allSent.WaitOne(10000), "Network Write not completed"); var mre = new ManualResetEvent(false); sender.FlushAsync(ex => mre.Set()); Assert.True(mre.WaitOne(10000), "Network Flush not completed"); var actual = sender.Log.ToString(); Assert.Contains("Parse endpoint address tcp://hostname:123/ Unspecified", actual); Assert.Contains("create socket InterNetwork Stream Tcp", actual); Assert.Contains("connect async to 0.0.0.0:123", actual); Assert.Contains("failed", actual); foreach (var ex in exceptions) { Assert.NotNull(ex); } } [Fact] public void TcpSendFailureTest() { var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified) { SendFailureIn = 3, // will cause failure on 3rd send Async = true, }; sender.Initialize(); byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog"); var exceptions = new Exception[9]; var writeFinished = new ManualResetEvent(false); int remaining = exceptions.Length; for (int i = 1; i < 10; i++) { int pos = i - 1; sender.Send( buffer, 0, i, ex => { lock (exceptions) { exceptions[pos] = ex; if (--remaining == 0) { writeFinished.Set(); } } }); } var mre = new ManualResetEvent(false); Assert.True(writeFinished.WaitOne(10000), "Network Write not completed"); sender.Close(ex => mre.Set()); Assert.True(mre.WaitOne(10000), "Network Flush not completed"); var actual = sender.Log.ToString(); Assert.Contains("Parse endpoint address tcp://hostname:123/ Unspecified", actual); Assert.Contains("create socket InterNetwork Stream Tcp", actual); Assert.Contains("connect async to 0.0.0.0:123", actual); Assert.Contains("send async 0 1 'q'", actual); Assert.Contains("send async 0 2 'qu'", actual); Assert.Contains("send async 0 3 'qui'", actual); Assert.Contains("failed", actual); Assert.Contains("close", actual); for (int i = 0; i < exceptions.Length; ++i) { if (i < 2) { Assert.Null(exceptions[i]); } else { Assert.NotNull(exceptions[i]); } } } internal class MyTcpNetworkSender : TcpNetworkSender { public StringWriter Log { get; set; } public MyTcpNetworkSender(string url, AddressFamily addressFamily) : base(url, addressFamily) { Log = new StringWriter(); } protected internal override ISocket CreateSocket(string host, AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { return new MockSocket(addressFamily, socketType, protocolType, this); } protected override IPAddress ResolveIpAddress(Uri uri, AddressFamily addressFamily) { Log.WriteLine("Parse endpoint address {0} {1}", uri, addressFamily); return IPAddress.Any; } public int ConnectFailure { get; set; } public bool Async { get; set; } public int SendFailureIn { get; set; } } internal sealed class MockSocket : ISocket { private readonly MyTcpNetworkSender sender; private readonly StringWriter log; private bool faulted; public MockSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, MyTcpNetworkSender sender) { this.sender = sender; log = sender.Log; log.WriteLine("create socket {0} {1} {2}", addressFamily, socketType, protocolType); } public bool ConnectAsync(SocketAsyncEventArgs args) { log.WriteLine("connect async to {0}", args.RemoteEndPoint); lock (this) { if (sender.ConnectFailure > 0) { sender.ConnectFailure--; faulted = true; args.SocketError = SocketError.SocketError; log.WriteLine("failed"); } } return InvokeCallback(args); } private bool InvokeCallback(SocketAsyncEventArgs args) { lock (this) { var args2 = args as TcpNetworkSender.MySocketAsyncEventArgs; if (sender.Async) { ThreadPool.QueueUserWorkItem(s => { Thread.Sleep(10); args2.RaiseCompleted(); }); return true; } else { return false; } } } public void Close() { lock (this) { log.WriteLine("close"); } } public bool SendAsync(SocketAsyncEventArgs args) { lock (this) { log.WriteLine("send async {0} {1} '{2}'", args.Offset, args.Count, Encoding.UTF8.GetString(args.Buffer, args.Offset, args.Count)); if (sender.SendFailureIn > 0) { sender.SendFailureIn--; if (sender.SendFailureIn == 0) { faulted = true; } } if (faulted) { log.WriteLine("failed"); args.SocketError = SocketError.SocketError; } } return InvokeCallback(args); } public bool SendToAsync(SocketAsyncEventArgs args) { lock (this) { log.WriteLine("sendto async {0} {1} '{2}' {3}", args.Offset, args.Count, Encoding.UTF8.GetString(args.Buffer, args.Offset, args.Count), args.RemoteEndPoint); return InvokeCallback(args); } } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; [DebuggerDisplay("Count = {Count}")] internal class ThreadSafeDictionary<TKey, TValue> : IDictionary<TKey, TValue> { private readonly object _lockObject = new object(); private Dictionary<TKey, TValue> _dict; private Dictionary<TKey, TValue> _dictReadOnly; // Reset cache on change public ThreadSafeDictionary() :this(EqualityComparer<TKey>.Default) { } public ThreadSafeDictionary(IEqualityComparer<TKey> comparer) { _dict = new Dictionary<TKey, TValue>(comparer); } public ThreadSafeDictionary(ThreadSafeDictionary<TKey, TValue> source) { var sourceDictionary = source.GetReadOnlyDict(); _dict = new Dictionary<TKey, TValue>(sourceDictionary.Count, sourceDictionary.Comparer); foreach (var item in sourceDictionary) _dict.Add(item.Key, item.Value); } public TValue this[TKey key] { get => GetReadOnlyDict()[key]; set { lock (_lockObject) { GetWritableDict()[key] = value; } } } public IEqualityComparer<TKey> Comparer => _dict.Comparer; public ICollection<TKey> Keys => GetReadOnlyDict().Keys; public ICollection<TValue> Values => GetReadOnlyDict().Values; public int Count => GetReadOnlyDict().Count; public bool IsReadOnly => false; public void Add(TKey key, TValue value) { lock (_lockObject) { GetWritableDict().Add(key, value); } } public void Add(KeyValuePair<TKey, TValue> item) { lock (_lockObject) { GetWritableDict().Add(item.Key, item.Value); } } public void Clear() { lock (_lockObject) { GetWritableDict(true); } } public bool Contains(KeyValuePair<TKey, TValue> item) { return GetReadOnlyDict().Contains(item); } public bool ContainsKey(TKey key) { return GetReadOnlyDict().ContainsKey(key); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { ((IDictionary<TKey,TValue>)GetReadOnlyDict()).CopyTo(array, arrayIndex); } public void CopyFrom(IDictionary<TKey, TValue> source) { if (!ReferenceEquals(this, source) && source?.Count > 0) { lock (_lockObject) { var destDict = GetWritableDict(); foreach (var item in source) destDict[item.Key] = item.Value; } } } public bool Remove(TKey key) { lock (_lockObject) { return GetWritableDict().Remove(key); } } public bool Remove(KeyValuePair<TKey, TValue> item) { lock (_lockObject) { return GetWritableDict().Remove(item); } } public bool TryGetValue(TKey key, out TValue value) { return GetReadOnlyDict().TryGetValue(key, out value); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return GetReadOnlyDict().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetReadOnlyDict().GetEnumerator(); } public Enumerator GetEnumerator() { return new Enumerator(GetReadOnlyDict().GetEnumerator()); } public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>> { Dictionary<TKey, TValue>.Enumerator _enumerator; public Enumerator(Dictionary<TKey, TValue>.Enumerator enumerator) { _enumerator = enumerator; } public KeyValuePair<TKey, TValue> Current => _enumerator.Current; object IEnumerator.Current => _enumerator.Current; public void Dispose() { _enumerator.Dispose(); } public bool MoveNext() { return _enumerator.MoveNext(); } void IEnumerator.Reset() { ((IEnumerator)_enumerator).Reset(); } } private Dictionary<TKey, TValue> GetReadOnlyDict() { var readOnly = _dictReadOnly; if (readOnly is null) { lock (_lockObject) { readOnly = _dictReadOnly = _dict; } } return readOnly; } private IDictionary<TKey, TValue> GetWritableDict(bool clearDictionary = false) { if (_dictReadOnly is null) { // Never exposed the dictionary using enumerator, so immutable is not required if (clearDictionary) _dict.Clear(); return _dict; } var newDict = new Dictionary<TKey, TValue>(clearDictionary ? 0 : _dict.Count + 1, _dict.Comparer); if (!clearDictionary) { // Less allocation with enumerator than Dictionary-constructor foreach (var item in _dict) newDict[item.Key] = item.Value; } _dict = newDict; _dictReadOnly = null; return newDict; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections.Generic; using NLog.Common; using NLog.Config; using NLog.Filters; using NLog.Targets; /// <summary> /// Represents target with a chain of filters which determine /// whether logging should happen. /// </summary> internal class TargetWithFilterChain { internal static readonly TargetWithFilterChain[] NoTargetsByLevel = CreateLoggingConfiguration(); private static TargetWithFilterChain[] CreateLoggingConfiguration() => new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 2]; // +2 to include LogLevel.Off private MruCache<CallSiteKey, string> _callSiteClassNameCache; /// <summary> /// Initializes a new instance of the <see cref="TargetWithFilterChain" /> class. /// </summary> /// <param name="target">The target.</param> /// <param name="filterChain">The filter chain.</param> /// <param name="filterDefaultAction">Default action if none of the filters match.</param> public TargetWithFilterChain(Target target, IList<Filter> filterChain, FilterResult filterDefaultAction) { Target = target; FilterChain = filterChain; FilterDefaultAction = filterDefaultAction; } /// <summary> /// Gets the target. /// </summary> /// <value>The target.</value> public Target Target { get; } /// <summary> /// Gets the filter chain. /// </summary> /// <value>The filter chain.</value> public IList<Filter> FilterChain { get; } /// <summary> /// Gets or sets the next <see cref="TargetWithFilterChain"/> item in the chain. /// </summary> /// <value>The next item in the chain.</value> /// <example>This is for example the 'target2' logger in writeTo='target1,target2' </example> public TargetWithFilterChain NextInChain { get; set; } /// <summary> /// Gets the stack trace usage. /// </summary> /// <returns>A <see cref="StackTraceUsage" /> value that determines stack trace handling.</returns> public StackTraceUsage StackTraceUsage { get; private set; } /// <summary> /// Default action if none of the filters match. /// </summary> public FilterResult FilterDefaultAction { get; } internal StackTraceUsage PrecalculateStackTraceUsage() { var stackTraceUsage = StackTraceUsage.None; // find all objects which may need stack trace // and determine maximum if (Target != null) { stackTraceUsage = Target.StackTraceUsage; } //recurse into chain if not max if (NextInChain != null && (stackTraceUsage & StackTraceUsage.Max) != StackTraceUsage.Max) { var stackTraceUsageForChain = NextInChain.PrecalculateStackTraceUsage(); stackTraceUsage |= stackTraceUsageForChain; } StackTraceUsage = stackTraceUsage; return stackTraceUsage; } static internal TargetWithFilterChain[] BuildLoggerConfiguration(string loggerName, LoggingConfiguration configuration, LogLevel globalLogLevel) { if (configuration is null || LogLevel.Off.Equals(globalLogLevel)) return TargetWithFilterChain.NoTargetsByLevel; TargetWithFilterChain[] targetsByLevel = TargetWithFilterChain.CreateLoggingConfiguration(); TargetWithFilterChain[] lastTargetsByLevel = TargetWithFilterChain.CreateLoggingConfiguration(); bool[] suppressedLevels = new bool[LogLevel.MaxLevel.Ordinal + 1]; //no "System.InvalidOperationException: Collection was modified" var loggingRules = configuration.GetLoggingRulesThreadSafe(); bool targetsFound = GetTargetsByLevelForLogger(loggerName, loggingRules, globalLogLevel, targetsByLevel, lastTargetsByLevel, suppressedLevels); return targetsFound ? targetsByLevel : TargetWithFilterChain.NoTargetsByLevel; } static private bool GetTargetsByLevelForLogger(string name, List<LoggingRule> loggingRules, LogLevel globalLogLevel, TargetWithFilterChain[] targetsByLevel, TargetWithFilterChain[] lastTargetsByLevel, bool[] suppressedLevels) { bool targetsFound = false; foreach (LoggingRule rule in loggingRules) { if (!rule.NameMatches(name)) { continue; } targetsFound = AddTargetsFromLoggingRule(rule, name, globalLogLevel, targetsByLevel, lastTargetsByLevel, suppressedLevels) || targetsFound; // Recursively analyze the child rules. if (rule.ChildRules.Count != 0) { targetsFound = GetTargetsByLevelForLogger(name, rule.GetChildRulesThreadSafe(), globalLogLevel, targetsByLevel, lastTargetsByLevel, suppressedLevels) || targetsFound; } } for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i) { TargetWithFilterChain tfc = targetsByLevel[i]; tfc?.PrecalculateStackTraceUsage(); } return targetsFound; } private static bool AddTargetsFromLoggingRule(LoggingRule rule, string loggerName, LogLevel globalLogLevel, TargetWithFilterChain[] targetsByLevel, TargetWithFilterChain[] lastTargetsByLevel, bool[] suppressedLevels) { bool targetsFound = false; bool duplicateTargetsFound = false; var finalMinLevel = rule.FinalMinLevel; var ruleLogLevels = rule.LogLevels; for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i) { if (SuppressLogLevel(rule, ruleLogLevels, finalMinLevel, globalLogLevel, i, ref suppressedLevels[i])) { continue; } foreach (Target target in rule.GetTargetsThreadSafe()) { targetsFound = true; var awf = CreateTargetChainFromLoggingRule(rule, target, targetsByLevel[i]); if (awf is null) { if (!duplicateTargetsFound) { InternalLogger.Warn("Logger: {0} configured with duplicate output to target: {1}. LoggingRule with NamePattern='{2}' and Level={3} has been skipped.", loggerName, target, rule.LoggerNamePattern, LogLevel.FromOrdinal(i)); } duplicateTargetsFound = true; continue; } if (lastTargetsByLevel[i] != null) { lastTargetsByLevel[i].NextInChain = awf; } else { targetsByLevel[i] = awf; } lastTargetsByLevel[i] = awf; } } return targetsFound; } private static bool SuppressLogLevel(LoggingRule rule, bool[] ruleLogLevels, LogLevel finalMinLevel, LogLevel globalLogLevel, int logLevelOrdinal, ref bool suppressedLevels) { if (logLevelOrdinal < globalLogLevel.Ordinal) { return true; } if (finalMinLevel is null) { if (suppressedLevels) { return true; } } else { suppressedLevels = finalMinLevel.Ordinal > logLevelOrdinal; } if (!ruleLogLevels[logLevelOrdinal]) { return true; } if (rule.Final) { suppressedLevels = true; } return false; } private static TargetWithFilterChain CreateTargetChainFromLoggingRule(LoggingRule rule, Target target, TargetWithFilterChain existingTargets) { var filterChain = rule.Filters.Count == 0 ? ArrayHelper.Empty<NLog.Filters.Filter>() : rule.Filters; var newTarget = new TargetWithFilterChain(target, filterChain, rule.FilterDefaultAction); if (existingTargets != null && newTarget.FilterChain.Count == 0) { for (TargetWithFilterChain afc = existingTargets; afc != null; afc = afc.NextInChain) { if (ReferenceEquals(target, afc.Target) && afc.FilterChain.Count == 0) { return null; // Duplicate Target } } } return newTarget; } internal bool TryCallSiteClassNameOptimization(StackTraceUsage stackTraceUsage, LogEventInfo logEvent) { if ((stackTraceUsage & (StackTraceUsage.WithCallSiteClassName | StackTraceUsage.WithStackTrace)) != StackTraceUsage.WithCallSiteClassName) return false; if (string.IsNullOrEmpty(logEvent.CallSiteInformation?.CallerFilePath)) return false; if (logEvent.HasStackTrace) return false; return true; } internal bool MustCaptureStackTrace(StackTraceUsage stackTraceUsage, LogEventInfo logEvent) { if (logEvent.HasStackTrace) return false; if ((stackTraceUsage & StackTraceUsage.WithStackTrace) != StackTraceUsage.None) return true; if ((stackTraceUsage & StackTraceUsage.WithCallSite) != StackTraceUsage.None && string.IsNullOrEmpty(logEvent.CallSiteInformation?.CallerMethodName) && string.IsNullOrEmpty(logEvent.CallSiteInformation?.CallerFilePath)) return true; // We don't have enough CallSiteInformation return false; } internal bool TryRememberCallSiteClassName(LogEventInfo logEvent) { if (string.IsNullOrEmpty(logEvent.CallSiteInformation?.CallerFilePath)) return false; string className = logEvent.CallSiteInformation.GetCallerClassName(null, true, true, true); if (string.IsNullOrEmpty(className)) return false; if (_callSiteClassNameCache is null) return false; string internClassName = logEvent.LoggerName == className ? logEvent.LoggerName : #if !NETSTANDARD1_3 && !NETSTANDARD1_5 string.Intern(className); // Single string-reference for all logging-locations for the same class #else className; #endif CallSiteKey callSiteKey = new CallSiteKey(logEvent.CallerMemberName, logEvent.CallerFilePath, logEvent.CallerLineNumber); return _callSiteClassNameCache.TryAddValue(callSiteKey, internClassName); } internal bool TryLookupCallSiteClassName(LogEventInfo logEvent, out string callSiteClassName) { callSiteClassName = logEvent.CallSiteInformation?.CallerClassName; if (!string.IsNullOrEmpty(callSiteClassName)) return true; if (_callSiteClassNameCache is null) { System.Threading.Interlocked.CompareExchange(ref _callSiteClassNameCache, new MruCache<CallSiteKey, string>(1000), null); } CallSiteKey callSiteKey = new CallSiteKey(logEvent.CallerMemberName, logEvent.CallerFilePath, logEvent.CallerLineNumber); return _callSiteClassNameCache.TryGetValue(callSiteKey, out callSiteClassName); } struct CallSiteKey : IEquatable<CallSiteKey> { public CallSiteKey(string methodName, string fileSourceName, int fileSourceLineNumber) { MethodName = methodName ?? string.Empty; FileSourceName = fileSourceName ?? string.Empty; FileSourceLineNumber = fileSourceLineNumber; } public readonly string MethodName; public readonly string FileSourceName; public readonly int FileSourceLineNumber; /// <summary> /// Serves as a hash function for a particular type. /// </summary> public override int GetHashCode() { return MethodName.GetHashCode() ^ FileSourceName.GetHashCode() ^ FileSourceLineNumber; } /// <summary> /// Determines if two objects are equal in value. /// </summary> /// <param name="obj">Other object to compare to.</param> /// <returns>True if objects are equal, false otherwise.</returns> public override bool Equals(object obj) { return obj is CallSiteKey key && Equals(key); } /// <summary> /// Determines if two objects of the same type are equal in value. /// </summary> /// <param name="other">Other object to compare to.</param> /// <returns>True if objects are equal, false otherwise.</returns> public bool Equals(CallSiteKey other) { return FileSourceLineNumber == other.FileSourceLineNumber && string.Equals(FileSourceName, other.FileSourceName, StringComparison.Ordinal) && string.Equals(MethodName, other.MethodName, StringComparison.Ordinal); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 && !NETSTANDARD1_5 namespace NLog.LayoutRenderers { using System; using System.IO; using System.Text; using NLog.Config; using NLog.Internal; /// <summary> /// System special folder path (includes My Documents, My Music, Program Files, Desktop, and more). /// </summary> [LayoutRenderer("specialfolder")] [AppDomainFixedOutput] [ThreadAgnostic] public class SpecialFolderLayoutRenderer : LayoutRenderer { /// <summary> /// Gets or sets the system special folder to use. /// </summary> /// <remarks> /// Full list of options is available at <a href="https://docs.microsoft.com/en-us/dotnet/api/system.environment.specialfolder">MSDN</a>. /// The most common ones are: /// <ul> /// <li><b>CommonApplicationData</b> - application data for all users.</li> /// <li><b>ApplicationData</b> - roaming application data for current user.</li> /// <li><b>LocalApplicationData</b> - non roaming application data for current user</li> /// <li><b>UserProfile</b> - Profile folder for current user</li> /// <li><b>DesktopDirectory</b> - Desktop-directory for current user</li> /// <li><b>MyDocuments</b> - My Documents-directory for current user</li> /// <li><b>System</b> - System directory</li> /// </ul> /// </remarks> /// <docgen category='Layout Options' order='10' /> [DefaultParameter] public Environment.SpecialFolder Folder { get; set; } /// <summary> /// Gets or sets the name of the file to be Path.Combine()'d with the directory name. /// </summary> /// <docgen category='Advanced Options' order='10' /> public string File { get; set; } /// <summary> /// Gets or sets the name of the directory to be Path.Combine()'d with the directory name. /// </summary> /// <docgen category='Advanced Options' order='10' /> public string Dir { get; set; } /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { string basePath = GetFolderPath(Folder); var path = PathHelpers.CombinePaths(basePath, Dir, File); builder.Append(path); } internal static string GetFolderPath(Environment.SpecialFolder folder) { try { var folderPath = Environment.GetFolderPath(folder); if (!string.IsNullOrEmpty(folderPath)) return folderPath; } catch { var folderPath = GetFolderPathFromEnvironment(folder); if (!string.IsNullOrEmpty(folderPath)) return folderPath; throw; } return GetFolderPathFromEnvironment(folder); } private static string GetFolderPathFromEnvironment(Environment.SpecialFolder folder) { try { var variableName = GetFolderWindowsEnvironmentVariable(folder); if (string.IsNullOrEmpty(variableName)) return string.Empty; if (!PlatformDetector.IsWin32) return string.Empty; // Fallback for Windows Nano: https://github.com/dotnet/runtime/issues/21430 var folderPath = Environment.GetEnvironmentVariable(variableName); return folderPath ?? string.Empty; } catch { return string.Empty; } } private static string GetFolderWindowsEnvironmentVariable(Environment.SpecialFolder folder) { switch (folder) { case Environment.SpecialFolder.CommonApplicationData: return "COMMONAPPDATA"; // Default user case Environment.SpecialFolder.LocalApplicationData: return "LOCALAPPDATA"; // Current user case Environment.SpecialFolder.ApplicationData: return "APPDATA"; // Current user #if !NET35 case Environment.SpecialFolder.UserProfile: return "USERPROFILE"; // Current user #endif default: return string.Empty; } } } } #endif<file_sep>Pull request management === Reviewing --- When reviewing a pull request, check the following: - Ensure the pull request has a good, descriptive name. - **Important:** Check for binary backwardscompatiblity. NB: new optional parameters are not binary compatible. - **Important:** set the Milestone. - Add the applicable Labels. Eg. - Part: `file-target`, `nlog-configuration` etc - Type: `bug`, `enhancement`, `feature`, `performance`. And `enhancement` is a change without functional impact. Small features are also labeled as `feature`. - Tests: `needs unittests`, `has unittests` - Status: `waiting for review`, `almost ready`, `ready for merge` - Set the Assignee. It must indicate who is currently holding the ball. For example, if you intend to review, assign to yourself. If, after the review, some changes need to be made, assign it back to the PR author. Applying --- Things to check before applying the PR. - Check if the comment of the PR has an `fixes ...` comment. - Check which documentation has to be done. Preferred to fix the documentation just before the merge of the PR> - Check for related issues and PR's - Double check binary backwardscompatiblity. - Add current milestone. Build Pipeline === For developing: the following platforms will be used: - net46;net45;net35;netstandard1.3;netstandard1.5;netstandard2.0 (see nlog.csproj) The build server will run unit-tests on both Windows and Linux platforms (see build.ps1 + run-tests.ps1) NuGet package management === ## Create NuGet packages See build.ps1 ## Versions - "BuildLastMajorVersion" should be `major.0.0`. In NLog 4.x - 4.y: 4.0.0 - "AssemblyFileVersion" should be: `major.minor.patch.appVeyorBuildVersion`, eg. 4.2.2.1251 for NLog 4.2.2 - "BuildVersion" should be: `major.minor.patch` where `.patch` is ommited when 0. E.g 4.0, 4.1, 4.1.1, 4.2 Example of correct version numbers in NuGet Package explorer: ![image](https://cloud.githubusercontent.com/assets/5808377/11546997/fbfad58a-9950-11e5-952d-f7369f747089.png) ## XSD file The XSD file of NLog.Schema is partly generated by "MakeNLogXSD" (inside tools). The enhances the following template: https://github.com/NLog/NLog/blob/master/tools/MakeNLogXSD/TemplateXSD.xml <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { /// <summary> /// Web Service Proxy Configuration Type /// </summary> public enum WebServiceProxyType { /// <summary> /// Default proxy configuration from app.config (System.Net.WebRequest.DefaultWebProxy) /// </summary> /// <example> /// Example of how to configure default proxy using app.config /// <code> /// &lt;system.net&gt; /// &lt;defaultProxy enabled = "true" useDefaultCredentials = "true" &gt; /// &lt;proxy usesystemdefault = "True" /&gt; /// &lt;/defaultProxy&gt; /// &lt;/system.net&gt; /// </code> /// </example> DefaultWebProxy, /// <summary> /// Automatic use of proxy with authentication (cached) /// </summary> AutoProxy, /// <summary> /// Disables use of proxy (fast) /// </summary> NoProxy, /// <summary> /// Custom proxy address (cached) /// </summary> ProxyAddress, } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Text; /// <summary> /// URL Encoding helper. /// </summary> internal static class UrlHelper { [Flags] public enum EscapeEncodingOptions { None = 0, /// <summary>Allow UnreservedMarks instead of ReservedMarks, as specified by chosen RFC</summary> UriString = 1, /// <summary>Use RFC2396 standard (instead of RFC3986)</summary> LegacyRfc2396 = 2, /// <summary>Should use lowercase when doing HEX escaping of special characters</summary> LowerCaseHex = 4, /// <summary>Replace space ' ' with '+' instead of '%20'</summary> SpaceAsPlus = 8, /// <summary>Skip UTF8 encoding, and prefix special characters with '%u'</summary> NLogLegacy = 16 | LegacyRfc2396 | LowerCaseHex | UriString, }; /// <summary> /// Escape unicode string data for use in http-requests /// </summary> /// <param name="source">unicode string-data to be encoded</param> /// <param name="target">target for the encoded result</param> /// <param name="options"><see cref="EscapeEncodingOptions"/>s for how to perform the encoding</param> public static void EscapeDataEncode(string source, StringBuilder target, EscapeEncodingOptions options) { if (string.IsNullOrEmpty(source)) return; bool isLowerCaseHex = Contains(options, EscapeEncodingOptions.LowerCaseHex); bool isSpaceAsPlus = Contains(options, EscapeEncodingOptions.SpaceAsPlus); bool isNLogLegacy = Contains(options, EscapeEncodingOptions.NLogLegacy); char[] charArray = null; byte[] byteArray = null; char[] hexChars = isLowerCaseHex ? hexLowerChars : hexUpperChars; for (int i = 0; i < source.Length; ++i) { char ch = source[i]; target.Append(ch); if (IsSimpleCharOrNumber(ch)) continue; if (isSpaceAsPlus && ch == ' ') { target[target.Length - 1] = '+'; continue; } if (IsAllowedChar(options, ch)) { continue; } if (isNLogLegacy) { HandleLegacyEncoding(target, ch, hexChars); continue; } if (charArray is null) charArray = new char[1]; charArray[0] = ch; if (byteArray is null) byteArray = new byte[8]; WriteWideChars(target, charArray, byteArray, hexChars); } } private static bool Contains(EscapeEncodingOptions options, EscapeEncodingOptions option) { return (options & option) == option; } /// <summary> /// Convert the wide-char into utf8-bytes, and then escape /// </summary> /// <param name="target"></param> /// <param name="charArray"></param> /// <param name="byteArray"></param> /// <param name="hexChars"></param> private static void WriteWideChars(StringBuilder target, char[] charArray, byte[] byteArray, char[] hexChars) { int byteCount = Encoding.UTF8.GetBytes(charArray, 0, 1, byteArray, 0); for (int j = 0; j < byteCount; ++j) { byte byteCh = byteArray[j]; if (j == 0) target[target.Length - 1] = '%'; else target.Append('%'); target.Append(hexChars[(byteCh & 0xf0) >> 4]); target.Append(hexChars[byteCh & 0xf]); } } private static void HandleLegacyEncoding(StringBuilder target, char ch, char[] hexChars) { if (ch < 256) { target[target.Length - 1] = '%'; target.Append(hexChars[(ch >> 4) & 0xF]); target.Append(hexChars[(ch >> 0) & 0xF]); } else { target[target.Length - 1] = '%'; target.Append('u'); target.Append(hexChars[(ch >> 12) & 0xF]); target.Append(hexChars[(ch >> 8) & 0xF]); target.Append(hexChars[(ch >> 4) & 0xF]); target.Append(hexChars[(ch >> 0) & 0xF]); } } /// <summary> /// Is allowed? /// </summary> /// <param name="options"></param> /// <param name="ch"></param> /// <returns></returns> private static bool IsAllowedChar(EscapeEncodingOptions options, char ch) { bool isUriString = (options & EscapeEncodingOptions.UriString) == EscapeEncodingOptions.UriString; bool isLegacyRfc2396 = (options & EscapeEncodingOptions.LegacyRfc2396) == EscapeEncodingOptions.LegacyRfc2396; if (isUriString) { if (!isLegacyRfc2396 && RFC3986UnreservedMarks.IndexOf(ch) >= 0) return true; if (isLegacyRfc2396 && RFC2396UnreservedMarks.IndexOf(ch) >= 0) return true; } else { if (!isLegacyRfc2396 && RFC3986ReservedMarks.IndexOf(ch) >= 0) return true; if (isLegacyRfc2396 && RFC2396ReservedMarks.IndexOf(ch) >= 0) return true; } return false; } /// <summary> /// Is a-z / A-Z / 0-9 /// </summary> /// <param name="ch"></param> /// <returns></returns> private static bool IsSimpleCharOrNumber(char ch) { if (ch >= 'a' && ch <= 'z') return true; if (ch >= 'A' && ch <= 'Z') return true; if (ch >= '0' && ch <= '9') return true; return false; } private const string RFC2396ReservedMarks = @";/?:@&=+$,"; private const string RFC3986ReservedMarks = @":/?#[]@!$&'()*+,;="; private const string RFC2396UnreservedMarks = @"-_.!~*'()"; private const string RFC3986UnreservedMarks = @"-._~"; private static readonly char[] hexUpperChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private static readonly char[] hexLowerChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; public static EscapeEncodingOptions GetUriStringEncodingFlags(bool escapeDataNLogLegacy, bool spaceAsPlus, bool escapeDataRfc3986) { EscapeEncodingOptions encodingOptions = EscapeEncodingOptions.UriString; if (escapeDataNLogLegacy) encodingOptions |= EscapeEncodingOptions.LowerCaseHex | EscapeEncodingOptions.NLogLegacy; else if (!escapeDataRfc3986) encodingOptions |= EscapeEncodingOptions.LowerCaseHex | EscapeEncodingOptions.LegacyRfc2396; if (spaceAsPlus) encodingOptions |= EscapeEncodingOptions.SpaceAsPlus; return encodingOptions; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Text; using NLog.LayoutRenderers; using Xunit; namespace NLog.UnitTests.LayoutRenderers { public class ProcessTimeLayoutRendererTests : NLogTestBase { [Theory] [InlineData(0, 1, 2, 30, 0, "01:02:30.000")] [InlineData(0, 1, 2, 30, 1, "01:02:30.001")] [InlineData(0, 1, 2, 30, 20, "01:02:30.020")] [InlineData(0, 11, 2, 30, 20, "11:02:30.020")] [InlineData(0, 50, 2, 30, 20, "02:02:30.020")] [InlineData(0, 1, 2, 30, 506, "01:02:30.506")] [InlineData(0, 1, 2, 30, -506, "01:02:29.494")] [InlineData(0, 0, 0, 0, -506, "00:00:00.000")] [InlineData(0, 0, 0, 0, 0, "00:00:00.000")] [InlineData(1, 0, 0, 0, 0, "00:00:00.000")] public void RenderTimeSpanTest(int day, int hour, int min, int sec, int milisec, string expected) { var time = new TimeSpan(day, hour, min, sec, milisec); var sb = new StringBuilder(); ProcessTimeLayoutRenderer.WritetTimestamp(sb, time, System.Globalization.CultureInfo.InvariantCulture); var result = sb.ToString(); Assert.Equal(expected, result); } [Fact] public void RenderProcessTimeLayoutRenderer() { var layout = "${processtime}"; var timestamp = LogEventInfo.ZeroDate; System.Threading.Thread.Sleep(16); var logEvent = new LogEventInfo(LogLevel.Debug, "logger1", "message1"); var time = logEvent.TimeStamp.ToUniversalTime() - timestamp; var expected = time.ToString("hh\\:mm\\:ss\\.fff"); AssertLayoutRendererOutput(layout, logEvent, expected); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #define DEBUG namespace NLog.UnitTests { using System; using System.Globalization; using System.Threading; using System.Diagnostics; using NLog.Config; using Xunit; public sealed class NLogTraceListenerTests : NLogTestBase, IDisposable { private readonly CultureInfo previousCultureInfo; public NLogTraceListenerTests() { previousCultureInfo = Thread.CurrentThread.CurrentCulture; // set the culture info with the decimal separator (comma) different from InvariantCulture separator (point) Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR"); } public void Dispose() { // restore previous culture info Thread.CurrentThread.CurrentCulture = previousCultureInfo; } #if !NETSTANDARD1_5 [Fact] public void TraceWriteTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Trace.Listeners.Clear(); Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1" }); Trace.Write("Hello"); AssertDebugLastMessage("debug", "Logger1 Debug Hello"); Trace.Write("Hello", "Cat1"); AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello"); Trace.Write(3.1415); AssertDebugLastMessage("debug", $"Logger1 Debug {3.1415}"); Trace.Write(3.1415, "Cat2"); AssertDebugLastMessage("debug", $"Logger1 Debug Cat2: {3.1415}"); } [Fact] public void TraceWriteLineTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Trace.Listeners.Clear(); Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1" }); Trace.WriteLine("Hello"); AssertDebugLastMessage("debug", "Logger1 Debug Hello"); Trace.WriteLine("Hello", "Cat1"); AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello"); Trace.WriteLine(3.1415); AssertDebugLastMessage("debug", $"Logger1 Debug {3.1415}"); Trace.WriteLine(3.1415, "Cat2"); AssertDebugLastMessage("debug", $"Logger1 Debug Cat2: {3.1415}"); } [Fact] public void TraceWriteNonDefaultLevelTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); Trace.Listeners.Clear(); Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); Trace.Write("Hello"); AssertDebugLastMessage("debug", "Logger1 Trace Hello"); } [Fact] public void TraceConfiguration() { var listener = new NLogTraceListener(); listener.Attributes.Add("defaultLogLevel", "Warn"); listener.Attributes.Add("forceLogLevel", "Error"); listener.Attributes.Add("autoLoggerName", "1"); listener.Attributes.Add("DISABLEFLUSH", "true"); Assert.Equal(LogLevel.Warn, listener.DefaultLogLevel); Assert.Equal(LogLevel.Error, listener.ForceLogLevel); Assert.True(listener.AutoLoggerName); Assert.True(listener.DisableFlush); } [Fact] public void TraceFailTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Trace.Listeners.Clear(); Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1" }); Trace.Fail("Message"); AssertDebugLastMessage("debug", "Logger1 Error Message"); Trace.Fail("Message", "Detailed Message"); AssertDebugLastMessage("debug", "Logger1 Error Message Detailed Message"); } [Fact] public void AutoLoggerNameTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Trace.Listeners.Clear(); Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1", AutoLoggerName = true }); Trace.Write("Hello"); AssertDebugLastMessage("debug", GetType().FullName + " Debug Hello"); } [Fact] public void TraceDataTests() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); ts.TraceData(TraceEventType.Critical, 123, 42); AssertDebugLastMessage("debug", "MySource1 Fatal 42 123"); ts.TraceData(TraceEventType.Critical, 145, 42, 3.14, "foo"); AssertDebugLastMessage("debug", $"MySource1 Fatal 42, {3.14.ToString(CultureInfo.CurrentCulture)}, foo 145"); } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void LogInformationTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); ts.TraceInformation("Quick brown fox"); AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox 0"); ts.TraceInformation("Mary had {0} lamb", "a little"); AssertDebugLastMessage("debug", "MySource1 Info Mary had a little lamb 0"); } [Fact] public void TraceEventTests() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); ts.TraceEvent(TraceEventType.Information, 123, "Quick brown {0} jumps over the lazy {1}.", "fox", "dog"); AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox jumps over the lazy dog. 123"); ts.TraceEvent(TraceEventType.Information, 123); AssertDebugLastMessage("debug", "MySource1 Info 123"); ts.TraceEvent(TraceEventType.Verbose, 145, "Bar"); AssertDebugLastMessage("debug", "MySource1 Trace Bar 145"); ts.TraceEvent(TraceEventType.Error, 145, "Foo"); AssertDebugLastMessage("debug", "MySource1 Error Foo 145"); ts.TraceEvent(TraceEventType.Suspend, 145, "Bar"); AssertDebugLastMessage("debug", "MySource1 Debug Bar 145"); ts.TraceEvent(TraceEventType.Resume, 145, "Foo"); AssertDebugLastMessage("debug", "MySource1 Debug Foo 145"); ts.TraceEvent(TraceEventType.Warning, 145, "Bar"); AssertDebugLastMessage("debug", "MySource1 Warn Bar 145"); ts.TraceEvent(TraceEventType.Critical, 145, "Foo"); AssertDebugLastMessage("debug", "MySource1 Fatal Foo 145"); } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void ForceLogLevelTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace, ForceLogLevel = LogLevel.Warn }); // force all logs to be Warn, DefaultLogLevel has no effect on TraceSource ts.TraceInformation("Quick brown fox"); AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0"); ts.TraceInformation("Mary had {0} lamb", "a little"); AssertDebugLastMessage("debug", "MySource1 Warn Mary had a little lamb 0"); } [Fact] public void FilterTraceTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace, ForceLogLevel = LogLevel.Warn, Filter = new EventTypeFilter(SourceLevels.Error) }); // force all logs to be Warn, DefaultLogLevel has no effect on TraceSource ts.TraceEvent(TraceEventType.Error, 0, "Quick brown fox"); AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0"); ts.TraceInformation("Mary had {0} lamb", "a little"); AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0"); } #endif [Fact] public void TraceTargetWriteLineTest() { var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteToTrace(layout: "${logger} ${level} ${message}", rawWrite: true); }).GetLogger("MySource1"); var sw = new System.IO.StringWriter(); try { Trace.Listeners.Clear(); Trace.Listeners.Add(new TextWriterTraceListener(sw)); foreach (var logLevel in LogLevel.AllLevels) { if (logLevel == LogLevel.Off) continue; logger.Log(logLevel, "Quick brown fox"); Trace.Flush(); Assert.Equal($"MySource1 {logLevel} Quick brown fox" + Environment.NewLine, sw.GetStringBuilder().ToString()); sw.GetStringBuilder().Length = 0; } Trace.Flush(); } finally { Trace.Listeners.Clear(); } } [Theory] [InlineData(true)] [InlineData(false)] public void TraceTargetEnableTraceFailTest(bool enableTraceFail) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString($@" <nlog> <targets> <target name='trace' type='Trace' layout='${{logger}} ${{level}} ${{message}}' enableTraceFail='{enableTraceFail}' /> </targets> <rules> <logger name='*' minlevel='Trace' writeTo='trace' /> </rules> </nlog>"); var logger = LogManager.GetLogger(nameof(TraceTargetEnableTraceFailTest)); var sw = new System.IO.StringWriter(); try { Trace.Listeners.Clear(); Trace.Listeners.Add(new TextWriterTraceListener(sw)); foreach (var logLevel in LogLevel.AllLevels) { if (logLevel == LogLevel.Off) continue; logger.Log(logLevel, "Quick brown fox"); Trace.Flush(); if (logLevel == LogLevel.Fatal) { if (enableTraceFail) Assert.Equal($"Fail: {logger.Name} Fatal Quick brown fox" + Environment.NewLine, sw.GetStringBuilder().ToString()); else Assert.NotEqual($"Fail: {logger.Name} Fatal Quick brown fox" + Environment.NewLine, sw.GetStringBuilder().ToString()); } Assert.Contains($"{logger.Name} {logLevel} Quick brown fox" + Environment.NewLine, sw.GetStringBuilder().ToString()); sw.GetStringBuilder().Length = 0; } } finally { Trace.Listeners.Clear(); } } private static TraceSource CreateTraceSource() { var ts = new TraceSource("MySource1", SourceLevels.All); #if MONO // for some reason needed on Mono ts.Switch = new SourceSwitch("MySource1", "Verbose"); ts.Switch.Level = SourceLevels.All; #endif return ts; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Contexts { using System; using System.Collections.Generic; using System.Linq; using Xunit; public class ScopeContextTest { [Fact] public void PushPropertyCaseInsensitiveTest() { // Arrange ScopeContext.Clear(); var expectedValue = "World"; Dictionary<string, object> allProperties = null; var success = false; object value; // Act using (ScopeContext.PushProperty("HELLO", expectedValue)) { success = ScopeContext.TryGetProperty("hello", out value); allProperties = ScopeContext.GetAllProperties().ToDictionary(x => x.Key, x => x.Value); } var failed = ScopeContext.TryGetProperty("hello", out var _); // Assert Assert.True(success); Assert.Equal(expectedValue, value); Assert.Single(allProperties); Assert.Equal(expectedValue, allProperties["HELLO"]); Assert.False(failed); } [Fact] public void LoggerPushPropertyTest() { // Arrange ScopeContext.Clear(); var expectedValue = "World"; Dictionary<string, object> allProperties = null; var success = false; object value; var logger = new LogFactory().GetCurrentClassLogger(); // Act using (logger.PushScopeProperty("HELLO", expectedValue)) { success = ScopeContext.TryGetProperty("hello", out value); allProperties = ScopeContext.GetAllProperties().ToDictionary(x => x.Key, x => x.Value); } var failed = ScopeContext.TryGetProperty("hello", out var _); // Assert Assert.True(success); Assert.Equal(expectedValue, value); Assert.Single(allProperties); Assert.Equal(expectedValue, allProperties["HELLO"]); Assert.False(failed); } [Fact] public void PushPropertyNestedTest() { // Arrange ScopeContext.Clear(); var expectedString = "World"; var expectedGuid = System.Guid.NewGuid(); Dictionary<string, object> allProperties = null; object stringValueLookup1 = null; object stringValueLookup2 = null; bool stringValueLookup3 = false; object guidValueLookup1 = null; bool guidValueLookup2 = false; bool guidValueLookup3 = false; // Act using (ScopeContext.PushProperty("Hello", expectedString)) { using (ScopeContext.PushProperty("RequestId", expectedGuid)) { ScopeContext.TryGetProperty("Hello", out stringValueLookup1); ScopeContext.TryGetProperty("RequestId", out guidValueLookup1); allProperties = ScopeContext.GetAllProperties().ToDictionary(x => x.Key, x => x.Value); } ScopeContext.TryGetProperty("Hello", out stringValueLookup2); guidValueLookup2 = ScopeContext.TryGetProperty("RequestId", out var _); } guidValueLookup3 = ScopeContext.TryGetProperty("RequestId", out var _); stringValueLookup3 = ScopeContext.TryGetProperty("Hello", out var _); // Assert Assert.Equal(2, allProperties.Count); Assert.Equal(expectedString, allProperties["Hello"]); Assert.Equal(expectedGuid, allProperties["RequestId"]); Assert.Equal(expectedString, stringValueLookup1); Assert.Equal(expectedString, stringValueLookup2); Assert.Equal(expectedGuid, guidValueLookup1); Assert.False(guidValueLookup2); Assert.False(guidValueLookup3); Assert.False(guidValueLookup3); Assert.False(stringValueLookup3); } #if !NET35 && !NET40 [Fact] public void PushNestedStatePropertiesTest() { // Arrange ScopeContext.Clear(); var expectedString = "World"; var expectedGuid = System.Guid.NewGuid(); var expectedProperties = new[] { new KeyValuePair<string, object>("Hello", expectedString), new KeyValuePair<string, object>("RequestId", expectedGuid) }; var expectedNestedState = "First Push"; Dictionary<string, object> allProperties = null; object[] allNestedStates = null; object stringValueLookup = null; // Act using (ScopeContext.PushProperty("Hello", "People")) { using (ScopeContext.PushNestedStateProperties(expectedNestedState, expectedProperties)) { allNestedStates = ScopeContext.GetAllNestedStates(); allProperties = ScopeContext.GetAllProperties().ToDictionary(x => x.Key, x => x.Value); } ScopeContext.TryGetProperty("Hello", out stringValueLookup); } // Assert Assert.Equal(2, allProperties.Count); Assert.Equal(expectedString, allProperties["Hello"]); Assert.Equal(expectedGuid, allProperties["RequestId"]); Assert.Single(allNestedStates); Assert.Equal(expectedNestedState, allNestedStates[0]); Assert.Equal("People", stringValueLookup); } [Fact] public void LoggerPushScopePropertiesTest() { // Arrange ScopeContext.Clear(); var expectedString = "World"; var expectedGuid = System.Guid.NewGuid(); var expectedProperties = new[] { new KeyValuePair<string, object>("Hello", expectedString), new KeyValuePair<string, object>("RequestId", expectedGuid) }; IEnumerable<KeyValuePair<string, object>> allPropertiesState = null; Dictionary<string, object> allProperties = null; var logger = new LogFactory().GetCurrentClassLogger(); object stringValueLookup = null; // Act using (logger.PushScopeProperties(expectedProperties)) { allPropertiesState = ScopeContext.GetAllProperties(); allProperties = allPropertiesState.ToDictionary(x => x.Key, x => x.Value); } ScopeContext.TryGetProperty("Hello", out stringValueLookup); // Assert #if !NET35 && !NET40 && !NET45 Assert.Same(expectedProperties, allPropertiesState); #endif Assert.Equal(2, allProperties.Count); Assert.Equal(expectedString, allProperties["Hello"]); Assert.Equal(expectedGuid, allProperties["RequestId"]); Assert.Equal(expectedProperties.Select(p => new KeyValuePair<string, object>(p.Key, p.Value)), allProperties); Assert.Null(stringValueLookup); } [Fact] public void LoggerPushScopePropertiesOverwriteTest() { // Arrange ScopeContext.Clear(); var expectedString = "World"; var expectedGuid = System.Guid.NewGuid(); var expectedProperties = new[] { new KeyValuePair<string, object>("Hello", expectedString), new KeyValuePair<string, object>("RequestId", expectedGuid) }; Dictionary<string, object> allProperties = null; object stringValueLookup = null; var logger = new LogFactory().GetCurrentClassLogger(); // Act using (logger.PushScopeProperty("Hello", "People")) { using (logger.PushScopeProperties(expectedProperties)) { allProperties = ScopeContext.GetAllProperties().ToDictionary(x => x.Key, x => x.Value); } ScopeContext.TryGetProperty("Hello", out stringValueLookup); } // Assert Assert.Equal(2, allProperties.Count); Assert.Equal(expectedString, allProperties["Hello"]); Assert.Equal(expectedGuid, allProperties["RequestId"]); Assert.Equal(expectedProperties.Select(p => new KeyValuePair<string, object>(p.Key, p.Value)), allProperties); Assert.Equal("People", stringValueLookup); } [Theory] [InlineData(false)] [InlineData(true)] public void LoggerPushScopePropertiesCovarianceTest(bool convertDictionary) { // Arrange ScopeContext.Clear(); var expectedString = "World"; var expectedId = 42; IReadOnlyCollection<KeyValuePair<string,IConvertible>> expectedProperties = new[] { new KeyValuePair<string, IConvertible>("Hello", expectedString), new KeyValuePair<string, IConvertible>("RequestId", expectedId) }; if (convertDictionary) expectedProperties = expectedProperties.ToDictionary(i => i.Key, i => i.Value); Dictionary<string, object> allProperties = null; object stringValueLookup = null; var logger = new LogFactory().GetCurrentClassLogger(); // Act using (logger.PushScopeProperty("Hello", "People")) { using (logger.PushScopeProperties(expectedProperties)) { allProperties = ScopeContext.GetAllProperties().ToDictionary(x => x.Key, x => x.Value); } ScopeContext.TryGetProperty("Hello", out stringValueLookup); } // Assert Assert.Equal(2, allProperties.Count); Assert.Equal(expectedString, allProperties["Hello"]); Assert.Equal(expectedId, allProperties["RequestId"]); Assert.Equal(expectedProperties.Select(p => new KeyValuePair<string, object>(p.Key, p.Value)), allProperties); Assert.Equal("People", stringValueLookup); } #endif [Fact] public void PushNestedStateTest() { // Arrange ScopeContext.Clear(); var expectedNestedState = "First Push"; object topNestedState = null; object[] allNestedStates = null; // Act using (ScopeContext.PushNestedState(expectedNestedState)) { topNestedState = ScopeContext.PeekNestedState(); allNestedStates = ScopeContext.GetAllNestedStates(); } var failed = ScopeContext.PeekNestedState() != null; // Assert Assert.Equal(expectedNestedState, topNestedState); Assert.Single(allNestedStates); Assert.Equal(expectedNestedState, allNestedStates[0]); Assert.False(failed); } [Fact] public void DoublePushNestedStateTest() { // Arrange ScopeContext.Clear(); var expectedNestedState1 = "First Push"; var expectedNestedState2 = System.Guid.NewGuid(); object topNestedState1 = null; object topNestedState2 = null; object[] allNestedStates = null; // Act using (ScopeContext.PushNestedState(expectedNestedState1)) { topNestedState1 = ScopeContext.PeekNestedState(); using (ScopeContext.PushNestedState(expectedNestedState2)) { topNestedState2 = ScopeContext.PeekNestedState(); allNestedStates = ScopeContext.GetAllNestedStates(); } } var failed = ScopeContext.PeekNestedState() != null; // Assert Assert.Equal(expectedNestedState1, topNestedState1); Assert.Equal(expectedNestedState2, topNestedState2); Assert.Equal(2, allNestedStates.Length); Assert.Equal(expectedNestedState2, allNestedStates[0]); Assert.Equal(expectedNestedState1, allNestedStates[1]); Assert.False(failed); } [Fact] public void LoggerPushNestedStateTest() { // Arrange ScopeContext.Clear(); var expectedNestedState = "First Push"; object topNestedState = null; object[] allNestedStates = null; var logger = new LogFactory().GetCurrentClassLogger(); // Act using (logger.PushScopeNested(expectedNestedState)) { topNestedState = ScopeContext.PeekNestedState(); allNestedStates = ScopeContext.GetAllNestedStates(); } var failed = ScopeContext.PeekNestedState() != null; // Assert Assert.Equal(expectedNestedState, topNestedState); Assert.Single(allNestedStates); Assert.Equal(expectedNestedState, allNestedStates[0]); Assert.False(failed); } [Fact] public void LoggerPushNestedStatePrimitiveTest() { // Arrange ScopeContext.Clear(); var expectedNestedState = 42; object topNestedState = null; object[] allNestedStates = null; var logger = new LogFactory().GetCurrentClassLogger(); // Act using (logger.PushScopeNested(expectedNestedState)) { topNestedState = ScopeContext.PeekNestedState(); allNestedStates = ScopeContext.GetAllNestedStates(); } var failed = ScopeContext.PeekNestedState() != null; // Assert Assert.Equal(expectedNestedState, topNestedState); Assert.Single(allNestedStates); Assert.Equal(expectedNestedState, allNestedStates[0]); Assert.False(failed); } [Fact] public void ClearScopeContextTest() { // Arrange ScopeContext.Clear(); var expectedNestedState = "First Push"; var expectedString = "World"; var expectedGuid = System.Guid.NewGuid(); object[] allNestedStates1 = null; object[] allNestedStates2 = null; object stringValueLookup1 = null; object stringValueLookup2 = null; // Act using (ScopeContext.PushProperty("Hello", expectedString)) { using (ScopeContext.PushProperty("RequestId", expectedGuid)) { using (ScopeContext.PushNestedState(expectedNestedState)) { ScopeContext.Clear(); allNestedStates1 = ScopeContext.GetAllNestedStates(); ScopeContext.TryGetProperty("Hello", out stringValueLookup1); } } // Original scope was restored on dispose, verify expected behavior allNestedStates2 = ScopeContext.GetAllNestedStates(); ScopeContext.TryGetProperty("Hello", out stringValueLookup2); } // Assert Assert.Null(stringValueLookup1); Assert.Equal(expectedString, stringValueLookup2); Assert.Empty(allNestedStates1); Assert.Empty(allNestedStates2); } [Fact] [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public void LegacyNdlcPopShouldNotAffectProperties1() { // Arrange ScopeContext.Clear(); var expectedValue = "World"; var success = false; object propertyValue; // Act using (ScopeContext.PushProperty("Hello", expectedValue)) { NestedDiagnosticsLogicalContext.PopObject(); // Should not pop anything (skip legacy mode) success = ScopeContext.TryGetProperty("Hello", out propertyValue); } // Assert Assert.True(success); Assert.Equal(expectedValue, propertyValue); } [Fact] [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public void LegacyNdlcPopShouldNotAffectProperties2() { // Arrange ScopeContext.Clear(); var expectedValue = "World"; var expectedNestedState = "First Push"; var success = false; object propertyValue; object nestedState; // Act using (ScopeContext.PushProperty("Hello", expectedValue)) { ScopeContext.PushNestedState(expectedNestedState); nestedState = NestedDiagnosticsLogicalContext.PopObject(); // Should only pop active scope (skip legacy mode) success = ScopeContext.TryGetProperty("Hello", out propertyValue); } // Assert Assert.True(success); Assert.Equal(expectedValue, propertyValue); Assert.Equal(expectedNestedState, nestedState); } [Fact] [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public void LegacyNdlcPopShouldNotAffectProperties3() { // Arrange ScopeContext.Clear(); var expectedValue1 = "World"; var expectedValue2 = System.Guid.NewGuid(); var expectedNestedState1 = "First Push"; var expectedNestedState2 = System.Guid.NewGuid(); var success1 = false; var success2 = false; object propertyValue1; object propertyValue2; object nestedState1; object nestedState2; // Act using (ScopeContext.PushProperty("Hello", expectedValue1)) { ScopeContext.PushNestedState(expectedNestedState1); ScopeContext.PushNestedState(expectedNestedState2); using (ScopeContext.PushProperty("RequestId", expectedValue2)) { nestedState2 = NestedDiagnosticsLogicalContext.PopObject(); // Evil pop where it should leave properties alone (Legacy mode) nestedState1 = NestedDiagnosticsLogicalContext.PopObject(); // Evil pop where it should leave properties alone (Legacy mode) success1 = ScopeContext.TryGetProperty("Hello", out propertyValue1); success2 = ScopeContext.TryGetProperty("RequestId", out propertyValue2); } } // Assert Assert.True(success1); Assert.True(success2); Assert.Equal(expectedValue1, propertyValue1); Assert.Equal(expectedValue2, propertyValue2); Assert.Equal(expectedNestedState1, nestedState1); Assert.Equal(expectedNestedState2, nestedState2); } [Fact] [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public void LegacyNdlcClearShouldNotAffectProperties1() { // Arrange ScopeContext.Clear(); var expectedValue = "World"; var success = false; object propertyValue; // Act using (ScopeContext.PushProperty("Hello", expectedValue)) { NestedDiagnosticsLogicalContext.Clear(); // Should not clear anything (skip legacy mode) success = ScopeContext.TryGetProperty("Hello", out propertyValue); } // Assert Assert.True(success); Assert.Equal(expectedValue, propertyValue); } [Fact] [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public void LegacyNdlcClearShouldNotAffectProperties2() { // Arrange ScopeContext.Clear(); var expectedValue = "World"; var expectedNestedState = "First Push"; var success = false; object propertyValue; // Act using (ScopeContext.PushProperty("Hello", expectedValue)) { ScopeContext.PushNestedState(expectedNestedState); NestedDiagnosticsLogicalContext.Clear(); // Should not clear properties (Legacy mode) success = ScopeContext.TryGetProperty("Hello", out propertyValue); } // Assert Assert.True(success); Assert.Equal(expectedValue, propertyValue); } [Fact] [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public void LegacyMdlcClearShouldNotAffectStackValues1() { // Arrange ScopeContext.Clear(); var expectedNestedState = "First Push"; object[] allNestedStates = null; // Act using (ScopeContext.PushNestedState(expectedNestedState)) { MappedDiagnosticsLogicalContext.Clear(); // Should not clear anything (skip legacy mode) allNestedStates = ScopeContext.GetAllNestedStates(); } // Assert Assert.Single(allNestedStates); Assert.Equal(expectedNestedState, allNestedStates[0]); } [Fact] [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public void LegacyMdlcClearShouldNotAffectStackValues2() { // Arrange ScopeContext.Clear(); var expectedValue = "World"; var expectedNestedState = "First Push"; object[] allNestedStates = null; // Act using (ScopeContext.PushNestedState(expectedNestedState)) { ScopeContext.PushProperty("Hello", expectedValue); MappedDiagnosticsLogicalContext.Clear(); // Should not clear stack (Legacy mode) allNestedStates = ScopeContext.GetAllNestedStates(); } // Assert Assert.Single(allNestedStates); Assert.Equal(expectedNestedState, allNestedStates[0]); } [Fact] [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public void LegacyMdlcRemoveShouldNotAffectStackValues1() { // Arrange ScopeContext.Clear(); var expectedNestedState = "First Push"; object[] allNestedStates = null; // Act using (ScopeContext.PushNestedState(expectedNestedState)) { MappedDiagnosticsLogicalContext.Remove("Hello"); // Should not remove anything (skip legacy mode) allNestedStates = ScopeContext.GetAllNestedStates(); } // Assert Assert.Single(allNestedStates); Assert.Equal(expectedNestedState, allNestedStates[0]); } [Fact] [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public void LegacyMdlcRemoveShouldNotAffectStackValues2() { // Arrange ScopeContext.Clear(); var expectedValue1 = "World"; var expectedValue2 = System.Guid.NewGuid(); var expectedNestedState1 = "First Push"; var expectedNestedState2 = System.Guid.NewGuid(); object propertyValue1; object propertyValue2; object[] allNestedStates = null; var success1 = false; var success2 = false; // Act using (ScopeContext.PushNestedState(expectedNestedState1)) { using (ScopeContext.PushProperty("Hello", expectedValue1)) { using (ScopeContext.PushNestedState(expectedNestedState2)) { ScopeContext.PushProperty("RequestId", expectedValue2); MappedDiagnosticsLogicalContext.Remove("RequestId"); // Should not change stack (Legacy mode) allNestedStates = ScopeContext.GetAllNestedStates(); success1 = ScopeContext.TryGetProperty("Hello", out propertyValue1); success2 = ScopeContext.TryGetProperty("RequestId", out propertyValue2); } } } // Assert Assert.Equal(2, allNestedStates.Length); Assert.Equal(expectedNestedState2, allNestedStates[0]); Assert.Equal(expectedNestedState1, allNestedStates[1]); Assert.True(success1); Assert.False(success2); Assert.Equal(expectedValue1, propertyValue1); Assert.Null(propertyValue2); } [Fact] [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public void LegacyMdlcSetShouldNotAffectStackValues1() { // Arrange ScopeContext.Clear(); var expectedValue = "World"; var expectedNestedState = "First Push"; object propertyValue; object[] allNestedStates = null; var success = false; // Act using (ScopeContext.PushNestedState(expectedNestedState)) { MappedDiagnosticsLogicalContext.Set("Hello", expectedValue); // Skip legacy mode (normal property push) success = ScopeContext.TryGetProperty("Hello", out propertyValue); allNestedStates = ScopeContext.GetAllNestedStates(); } // Assert Assert.Single(allNestedStates); Assert.Equal(expectedNestedState, allNestedStates[0]); Assert.True(success); Assert.Equal(expectedValue, propertyValue); } [Fact] [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public void LegacyMdlcSetShouldNotAffectStackValues2() { // Arrange ScopeContext.Clear(); var expectedValue = "World"; var expectedNestedState = "First Push"; object propertyValue; object[] allNestedStates = null; var success = false; // Act using (ScopeContext.PushNestedState(expectedNestedState)) { using (ScopeContext.PushProperty("Hello", expectedValue)) { MappedDiagnosticsLogicalContext.Set("Hello", expectedValue); // Skip legacy mode (ignore when same value) success = ScopeContext.TryGetProperty("Hello", out propertyValue); allNestedStates = ScopeContext.GetAllNestedStates(); } } // Assert Assert.Single(allNestedStates); Assert.Equal(expectedNestedState, allNestedStates[0]); Assert.True(success); Assert.Equal(expectedValue, propertyValue); } [Fact] [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public void LegacyMdlcSetShouldNotAffectStackValues3() { // Arrange ScopeContext.Clear(); var expectedValue = "Bob"; var expectedNestedState = "First Push"; object propertyValue1; object propertyValue2; object[] allNestedStates = null; var success1 = false; var success2 = false; // Act using (ScopeContext.PushNestedState(expectedNestedState)) { using (ScopeContext.PushProperty("Hello", "World")) { MappedDiagnosticsLogicalContext.Set("Hello", expectedValue); // Enter legacy mode (need to overwrite) success1 = ScopeContext.TryGetProperty("Hello", out propertyValue1); allNestedStates = ScopeContext.GetAllNestedStates(); } success2 = ScopeContext.TryGetProperty("Hello", out propertyValue2); } // Assert Assert.Single(allNestedStates); Assert.Equal(expectedNestedState, allNestedStates[0]); Assert.True(success1); Assert.Equal(expectedValue, propertyValue1); Assert.False(success2); Assert.Null(propertyValue2); } [Fact] public void ScopeContextPushWithoutStackOverflow() { // Arrange ScopeContext.Clear(); var scopeData = new[] { new KeyValuePair<string, object>("Hello", "World") }; // Act ScopeContext.PushProperty(scopeData[0].Key, scopeData[0].Value); for (int i = 0; i < 50000; ++i) { ScopeContext.PushNestedState(scopeData); } var scopeProperties = ScopeContext.GetAllProperties(); // Assert Assert.Single(scopeProperties); Assert.Equal(scopeData[0].Key, scopeProperties.First().Key); Assert.Equal(scopeData[0].Value, scopeProperties.First().Value); } [Fact] public void ScopeContextPushWithoutStackOverflow2() { // Arrange ScopeContext.Clear(); var scopeData = new[] { new KeyValuePair<string, object>("Hello", "World") }; // Act ScopeContext.PushNestedState(scopeData); for (int i = 0; i < 50000; ++i) { ScopeContext.PushProperty(scopeData[0].Key, scopeData[0].Value); } var scopeProperties = ScopeContext.GetAllProperties(); var scopeNestedStates = ScopeContext.GetAllNestedStates(); // Assert Assert.Single(scopeProperties); Assert.Equal(scopeData[0].Key, scopeProperties.First().Key); Assert.Equal(scopeData[0].Value, scopeProperties.First().Value); Assert.Single(scopeNestedStates); Assert.Equal(scopeData, scopeNestedStates[0]); } #if !NET35 && !NET40 [Fact] public void ScopeContextPushWithoutStackOverflow3() { // Arrange ScopeContext.Clear(); var scopeData = new[] { new KeyValuePair<string, object>("Hello", "World") }; // Act for (int i = 0; i < 50000; ++i) { ScopeContext.PushNestedStateProperties(scopeData, scopeData); } var scopeProperties = ScopeContext.GetAllProperties(); // Assert Assert.Single(scopeProperties); Assert.Equal(scopeData[0].Key, scopeProperties.First().Key); Assert.Equal(scopeData[0].Value, scopeProperties.First().Value); } [Fact] public void ScopeContextPushWithoutStackOverflow4() { // Arrange ScopeContext.Clear(); var scopeData = new[] { new KeyValuePair<string, object>("Hello", "World") }; // Act ScopeContext.PushNestedState(scopeData); for (int i = 0; i < 50000; ++i) { ScopeContext.PushNestedStateProperties(null, scopeData); } var scopeProperties = ScopeContext.GetAllProperties(); var scopeNestedStates = ScopeContext.GetAllNestedStates(); // Assert Assert.Single(scopeProperties); Assert.Equal(scopeData[0].Key, scopeProperties.First().Key); Assert.Equal(scopeData[0].Value, scopeProperties.First().Value); Assert.Single(scopeNestedStates); Assert.Equal(scopeData, scopeNestedStates[0]); } #endif } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 && !NETSTANDARD1_5 namespace NLog.Targets { using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Text; using System.IO; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; #if !NETSTANDARD using System.Configuration; using System.Net.Configuration; #endif /// <summary> /// Sends log messages by email using SMTP protocol. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/Mail-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/Mail-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/Mail/Simple/NLog.config" /> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/Mail/Simple/Example.cs" /> /// <p> /// Mail target works best when used with BufferingWrapper target /// which lets you send multiple log messages in single mail /// </p> /// <p> /// To set up the buffered mail target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/Mail/Buffered/NLog.config" /> /// <p> /// To set up the buffered mail target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/Mail/Buffered/Example.cs" /> /// </example> [Target("Mail")] [Target("Email")] [Target("Smtp")] [Target("SmtpClient")] public class MailTarget : TargetWithLayoutHeaderAndFooter { private const string RequiredPropertyIsEmptyFormat = "After the processing of the MailTarget's '{0}' property it appears to be empty. The email message will not be sent."; private Layout _from; /// <summary> /// Initializes a new instance of the <see cref="MailTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> public MailTarget() { Body = "${message}${newline}"; } /// <summary> /// Initializes a new instance of the <see cref="MailTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> /// <param name="name">Name of the target.</param> public MailTarget(string name) : this() { Name = name; } #if !NETSTANDARD private SmtpSection _currentailSettings; /// <summary> /// Gets the mailSettings/smtp configuration from app.config in cases when we need those configuration. /// E.g when UseSystemNetMailSettings is enabled and we need to read the From attribute from system.net/mailSettings/smtp /// </summary> /// <remarks>Internal for mocking</remarks> internal SmtpSection SmtpSection { get { if (_currentailSettings is null) { try { _currentailSettings = System.Configuration.ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection; } catch (Exception ex) { InternalLogger.Warn(ex, "{0}: Reading 'From' from .config failed.", this); if (LogManager.ThrowExceptions) throw; _currentailSettings = new SmtpSection(); } } return _currentailSettings; } set => _currentailSettings = value; } #endif /// <summary> /// Gets or sets sender's email address (e.g. <EMAIL>). /// </summary> /// <docgen category='Message Options' order='10' /> [RequiredParameter] public Layout From { get { #if !NETSTANDARD // In contrary to other settings, System.Net.Mail.SmtpClient doesn't read the 'From' attribute from the system.net/mailSettings/smtp section in the config file. // Thus, when UseSystemNetMailSettings is enabled we have to read the configuration section of system.net/mailSettings/smtp to initialize the 'From' address. // It will do so only if the 'From' attribute in system.net/mailSettings/smtp is not empty. //only use from config when not set in current if (UseSystemNetMailSettings && _from is null) { var from = SmtpSection.From; return from; } #endif return _from; } set { _from = value; } } /// <summary> /// Gets or sets recipients' email addresses separated by semicolons (e.g. <EMAIL>;<EMAIL>). /// </summary> /// <docgen category='Message Options' order='11' /> [RequiredParameter] public Layout To { get; set; } /// <summary> /// Gets or sets CC email addresses separated by semicolons (e.g. <EMAIL>;<EMAIL>). /// </summary> /// <docgen category='Message Options' order='12' /> public Layout CC { get; set; } /// <summary> /// Gets or sets BCC email addresses separated by semicolons (e.g. <EMAIL>;<EMAIL>). /// </summary> /// <docgen category='Message Options' order='13' /> public Layout Bcc { get; set; } /// <summary> /// Gets or sets a value indicating whether to add new lines between log entries. /// </summary> /// <value>A value of <c>true</c> if new lines should be added; otherwise, <c>false</c>.</value> /// <docgen category='Message Options' order='99' /> public bool AddNewLines { get; set; } /// <summary> /// Gets or sets the mail subject. /// </summary> /// <docgen category='Message Options' order='5' /> [RequiredParameter] public Layout Subject { get; set; } = "Message from NLog on ${machinename}"; /// <summary> /// Gets or sets mail message body (repeated for each log message send in one mail). /// </summary> /// <remarks>Alias for the <c>Layout</c> property.</remarks> /// <docgen category='Message Options' order='6' /> public Layout Body { get => Layout; set => Layout = value; } /// <summary> /// Gets or sets encoding to be used for sending e-mail. /// </summary> /// <docgen category='Message Options' order='20' /> public Encoding Encoding { get; set; } = Encoding.UTF8; /// <summary> /// Gets or sets a value indicating whether to send message as HTML instead of plain text. /// </summary> /// <docgen category='Message Options' order='11' /> public bool Html { get; set; } /// <summary> /// Gets or sets SMTP Server to be used for sending. /// </summary> /// <docgen category='SMTP Options' order='10' /> public Layout SmtpServer { get; set; } /// <summary> /// Gets or sets SMTP Authentication mode. /// </summary> /// <docgen category='SMTP Options' order='11' /> public SmtpAuthenticationMode SmtpAuthentication { get; set; } = SmtpAuthenticationMode.None; /// <summary> /// Gets or sets the username used to connect to SMTP server (used when SmtpAuthentication is set to "basic"). /// </summary> /// <docgen category='SMTP Options' order='12' /> public Layout SmtpUserName { get; set; } /// <summary> /// Gets or sets the password used to authenticate against SMTP server (used when SmtpAuthentication is set to "basic"). /// </summary> /// <docgen category='SMTP Options' order='13' /> public Layout SmtpPassword { get; set; } /// <summary> /// Gets or sets a value indicating whether SSL (secure sockets layer) should be used when communicating with SMTP server. /// </summary> /// <docgen category='SMTP Options' order='14' />. public bool EnableSsl { get; set; } /// <summary> /// Gets or sets the port number that SMTP Server is listening on. /// </summary> /// <docgen category='SMTP Options' order='15' /> public Layout<int> SmtpPort { get; set; } = 25; /// <summary> /// Gets or sets a value indicating whether the default Settings from System.Net.MailSettings should be used. /// </summary> /// <docgen category='SMTP Options' order='16' /> public bool UseSystemNetMailSettings { get; set; } /// <summary> /// Specifies how outgoing email messages will be handled. /// </summary> /// <docgen category='SMTP Options' order='18' /> public SmtpDeliveryMethod DeliveryMethod { get; set; } = SmtpDeliveryMethod.Network; /// <summary> /// Gets or sets the folder where applications save mail messages to be processed by the local SMTP server. /// </summary> /// <docgen category='SMTP Options' order='17' /> public Layout PickupDirectoryLocation { get; set; } /// <summary> /// Gets or sets the priority used for sending mails. /// </summary> /// <docgen category='Message Options' order='100' /> public Layout<MailPriority> Priority { get; set; } /// <summary> /// Gets or sets a value indicating whether NewLine characters in the body should be replaced with <br/> tags. /// </summary> /// <remarks>Only happens when <see cref="Html"/> is set to true.</remarks> /// <docgen category='Message Options' order='100' /> public bool ReplaceNewlineWithBrTagInHtml { get; set; } /// <summary> /// Gets or sets a value indicating the SMTP client timeout. /// </summary> /// <remarks>Warning: zero is not infinite waiting</remarks> /// <docgen category='SMTP Options' order='100' /> public Layout<int> Timeout { get; set; } = 10000; /// <summary> /// Gets the array of email headers that are transmitted with this email message /// </summary> /// <docgen category='Message Options' order='100' /> [ArrayParameter(typeof(MethodCallParameter), "mailheader")] public IList<MethodCallParameter> MailHeaders { get; } = new List<MethodCallParameter>(); internal virtual ISmtpClient CreateSmtpClient() { return new MySmtpClient(); } /// <inheritdoc/> protected override void Write(AsyncLogEventInfo logEvent) { Write((IList<AsyncLogEventInfo>)new[] { logEvent }); } /// <inheritdoc/> protected override void Write(IList<AsyncLogEventInfo> logEvents) { if (logEvents.Count == 1) { ProcessSingleMailMessage(logEvents); } else { var buckets = logEvents.GroupBy(l => GetSmtpSettingsKey(l.LogEvent)); foreach (var bucket in buckets) { var eventInfos = bucket; ProcessSingleMailMessage(eventInfos); } } } /// <inheritdoc/> protected override void InitializeTarget() { CheckRequiredParameters(); base.InitializeTarget(); } /// <summary> /// Create mail and send with SMTP /// </summary> /// <param name="events">event printed in the body of the event</param> private void ProcessSingleMailMessage(IEnumerable<AsyncLogEventInfo> events) { try { LogEventInfo firstEvent = events.FirstOrDefault().LogEvent; LogEventInfo lastEvent = events.LastOrDefault().LogEvent; if (firstEvent is null || lastEvent is null) { throw new NLogRuntimeException("We need at least one event."); } // unbuffered case, create a local buffer, append header, body and footer var bodyBuffer = CreateBodyBuffer(events, firstEvent, lastEvent); using (var msg = CreateMailMessage(lastEvent, bodyBuffer.ToString())) { using (ISmtpClient client = CreateSmtpClient()) { if (!UseSystemNetMailSettings) { ConfigureMailClient(lastEvent, client); } if (client.EnableSsl) InternalLogger.Debug("{0}: Sending mail to {1} using {2}:{3} (ssl=true)", this, msg.To, client.Host, client.Port); else InternalLogger.Debug("{0}: Sending mail to {1} using {2}:{3} (ssl=false)", this, msg.To, client.Host, client.Port); InternalLogger.Trace("{0}: Subject: '{1}'", this, msg.Subject); InternalLogger.Trace("{0}: From: '{1}'", this, msg.From); client.Send(msg); foreach (var ev in events) { ev.Continuation(null); } } } } catch (Exception exception) { //always log InternalLogger.Error(exception, "{0}: Error sending mail.", this); if (LogManager.ThrowExceptions) throw; foreach (var ev in events) { ev.Continuation(exception); } } } /// <summary> /// Create buffer for body /// </summary> /// <param name="events">all events</param> /// <param name="firstEvent">first event for header</param> /// <param name="lastEvent">last event for footer</param> /// <returns></returns> private StringBuilder CreateBodyBuffer(IEnumerable<AsyncLogEventInfo> events, LogEventInfo firstEvent, LogEventInfo lastEvent) { var bodyBuffer = new StringBuilder(); if (Header != null) { bodyBuffer.Append(RenderLogEvent(Header, firstEvent)); if (AddNewLines) { bodyBuffer.Append('\n'); } } foreach (AsyncLogEventInfo eventInfo in events) { bodyBuffer.Append(RenderLogEvent(Layout, eventInfo.LogEvent)); if (AddNewLines) { bodyBuffer.Append('\n'); } } if (Footer != null) { bodyBuffer.Append(RenderLogEvent(Footer, lastEvent)); if (AddNewLines) { bodyBuffer.Append('\n'); } } return bodyBuffer; } /// <summary> /// Set properties of <paramref name="client"/> /// </summary> /// <param name="lastEvent">last event for username/password</param> /// <param name="client">client to set properties on</param> /// <remarks>Configure not at <see cref="InitializeTarget"/>, as the properties could have layout renderers.</remarks> internal void ConfigureMailClient(LogEventInfo lastEvent, ISmtpClient client) { CheckRequiredParameters(); if (DeliveryMethod == SmtpDeliveryMethod.Network) { var smtpServer = RenderLogEvent(SmtpServer, lastEvent); if (string.IsNullOrEmpty(smtpServer)) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer")); } var smtpPort = RenderLogEvent(SmtpPort, lastEvent, 25); if (smtpPort <= 0) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpPort")); } client.Host = smtpServer; client.Port = smtpPort; client.EnableSsl = EnableSsl; if (SmtpAuthentication == SmtpAuthenticationMode.Ntlm) { InternalLogger.Trace("{0}: Using NTLM authentication.", this); client.Credentials = CredentialCache.DefaultNetworkCredentials; } else if (SmtpAuthentication == SmtpAuthenticationMode.Basic) { string username = RenderLogEvent(SmtpUserName, lastEvent); string password = RenderLogEvent(SmtpPassword, lastEvent); InternalLogger.Trace("{0}: Using basic authentication: Username='{1}' Password='{2}'", this, username, new string('*', password.Length)); client.Credentials = new NetworkCredential(username, password); } } if (DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory) { var pickupDirectoryLocation = RenderLogEvent(PickupDirectoryLocation, lastEvent); if (string.IsNullOrEmpty(pickupDirectoryLocation)) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "PickupDirectoryLocation")); } client.PickupDirectoryLocation = ConvertDirectoryLocation(pickupDirectoryLocation); } // In case DeliveryMethod = PickupDirectoryFromIis we will not require Host nor PickupDirectoryLocation client.DeliveryMethod = DeliveryMethod; client.Timeout = RenderLogEvent(Timeout, lastEvent, 10000); } /// <summary> /// Handle <paramref name="pickupDirectoryLocation"/> if it is a virtual directory. /// </summary> /// <param name="pickupDirectoryLocation"></param> /// <returns></returns> internal static string ConvertDirectoryLocation(string pickupDirectoryLocation) { const string virtualPathPrefix = "~/"; if (!pickupDirectoryLocation.StartsWith(virtualPathPrefix, StringComparison.Ordinal)) { return pickupDirectoryLocation; } // Support for Virtual Paths var root = AppDomain.CurrentDomain.BaseDirectory; var directory = pickupDirectoryLocation.Substring(virtualPathPrefix.Length).Replace('/', Path.DirectorySeparatorChar); var pickupRoot = Path.Combine(root, directory); return pickupRoot; } private void CheckRequiredParameters() { if (!UseSystemNetMailSettings && DeliveryMethod == SmtpDeliveryMethod.Network && SmtpServer is null) { throw new NLogConfigurationException($"The MailTarget's '{nameof(SmtpServer)}' properties are not set - but needed because useSystemNetMailSettings=false and DeliveryMethod=Network. The email message will not be sent."); } if (!UseSystemNetMailSettings && DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory && PickupDirectoryLocation is null) { throw new NLogConfigurationException($"The MailTarget's '{nameof(PickupDirectoryLocation)}' properties are not set - but needed because useSystemNetMailSettings=false and DeliveryMethod=SpecifiedPickupDirectory. The email message will not be sent."); } } /// <summary> /// Create key for grouping. Needed for multiple events in one mail message /// </summary> /// <param name="logEvent">event for rendering layouts </param> /// <returns>string to group on</returns> private string GetSmtpSettingsKey(LogEventInfo logEvent) { return $@"{RenderLogEvent(From, logEvent)} {RenderLogEvent(To, logEvent)} {RenderLogEvent(CC, logEvent)} {RenderLogEvent(Bcc, logEvent)} {RenderLogEvent(SmtpServer, logEvent)} {RenderLogEvent(SmtpPassword, logEvent)} {RenderLogEvent(SmtpUserName, logEvent)} {RenderLogEvent(PickupDirectoryLocation, logEvent)}"; } /// <summary> /// Create the mail message with the addresses, properties and body. /// </summary> private MailMessage CreateMailMessage(LogEventInfo lastEvent, string body) { var msg = new MailMessage(); var renderedFrom = RenderLogEvent(From, lastEvent); if (string.IsNullOrEmpty(renderedFrom)) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "From")); } msg.From = new MailAddress(renderedFrom); var addedTo = AddAddresses(msg.To, To, lastEvent); var addedCc = AddAddresses(msg.CC, CC, lastEvent); var addedBcc = AddAddresses(msg.Bcc, Bcc, lastEvent); if (!addedTo && !addedCc && !addedBcc) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "To/Cc/Bcc")); } msg.Subject = (RenderLogEvent(Subject, lastEvent) ?? string.Empty).Trim(); msg.BodyEncoding = Encoding; msg.IsBodyHtml = Html; if (Priority != null) { msg.Priority = RenderLogEvent(Priority, lastEvent, MailPriority.Normal); } msg.Body = body; if (msg.IsBodyHtml && ReplaceNewlineWithBrTagInHtml && msg.Body != null) msg.Body = msg.Body.Replace(Environment.NewLine, "<br/>"); if (MailHeaders?.Count > 0) { for (int i = 0; i < MailHeaders.Count; i++) { string headerValue = RenderLogEvent(MailHeaders[i].Layout, lastEvent); if (headerValue is null) continue; msg.Headers.Add(MailHeaders[i].Name, headerValue); } } return msg; } /// <summary> /// Render <paramref name="layout"/> and add the addresses to <paramref name="mailAddressCollection"/> /// </summary> /// <param name="mailAddressCollection">Addresses appended to this list</param> /// <param name="layout">layout with addresses, ; separated</param> /// <param name="logEvent">event for rendering the <paramref name="layout"/></param> /// <returns>added a address?</returns> private bool AddAddresses(MailAddressCollection mailAddressCollection, Layout layout, LogEventInfo logEvent) { var added = false; var mailAddresses = RenderLogEvent(layout, logEvent); if (!string.IsNullOrEmpty(mailAddresses)) { foreach (string mail in mailAddresses.Split(';')) { var mailAddress = mail.Trim(); if (string.IsNullOrEmpty(mailAddress)) continue; mailAddressCollection.Add(mailAddress); added = true; } } return added; } } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using NLog.MessageTemplates; /// <summary> /// Dictionary that combines the standard <see cref="LogEventInfo.Properties" /> with the /// MessageTemplate-properties extracted from the <see cref="LogEventInfo.Message" />. /// /// The <see cref="MessageProperties" /> are returned as the first items /// in the collection, and in positional order. /// </summary> [DebuggerDisplay("Count = {Count}")] internal sealed class PropertiesDictionary : IDictionary<object, object>, IEnumerable<MessageTemplateParameter> { private struct PropertyValue { /// <summary> /// Value of the property /// </summary> public readonly object Value; /// <summary> /// Has property been captured from message-template ? /// </summary> public readonly bool IsMessageProperty; public PropertyValue(object value, bool isMessageProperty) { Value = value; IsMessageProperty = isMessageProperty; } } /// <summary> /// The properties of the logEvent /// </summary> private Dictionary<object, PropertyValue> _eventProperties; /// <summary> /// The properties extracted from the message-template /// </summary> private IList<MessageTemplateParameter> _messageProperties; private DictionaryCollection _keyCollection; private DictionaryCollection _valueCollection; /// <summary> /// Wraps the list of message-template-parameters as IDictionary-interface /// </summary> /// <param name="messageParameters">Message-template-parameters</param> public PropertiesDictionary(IList<MessageTemplateParameter> messageParameters = null) { if (messageParameters?.Count > 0) { MessageProperties = messageParameters; } } #if !NET35 /// <summary> /// Transforms the list of event-properties into IDictionary-interface /// </summary> /// <param name="eventProperties">Message-template-parameters</param> public PropertiesDictionary(IReadOnlyList<KeyValuePair<object, object>> eventProperties) { var propertyCount = eventProperties.Count; if (propertyCount > 0) { _eventProperties = new Dictionary<object, PropertyValue>(propertyCount, PropertyKeyComparer.Default); for (int i = 0; i < propertyCount; ++i) { var property = eventProperties[i]; _eventProperties[property.Key] = new PropertyValue(property.Value, false); } } } #endif private bool IsEmpty => (_eventProperties is null || _eventProperties.Count == 0) && (_messageProperties is null || _messageProperties.Count == 0); private Dictionary<object, PropertyValue> EventProperties { get { if (_eventProperties is null) { System.Threading.Interlocked.CompareExchange(ref _eventProperties, BuildEventProperties(_messageProperties), null); } return _eventProperties; } } public IList<MessageTemplateParameter> MessageProperties { get => _messageProperties ?? ArrayHelper.Empty<MessageTemplateParameter>(); internal set => _messageProperties = SetMessageProperties(value, _messageProperties); } private IList<MessageTemplateParameter> SetMessageProperties(IList<MessageTemplateParameter> newMessageProperties, IList<MessageTemplateParameter> oldMessageProperties) { if (_eventProperties is null && VerifyUniqueMessageTemplateParametersFast(newMessageProperties)) { return newMessageProperties; } else { var eventProperties = _eventProperties; if (eventProperties is null) { eventProperties = _eventProperties = new Dictionary<object, PropertyValue>(newMessageProperties?.Count ?? 0, PropertyKeyComparer.Default); } if (oldMessageProperties != null && eventProperties.Count > 0) { RemoveOldMessageProperties(oldMessageProperties, eventProperties); } if (newMessageProperties != null) { InsertMessagePropertiesIntoEmptyDictionary(newMessageProperties, eventProperties); } return newMessageProperties; } } private void RemoveOldMessageProperties(IList<MessageTemplateParameter> oldMessageProperties, Dictionary<object, PropertyValue> eventProperties) { for (int i = 0; i < oldMessageProperties.Count; ++i) { if (eventProperties.TryGetValue(oldMessageProperties[i].Name, out var propertyValue) && propertyValue.IsMessageProperty) { eventProperties.Remove(oldMessageProperties[i].Name); } } } private static Dictionary<object, PropertyValue> BuildEventProperties(IList<MessageTemplateParameter> messageProperties) { if (messageProperties?.Count > 0) { var eventProperties = new Dictionary<object, PropertyValue>(messageProperties.Count, PropertyKeyComparer.Default); InsertMessagePropertiesIntoEmptyDictionary(messageProperties, eventProperties); return eventProperties; } else { return new Dictionary<object, PropertyValue>(PropertyKeyComparer.Default); } } /// <inheritDoc/> public object this[object key] { get { if (TryGetValue(key, out var valueItem)) { return valueItem; } throw new KeyNotFoundException(); } set => EventProperties[key] = new PropertyValue(value, false); } /// <inheritDoc/> public ICollection<object> Keys => KeyCollection; /// <inheritDoc/> public ICollection<object> Values => ValueCollection; private DictionaryCollection KeyCollection { get { if (_keyCollection != null) return _keyCollection; if (IsEmpty) return EmptyKeyCollection; return _keyCollection ?? (_keyCollection = new DictionaryCollection(this, true)); } } private DictionaryCollection ValueCollection { get { if (_valueCollection != null) return _valueCollection; if (IsEmpty) return EmptyValueCollection; return _valueCollection ?? (_valueCollection = new DictionaryCollection(this, false)); } } private static readonly DictionaryCollection EmptyKeyCollection = new DictionaryCollection(new PropertiesDictionary(), true); private static readonly DictionaryCollection EmptyValueCollection = new DictionaryCollection(new PropertiesDictionary(), false); /// <inheritDoc/> public int Count => (_eventProperties?.Count) ?? (_messageProperties?.Count) ?? 0; /// <inheritDoc/> public bool IsReadOnly => false; /// <inheritDoc/> public void Add(object key, object value) { EventProperties.Add(key, new PropertyValue(value, false)); } /// <inheritDoc/> public void Add(KeyValuePair<object, object> item) { Add(item.Key, item.Value); } /// <inheritDoc/> public void Clear() { if (_eventProperties != null) _eventProperties = null; if (_messageProperties != null) _messageProperties = ArrayHelper.Empty<MessageTemplateParameter>(); } /// <inheritDoc/> public bool Contains(KeyValuePair<object, object> item) { if (!IsEmpty) { if (((IDictionary<object, PropertyValue>)EventProperties).Contains(new KeyValuePair<object, PropertyValue>(item.Key, new PropertyValue(item.Value, false)))) return true; if (((IDictionary<object, PropertyValue>)EventProperties).Contains(new KeyValuePair<object, PropertyValue>(item.Key, new PropertyValue(item.Value, true)))) return true; } return false; } /// <inheritDoc/> public bool ContainsKey(object key) { return TryGetValue(key, out var _); } /// <inheritDoc/> public void CopyTo(KeyValuePair<object, object>[] array, int arrayIndex) { Guard.ThrowIfNull(array); if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); if (!IsEmpty) { foreach (var propertyItem in this) { array[arrayIndex++] = propertyItem; } } } /// <inheritDoc/> public IEnumerator<KeyValuePair<object, object>> GetEnumerator() { if (IsEmpty) return System.Linq.Enumerable.Empty<KeyValuePair<object, object>>().GetEnumerator(); return new DictionaryEnumerator(this); } /// <inheritDoc/> IEnumerator IEnumerable.GetEnumerator() { if (IsEmpty) return ArrayHelper.Empty<KeyValuePair<object, object>>().GetEnumerator(); return new DictionaryEnumerator(this); } /// <inheritDoc/> public bool Remove(object key) { if (!IsEmpty) { return EventProperties.Remove(key); } return false; } /// <inheritDoc/> public bool Remove(KeyValuePair<object, object> item) { if (!IsEmpty) { if (((IDictionary<object, PropertyValue>)EventProperties).Remove(new KeyValuePair<object, PropertyValue>(item.Key, new PropertyValue(item.Value, false)))) return true; if (((IDictionary<object, PropertyValue>)EventProperties).Remove(new KeyValuePair<object, PropertyValue>(item.Key, new PropertyValue(item.Value, true)))) return true; } return false; } /// <inheritDoc/> public bool TryGetValue(object key, out object value) { if (!IsEmpty) { if (_eventProperties is null && _messageProperties?.Count < 5) { return TryLookupMessagePropertyValue(key, out value); } else if (EventProperties.TryGetValue(key, out var valueItem)) { value = valueItem.Value; return true; } } value = null; return false; } private bool TryLookupMessagePropertyValue(object key, out object propertyValue) { if (key is string keyString) { for (int i = 0; i < _messageProperties.Count; ++i) { if (keyString.Equals(_messageProperties[i].Name, StringComparison.Ordinal)) { propertyValue = _messageProperties[i].Value; return true; } } } else if (key is IgnoreCasePropertyKey keyIgnoreCase) { for (int i = 0; i < _messageProperties.Count; ++i) { if (keyIgnoreCase.Equals(_messageProperties[i].Name)) { propertyValue = _messageProperties[i].Value; return true; } } } propertyValue = null; return false; } /// <summary> /// Check if the message-template-parameters can be used directly without allocating a dictionary /// </summary> /// <param name="parameterList">Message-template-parameters</param> /// <returns>Are all parameter names unique (true / false)</returns> private static bool VerifyUniqueMessageTemplateParametersFast(IList<MessageTemplateParameter> parameterList) { if (parameterList is null) return true; var parameterCount = parameterList.Count; if (parameterCount <= 1) return true; if (parameterCount > 10) return false; for (int i = 0; i < parameterCount - 1; ++i) { for (int j = i + 1; j < parameterCount; ++j) { if (parameterList[i].Name == parameterList[j].Name) return false; } } return true; } /// <summary> /// Attempt to insert the message-template-parameters into an empty dictionary /// </summary> /// <param name="messageProperties">Message-template-parameters</param> /// <param name="eventProperties">The dictionary that initially contains no message-template-parameters</param> private static void InsertMessagePropertiesIntoEmptyDictionary(IList<MessageTemplateParameter> messageProperties, Dictionary<object, PropertyValue> eventProperties) { for (int i = 0; i < messageProperties.Count; ++i) { try { eventProperties.Add(messageProperties[i].Name, new PropertyValue(messageProperties[i].Value, true)); } catch (ArgumentException) { var duplicateProperty = messageProperties[i]; if (eventProperties.TryGetValue(duplicateProperty.Name, out var propertyValue) && propertyValue.IsMessageProperty) { var uniqueName = GenerateUniquePropertyName(duplicateProperty.Name, eventProperties, (newkey, props) => props.ContainsKey(newkey)); eventProperties.Add(uniqueName, new PropertyValue(messageProperties[i].Value, true)); messageProperties[i] = new MessageTemplateParameter(uniqueName, duplicateProperty.Value, duplicateProperty.Format, duplicateProperty.CaptureType); } } } } internal static string GenerateUniquePropertyName<TKey, TValue>(string originalName, IDictionary<TKey, TValue> properties, Func<string, IDictionary<TKey, TValue>, bool> containsKey) { originalName = originalName ?? string.Empty; int newNameIndex = 1; var newItemName = string.Concat(originalName, "_1"); while (containsKey(newItemName, properties)) { newItemName = string.Concat(originalName, "_", (++newNameIndex).ToString()); } return newItemName; } IEnumerator<MessageTemplateParameter> IEnumerable<MessageTemplateParameter>.GetEnumerator() { return new ParameterEnumerator(this); } private abstract class DictionaryEnumeratorBase : IDisposable { private readonly PropertiesDictionary _dictionary; private int? _messagePropertiesEnumerator; private bool _eventEnumeratorCreated; private Dictionary<object, PropertyValue>.Enumerator _eventEnumerator; protected DictionaryEnumeratorBase(PropertiesDictionary dictionary) { _dictionary = dictionary; } protected KeyValuePair<object, object> CurrentProperty { get { if (_messagePropertiesEnumerator.HasValue) { var property = _dictionary._messageProperties[_messagePropertiesEnumerator.Value]; return new KeyValuePair<object, object>(property.Name, property.Value); } if (_eventEnumeratorCreated) return new KeyValuePair<object, object>(_eventEnumerator.Current.Key, _eventEnumerator.Current.Value.Value); throw new InvalidOperationException(); } } protected MessageTemplateParameter CurrentParameter { get { if (_messagePropertiesEnumerator.HasValue) { return _dictionary._messageProperties[_messagePropertiesEnumerator.Value]; } if (_eventEnumeratorCreated) { string parameterName = XmlHelper.XmlConvertToString(_eventEnumerator.Current.Key ?? string.Empty) ?? string.Empty; return new MessageTemplateParameter(parameterName, _eventEnumerator.Current.Value.Value, null, CaptureType.Unknown); } throw new InvalidOperationException(); } } public bool MoveNext() { if (_messagePropertiesEnumerator.HasValue) { if (_messagePropertiesEnumerator.Value + 1 < _dictionary._messageProperties.Count) { // Move forward to a key that is not overridden _messagePropertiesEnumerator = FindNextValidMessagePropertyIndex(_messagePropertiesEnumerator.Value + 1); if (_messagePropertiesEnumerator.HasValue) return true; _messagePropertiesEnumerator = _dictionary._eventProperties.Count - 1; } if (HasEventProperties(_dictionary)) { _messagePropertiesEnumerator = null; _eventEnumerator = _dictionary._eventProperties.GetEnumerator(); _eventEnumeratorCreated = true; return MoveNextValidEventProperty(); } return false; } if (_eventEnumeratorCreated) { return MoveNextValidEventProperty(); } if (HasMessageProperties(_dictionary)) { // Move forward to a key that is not overridden _messagePropertiesEnumerator = FindNextValidMessagePropertyIndex(0); if (_messagePropertiesEnumerator.HasValue) { return true; } } if (HasEventProperties(_dictionary)) { _eventEnumerator = _dictionary._eventProperties.GetEnumerator(); _eventEnumeratorCreated = true; return MoveNextValidEventProperty(); } return false; } private static bool HasMessageProperties(PropertiesDictionary propertiesDictionary) { return propertiesDictionary._messageProperties?.Count > 0; } private static bool HasEventProperties(PropertiesDictionary propertiesDictionary) { return propertiesDictionary._eventProperties?.Count > 0; } private bool MoveNextValidEventProperty() { while (_eventEnumerator.MoveNext()) { if (!_eventEnumerator.Current.Value.IsMessageProperty) return true; } return false; } private int? FindNextValidMessagePropertyIndex(int startIndex) { var eventProperties = _dictionary._eventProperties; if (eventProperties is null) return startIndex; for (int i = startIndex; i < _dictionary._messageProperties.Count; ++i) { if (eventProperties.TryGetValue(_dictionary._messageProperties[i].Name, out var valueItem) && valueItem.IsMessageProperty) { return i; } } return null; } public void Dispose() { // Nothing to do } public void Reset() { _messagePropertiesEnumerator = null; _eventEnumeratorCreated = false; _eventEnumerator = default(Dictionary<object, PropertyValue>.Enumerator); } } private sealed class ParameterEnumerator : DictionaryEnumeratorBase, IEnumerator<MessageTemplateParameter> { /// <inheritDoc/> public MessageTemplateParameter Current => CurrentParameter; /// <inheritDoc/> object IEnumerator.Current => CurrentParameter; public ParameterEnumerator(PropertiesDictionary dictionary) : base(dictionary) { } } private sealed class DictionaryEnumerator : DictionaryEnumeratorBase, IEnumerator<KeyValuePair<object, object>> { /// <inheritDoc/> public KeyValuePair<object, object> Current => CurrentProperty; /// <inheritDoc/> object IEnumerator.Current => CurrentProperty; public DictionaryEnumerator(PropertiesDictionary dictionary) : base(dictionary) { } } [DebuggerDisplay("Count = {Count}")] private sealed class DictionaryCollection : ICollection<object> { private readonly PropertiesDictionary _dictionary; private readonly bool _keyCollection; public DictionaryCollection(PropertiesDictionary dictionary, bool keyCollection) { _dictionary = dictionary; _keyCollection = keyCollection; } /// <inheritDoc/> public int Count => _dictionary.Count; /// <inheritDoc/> public bool IsReadOnly => true; /// <summary>Will always throw, as collection is readonly</summary> public void Add(object item) { throw new NotSupportedException(); } /// <summary>Will always throw, as collection is readonly</summary> public void Clear() { throw new NotSupportedException(); } /// <summary>Will always throw, as collection is readonly</summary> public bool Remove(object item) { throw new NotSupportedException(); } /// <inheritDoc/> public bool Contains(object item) { if (_keyCollection) { return _dictionary.ContainsKey(item); } if (!_dictionary.IsEmpty) { if (_dictionary.EventProperties.ContainsValue(new PropertyValue(item, false))) return true; if (_dictionary.EventProperties.ContainsValue(new PropertyValue(item, true))) return true; } return false; } /// <inheritDoc/> public void CopyTo(object[] array, int arrayIndex) { Guard.ThrowIfNull(array); if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); if (!_dictionary.IsEmpty) { foreach (var propertyItem in _dictionary) { array[arrayIndex++] = _keyCollection ? propertyItem.Key : propertyItem.Value; } } } /// <inheritDoc/> public IEnumerator<object> GetEnumerator() { return new DictionaryCollectionEnumerator(_dictionary, _keyCollection); } /// <inheritDoc/> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private sealed class DictionaryCollectionEnumerator : DictionaryEnumeratorBase, IEnumerator<object> { private readonly bool _keyCollection; public DictionaryCollectionEnumerator(PropertiesDictionary dictionary, bool keyCollection) : base(dictionary) { _keyCollection = keyCollection; } /// <inheritDoc/> public object Current => _keyCollection ? CurrentProperty.Key : CurrentProperty.Value; } } /// <summary> /// Special property-key for lookup without being case-sensitive /// </summary> internal class IgnoreCasePropertyKey { private readonly string _propertyName; public IgnoreCasePropertyKey(string propertyName) { _propertyName = propertyName; } public bool Equals(string propertyName) => Equals(_propertyName, propertyName); public override bool Equals(object obj) { if (obj is string stringObj) return Equals(_propertyName, stringObj); else if (obj is IgnoreCasePropertyKey ignoreCase) return Equals(_propertyName, ignoreCase._propertyName); else return false; } public override int GetHashCode() { return GetHashCode(_propertyName); } public override string ToString() => _propertyName; internal static int GetHashCode(string propertyName) { return StringComparer.OrdinalIgnoreCase.GetHashCode(propertyName); } internal static bool Equals(string x, string y) { return string.Equals(x, y, StringComparison.OrdinalIgnoreCase); } } /// <summary> /// Property-Key equality-comparer that uses string-hashcode from OrdinalIgnoreCase /// Enables case-insensitive lookup using <see cref="IgnoreCasePropertyKey"/> /// </summary> private sealed class PropertyKeyComparer : IEqualityComparer<object> { public static readonly PropertyKeyComparer Default = new PropertyKeyComparer(); public new bool Equals(object x, object y) { if (y is IgnoreCasePropertyKey ynocase && x is string xstring) { return ynocase.Equals(xstring); } else if (x is IgnoreCasePropertyKey xnocase && y is string ystring) { return xnocase.Equals(ystring); } else { return EqualityComparer<object>.Default.Equals(x, y); } } public int GetHashCode(object obj) { if (obj is string objstring) return IgnoreCasePropertyKey.GetHashCode(objstring); else return EqualityComparer<object>.Default.GetHashCode(obj); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections.Generic; using NLog.Common; /// <summary> /// Keeps track of pending operation count, and can notify when pending operation count reaches zero /// </summary> internal class AsyncOperationCounter { private int _pendingOperationCounter; private readonly LinkedList<AsyncContinuation> _pendingCompletionList = new LinkedList<AsyncContinuation>(); /// <summary> /// Mark operation has started /// </summary> public void BeginOperation() { System.Threading.Interlocked.Increment(ref _pendingOperationCounter); } /// <summary> /// Mark operation has completed /// </summary> /// <param name="exception">Exception coming from the completed operation [optional]</param> public void CompleteOperation(Exception exception) { NotifyCompletion(exception); } private int NotifyCompletion(Exception exception) { int pendingOperations = System.Threading.Interlocked.Decrement(ref _pendingOperationCounter); if (_pendingCompletionList.Count > 0) { lock (_pendingCompletionList) { var nodeNext = _pendingCompletionList.First; while (nodeNext != null) { var nodeValue = nodeNext.Value; nodeNext = nodeNext.Next; nodeValue(exception); // Will modify _pendingCompletionList } } } return pendingOperations; } /// <summary> /// Registers an AsyncContinuation to be called when all pending operations have completed /// </summary> /// <param name="asyncContinuation">Invoked on completion</param> /// <returns>AsyncContinuation operation</returns> public AsyncContinuation RegisterCompletionNotification(AsyncContinuation asyncContinuation) { // We only want to wait for the operations currently in progress (not the future operations) int remainingCompletionCounter = System.Threading.Interlocked.Increment(ref _pendingOperationCounter); if (remainingCompletionCounter <= 1) { // No active operations if (NotifyCompletion(null) < 0) { System.Threading.Interlocked.Exchange(ref _pendingOperationCounter, 0); } return asyncContinuation; } else { lock (_pendingCompletionList) { if (NotifyCompletion(null) <= 0) { return asyncContinuation; // No active operations } var pendingCompletion = new LinkedListNode<AsyncContinuation>(null); _pendingCompletionList.AddLast(pendingCompletion); remainingCompletionCounter = System.Threading.Interlocked.Increment(ref _pendingOperationCounter); if (remainingCompletionCounter <= 0) { remainingCompletionCounter = 1; } pendingCompletion.Value = (ex) => { if (System.Threading.Interlocked.Decrement(ref remainingCompletionCounter) == 0) { lock (_pendingCompletionList) { _pendingCompletionList.Remove(pendingCompletion); NotifyCompletion(ex); } asyncContinuation(ex); } }; return pendingCompletion.Value; } } } /// <summary> /// Clear o /// </summary> public void Clear() { _pendingCompletionList.Clear(); System.Threading.Interlocked.Exchange(ref _pendingOperationCounter, 0); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Common { using System; using NLog.Internal; /// <summary> /// String Conversion Helpers /// </summary> public static class ConversionHelpers { /// <summary> /// Converts input string value into <see cref="System.Enum"/>. Parsing is case-insensitive. /// </summary> /// <param name="inputValue">Input value</param> /// <param name="resultValue">Output value</param> /// <param name="defaultValue">Default value</param> /// <returns>Returns false if the input value could not be parsed</returns> public static bool TryParseEnum<TEnum>(string inputValue, out TEnum resultValue, TEnum defaultValue = default(TEnum)) where TEnum : struct { if (!TryParseEnum(inputValue, true, out resultValue)) { resultValue = defaultValue; return false; } return true; } /// <summary> /// Converts input string value into <see cref="System.Enum"/>. Parsing is case-insensitive. /// </summary> /// <param name="inputValue">Input value</param> /// <param name="enumType">The type of the enum</param> /// <param name="resultValue">Output value. Null if parse failed</param> internal static bool TryParseEnum(string inputValue, Type enumType, out object resultValue) { if (StringHelpers.IsNullOrWhiteSpace(inputValue)) { resultValue = null; return false; } // Note: .NET Standard 2.1 added a public Enum.TryParse(Type) try { resultValue = Enum.Parse(enumType, inputValue, true); return true; } catch (ArgumentException) { resultValue = null; return false; } } /// <summary> /// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. The return value indicates whether the conversion succeeded. /// </summary> /// <typeparam name="TEnum">The enumeration type to which to convert value.</typeparam> /// <param name="inputValue">The string representation of the enumeration name or underlying value to convert.</param> /// <param name="ignoreCase"><c>true</c> to ignore case; <c>false</c> to consider case.</param> /// <param name="resultValue">When this method returns, result contains an object of type TEnum whose value is represented by value if the parse operation succeeds. If the parse operation fails, result contains the default value of the underlying type of TEnum. Note that this value need not be a member of the TEnum enumeration. This parameter is passed uninitialized.</param> /// <returns><c>true</c> if the value parameter was converted successfully; otherwise, <c>false</c>.</returns> /// <remarks>Wrapper because Enum.TryParse is not present in .net 3.5</remarks> internal static bool TryParseEnum<TEnum>(string inputValue, bool ignoreCase, out TEnum resultValue) where TEnum : struct { if (StringHelpers.IsNullOrWhiteSpace(inputValue)) { resultValue = default(TEnum); return false; } #if !NET35 return Enum.TryParse(inputValue, ignoreCase, out resultValue); #else return TryParseEnum_net3(inputValue, ignoreCase, out resultValue); #endif } /// <summary> /// Enum.TryParse implementation for .net 3.5 /// /// </summary> /// <returns></returns> /// <remarks>Don't uses reflection</remarks> // ReSharper disable once UnusedMember.Local private static bool TryParseEnum_net3<TEnum>(string value, bool ignoreCase, out TEnum result) where TEnum : struct { var enumType = typeof(TEnum); if (!enumType.IsEnum()) throw new ArgumentException($"Type '{enumType.FullName}' is not an enum"); if (StringHelpers.IsNullOrWhiteSpace(value)) { result = default(TEnum); return false; } try { result = (TEnum)Enum.Parse(enumType, value, ignoreCase); return true; } catch (Exception) { result = default(TEnum); return false; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Text; namespace NLog.Internal { /// <summary> /// Split a string /// </summary> internal static class StringSplitter { /// <summary> /// Split a string, optional quoted value /// </summary> /// <param name="text">Text to split</param> /// <param name="splitChar">Character to split the <paramref name="text" /></param> /// <param name="quoteChar">Quote character</param> /// <param name="escapeChar"> /// Escape for the <paramref name="quoteChar" />, not escape for the <paramref name="splitChar" /> /// , use quotes for that. /// </param> public static IEnumerable<string> SplitQuoted(this string text, char splitChar, char quoteChar, char escapeChar) { if (!string.IsNullOrEmpty(text)) { if (splitChar == quoteChar) { throw new NotSupportedException("Quote character should different from split character"); } if (splitChar == escapeChar) { throw new NotSupportedException("Escape character should different from split character"); } return SplitQuoted2(text, splitChar, quoteChar, escapeChar); } return ArrayHelper.Empty<string>(); } /// <summary> /// Split a string, optional quoted value /// </summary> /// <param name="text">Text to split</param> /// <param name="splitChar">Character to split the <paramref name="text" /></param> /// <param name="quoteChar">Quote character</param> /// <param name="escapeChar"> /// Escape for the <paramref name="quoteChar" />, not escape for the <paramref name="splitChar" /> /// , use quotes for that. /// </param> private static IEnumerable<string> SplitQuoted2(string text, char splitChar, char quoteChar, char escapeChar) { bool inQuotedMode = false; bool prevEscape = false; bool prevQuote = false; bool doubleQuotesEscapes = escapeChar == quoteChar; // Special mode var item = new StringBuilder(); foreach (var c in text) { if (c == quoteChar) { if (inQuotedMode) { if (prevEscape && !doubleQuotesEscapes) { item.Append(c); // Escaped quote-char in quoted-mode prevEscape = false; prevQuote = false; } else if (prevQuote && doubleQuotesEscapes) { // Double quote, means escaped quote, quoted-mode not real item.Append(c); inQuotedMode = false; prevEscape = false; prevQuote = false; } else if (item.Length > 0) { // quoted-mode ended with something to yield inQuotedMode = false; yield return item.ToString(); item.Length = 0; // Start new item prevEscape = false; prevQuote = true; // signal that item is empty, because it has just been yielded after quoted-mode } else { // quoted-mode ended without anything to yield inQuotedMode = false; prevEscape = false; prevQuote = false; } } else { if (item.Length != 0 || prevEscape) { // Quoted-mode can only be activated initially item.Append(c); prevEscape = false; prevQuote = false; } else { // Quoted-mode is now activated prevEscape = c == escapeChar; prevQuote = true; inQuotedMode = true; } } } else if (c == escapeChar) { if (prevEscape) item.Append(escapeChar); // Escape-chars are only stripped in quoted-mode when placed before quote prevEscape = true; prevQuote = false; } else if (inQuotedMode) { item.Append(c); prevEscape = false; prevQuote = false; } else if (c == splitChar) { if (prevEscape) item.Append(escapeChar); // Escape-chars are only stripped in quoted-mode when placed before quote if (item.Length > 0 || !prevQuote) { yield return item.ToString(); item.Length = 0; // Start new item } prevEscape = false; prevQuote = false; } else { if (prevEscape) item.Append(escapeChar); // Escape-chars are only stripped in quoted-mode when placed before quote item.Append(c); prevEscape = false; prevQuote = false; } } if (prevEscape && !doubleQuotesEscapes) item.Append(escapeChar); // incomplete escape-sequence, means escape should be included if (inQuotedMode) { // incomplete quoted-mode, means quotes should be included if (prevQuote) { item.Append(quoteChar); } else { item.Insert(0, quoteChar); } } if (item.Length > 0 || !prevQuote) yield return item.ToString(); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Common { using System; using System.Collections.Generic; using System.Text; using System.Threading; using NLog.Internal; /// <summary> /// Helpers for asynchronous operations. /// </summary> public static class AsyncHelpers { internal static int GetManagedThreadId() { #if !NETSTANDARD1_3 return Thread.CurrentThread.ManagedThreadId; #else return System.Environment.CurrentManagedThreadId; #endif } internal static void StartAsyncTask(AsyncHelpersTask asyncTask, object state) { var asyncDelegate = asyncTask.AsyncDelegate; #if !NETSTANDARD1_3 && !NETSTANDARD1_5 ThreadPool.QueueUserWorkItem(asyncDelegate, state); #else System.Threading.Tasks.Task.Factory.StartNew(asyncDelegate, state, CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default); #endif } internal static void WaitForDelay(TimeSpan delay) { #if !NETSTANDARD1_3 Thread.Sleep(delay); #else System.Threading.Tasks.Task.Delay(delay).ConfigureAwait(false).GetAwaiter().GetResult(); #endif } /// <summary> /// Iterates over all items in the given collection and runs the specified action /// in sequence (each action executes only after the preceding one has completed without an error). /// </summary> /// <typeparam name="T">Type of each item.</typeparam> /// <param name="items">The items to iterate.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke once all items /// have been iterated.</param> /// <param name="action">The action to invoke for each item.</param> [Obsolete("Marked obsolete on NLog 5.0")] public static void ForEachItemSequentially<T>(IEnumerable<T> items, AsyncContinuation asyncContinuation, AsynchronousAction<T> action) { action = ExceptionGuard(action); IEnumerator<T> enumerator = items.GetEnumerator(); void InvokeNext(Exception ex) { if (ex != null) { asyncContinuation(ex); return; } if (!enumerator.MoveNext()) { enumerator.Dispose(); asyncContinuation(null); return; } action(enumerator.Current, PreventMultipleCalls(InvokeNext)); } InvokeNext(null); } /// <summary> /// Repeats the specified asynchronous action multiple times and invokes asynchronous continuation at the end. /// </summary> /// <param name="repeatCount">The repeat count.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke at the end.</param> /// <param name="action">The action to invoke.</param> public static void Repeat(int repeatCount, AsyncContinuation asyncContinuation, AsynchronousAction action) { action = ExceptionGuard(action); int remaining = repeatCount; void InvokeNext(Exception ex) { if (ex != null) { asyncContinuation(ex); return; } if (remaining-- <= 0) { asyncContinuation(null); return; } action(PreventMultipleCalls(InvokeNext)); } InvokeNext(null); } /// <summary> /// Modifies the continuation by pre-pending given action to execute just before it. /// </summary> /// <param name="asyncContinuation">The async continuation.</param> /// <param name="action">The action to pre-pend.</param> /// <returns>Continuation which will execute the given action before forwarding to the actual continuation.</returns> [Obsolete("Marked obsolete on NLog 5.0")] public static AsyncContinuation PrecededBy(AsyncContinuation asyncContinuation, AsynchronousAction action) { action = ExceptionGuard(action); AsyncContinuation continuation = ex => { if (ex != null) { // if got exception from original invocation, don't execute action asyncContinuation(ex); return; } // call the action and continue action(PreventMultipleCalls(asyncContinuation)); }; return continuation; } /// <summary> /// Attaches a timeout to a continuation which will invoke the continuation when the specified /// timeout has elapsed. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeout">The timeout.</param> /// <returns>Wrapped continuation.</returns> public static AsyncContinuation WithTimeout(AsyncContinuation asyncContinuation, TimeSpan timeout) { return new TimeoutContinuation(asyncContinuation, timeout).Function; } /// <summary> /// Iterates over all items in the given collection and runs the specified action /// in parallel (each action executes on a thread from thread pool). /// </summary> /// <typeparam name="T">Type of each item.</typeparam> /// <param name="values">The items to iterate.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke once all items /// have been iterated.</param> /// <param name="action">The action to invoke for each item.</param> public static void ForEachItemInParallel<T>(IEnumerable<T> values, AsyncContinuation asyncContinuation, AsynchronousAction<T> action) { action = ExceptionGuard(action); var items = new List<T>(values); int remaining = items.Count; var exceptions = new List<Exception>(); InternalLogger.Trace("ForEachItemInParallel() {0} items", items.Count); if (remaining == 0) { asyncContinuation(null); return; } AsyncContinuation continuation = ex => { InternalLogger.Trace("Continuation invoked: {0}", ex); if (ex != null) { lock (exceptions) { exceptions.Add(ex); } } var r = Interlocked.Decrement(ref remaining); InternalLogger.Trace("Parallel task completed. {0} items remaining", r); if (r == 0) { asyncContinuation(GetCombinedException(exceptions)); } }; foreach (T item in items) { T itemCopy = item; StartAsyncTask(new AsyncHelpersTask(s => { var preventMultipleCalls = PreventMultipleCalls(continuation); try { action(itemCopy, preventMultipleCalls); } catch (Exception ex) { #if DEBUG if (ex.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } #endif InternalLogger.Error(ex, "ForEachItemInParallel - Unhandled Exception"); preventMultipleCalls.Invoke(ex); } }), null); } } /// <summary> /// Runs the specified asynchronous action synchronously (blocks until the continuation has /// been invoked). /// </summary> /// <param name="action">The action.</param> /// <remarks> /// Using this method is not recommended because it will block the calling thread. /// </remarks> [Obsolete("Marked obsolete on NLog 5.0")] public static void RunSynchronously(AsynchronousAction action) { var ev = new ManualResetEvent(false); Exception lastException = null; action(PreventMultipleCalls(ex => { lastException = ex; ev.Set(); })); ev.WaitOne(); if (lastException != null) { throw new NLogRuntimeException("Asynchronous exception has occurred.", lastException); } } /// <summary> /// Wraps the continuation with a guard which will only make sure that the continuation function /// is invoked only once. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <returns>Wrapped asynchronous continuation.</returns> public static AsyncContinuation PreventMultipleCalls(AsyncContinuation asyncContinuation) { if (asyncContinuation.Target is SingleCallContinuation) { return asyncContinuation; } return new SingleCallContinuation(asyncContinuation).Function; } /// <summary> /// Gets the combined exception from all exceptions in the list. /// </summary> /// <param name="exceptions">The exceptions.</param> /// <returns>Combined exception or null if no exception was thrown.</returns> public static Exception GetCombinedException(IList<Exception> exceptions) { if (exceptions.Count == 0) { return null; } if (exceptions.Count == 1) { return exceptions[0]; } var sb = new StringBuilder(); string separator = string.Empty; string newline = EnvironmentHelper.NewLine; foreach (var ex in exceptions) { sb.Append(separator); sb.Append(ex.ToString()); sb.Append(newline); separator = newline; } return new NLogRuntimeException("Got multiple exceptions:\r\n" + sb); } private static AsynchronousAction ExceptionGuard(AsynchronousAction action) { return cont => { try { action(cont); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } cont(exception); } }; } private static AsynchronousAction<T> ExceptionGuard<T>(AsynchronousAction<T> action) { return (T argument, AsyncContinuation cont) => { try { action(argument, cont); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } cont(exception); } }; } /// <summary> /// Disposes the Timer, and waits for it to leave the Timer-callback-method /// </summary> /// <param name="timer">The Timer object to dispose</param> /// <param name="timeout">Timeout to wait (TimeSpan.Zero means dispose without waiting)</param> /// <returns>Timer disposed within timeout (true/false)</returns> internal static bool WaitForDispose(this Timer timer, TimeSpan timeout) { timer.Change(Timeout.Infinite, Timeout.Infinite); if (timeout != TimeSpan.Zero) { ManualResetEvent waitHandle = new ManualResetEvent(false); if (timer.Dispose(waitHandle) && !waitHandle.WaitOne((int)timeout.TotalMilliseconds)) { return false; // Return without waiting for timer, and without closing waitHandle (Avoid ObjectDisposedException) } waitHandle.Close(); } else { timer.Dispose(); } return true; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Reflection; using System.Text; #if !NETSTANDARD1_3 && !NETSTANDARD1_5 using System.Transactions; #endif using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; #if !NETSTANDARD using System.Configuration; using ConfigurationManager = System.Configuration.ConfigurationManager; #endif /// <summary> /// Writes log messages to the database using an ADO.NET provider. /// </summary> /// <remarks> /// <para> /// Note .NET Core application cannot load connectionstrings from app.config / web.config. Instead use ${configsetting} /// </para> /// <a href="https://github.com/nlog/nlog/wiki/Database-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/Database-target">Documentation on NLog Wiki</seealso> /// <example> /// <para> /// The configuration is dependent on the database type, because /// there are different methods of specifying connection string, SQL /// command and command parameters. /// </para> /// <para>MS SQL Server using System.Data.SqlClient:</para> /// <code lang="XML" source="examples/targets/Configuration File/Database/MSSQL/NLog.config" height="450" /> /// <para>Oracle using System.Data.OracleClient:</para> /// <code lang="XML" source="examples/targets/Configuration File/Database/Oracle.Native/NLog.config" height="350" /> /// <para>Oracle using System.Data.OleDBClient:</para> /// <code lang="XML" source="examples/targets/Configuration File/Database/Oracle.OleDB/NLog.config" height="350" /> /// <para>To set up the log target programmatically use code like this (an equivalent of MSSQL configuration):</para> /// <code lang="C#" source="examples/targets/Configuration API/Database/MSSQL/Example.cs" height="630" /> /// </example> [Target("Database")] public class DatabaseTarget : Target, IInstallable { private IDbConnection _activeConnection; private string _activeConnectionString; /// <summary> /// Initializes a new instance of the <see cref="DatabaseTarget" /> class. /// </summary> public DatabaseTarget() { DBProvider = "sqlserver"; DBHost = "."; #if !NETSTANDARD ConnectionStringsSettings = ConfigurationManager.ConnectionStrings; #endif CommandType = CommandType.Text; } /// <summary> /// Initializes a new instance of the <see cref="DatabaseTarget" /> class. /// </summary> /// <param name="name">Name of the target.</param> public DatabaseTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets the name of the database provider. /// </summary> /// <remarks> /// <para> /// The parameter name should be a provider invariant name as registered in machine.config or app.config. Common values are: /// </para> /// <ul> /// <li><c>System.Data.SqlClient</c> - <see href="https://msdn.microsoft.com/en-us/library/system.data.sqlclient.aspx">SQL Sever Client</see></li> /// <li><c>System.Data.SqlServerCe.3.5</c> - <see href="https://www.microsoft.com/sqlserver/2005/en/us/compact.aspx">SQL Sever Compact 3.5</see></li> /// <li><c>System.Data.OracleClient</c> - <see href="https://msdn.microsoft.com/en-us/library/system.data.oracleclient.aspx">Oracle Client from Microsoft</see> (deprecated in .NET Framework 4)</li> /// <li><c>Oracle.DataAccess.Client</c> - <see href="https://www.oracle.com/technology/tech/windows/odpnet/index.html">ODP.NET provider from Oracle</see></li> /// <li><c>System.Data.SQLite</c> - <see href="http://sqlite.phxsoftware.com/">System.Data.SQLite driver for SQLite</see></li> /// <li><c>Npgsql</c> - <see href="https://www.npgsql.org/">Npgsql driver for PostgreSQL</see></li> /// <li><c>MySql.Data.MySqlClient</c> - <see href="https://www.mysql.com/downloads/connector/net/">MySQL Connector/Net</see></li> /// </ul> /// <para>(Note that provider invariant names are not supported on .NET Compact Framework).</para> /// <para> /// Alternatively the parameter value can be be a fully qualified name of the provider /// connection type (class implementing <see cref="IDbConnection" />) or one of the following tokens: /// </para> /// <ul> /// <li><c>sqlserver</c>, <c>mssql</c>, <c>microsoft</c> or <c>msde</c> - SQL Server Data Provider</li> /// <li><c>oledb</c> - OLEDB Data Provider</li> /// <li><c>odbc</c> - ODBC Data Provider</li> /// </ul> /// </remarks> /// <docgen category='Connection Options' order='10' /> [RequiredParameter] [DefaultValue("sqlserver")] public string DBProvider { get; set; } #if !NETSTANDARD /// <summary> /// Gets or sets the name of the connection string (as specified in <see href="https://msdn.microsoft.com/en-us/library/bf7sd233.aspx">&lt;connectionStrings&gt; configuration section</see>. /// </summary> /// <docgen category='Connection Options' order='50' /> public string ConnectionStringName { get; set; } #endif /// <summary> /// Gets or sets the connection string. When provided, it overrides the values /// specified in DBHost, DBUserName, DBPassword, DBDatabase. /// </summary> /// <docgen category='Connection Options' order='10' /> public Layout ConnectionString { get; set; } /// <summary> /// Gets or sets the connection string using for installation and uninstallation. If not provided, regular ConnectionString is being used. /// </summary> /// <docgen category='Installation Options' order='100' /> public Layout InstallConnectionString { get; set; } /// <summary> /// Gets the installation DDL commands. /// </summary> /// <docgen category='Installation Options' order='100' /> [ArrayParameter(typeof(DatabaseCommandInfo), "install-command")] public IList<DatabaseCommandInfo> InstallDdlCommands { get; } = new List<DatabaseCommandInfo>(); /// <summary> /// Gets the uninstallation DDL commands. /// </summary> /// <docgen category='Installation Options' order='100' /> [ArrayParameter(typeof(DatabaseCommandInfo), "uninstall-command")] public IList<DatabaseCommandInfo> UninstallDdlCommands { get; } = new List<DatabaseCommandInfo>(); /// <summary> /// Gets or sets a value indicating whether to keep the /// database connection open between the log events. /// </summary> /// <docgen category='Connection Options' order='10' /> [DefaultValue(false)] public bool KeepConnection { get; set; } /// <summary> /// Gets or sets the database host name. If the ConnectionString is not provided /// this value will be used to construct the "Server=" part of the /// connection string. /// </summary> /// <docgen category='Connection Options' order='50' /> public Layout DBHost { get; set; } /// <summary> /// Gets or sets the database user name. If the ConnectionString is not provided /// this value will be used to construct the "User ID=" part of the /// connection string. /// </summary> /// <docgen category='Connection Options' order='50' /> public Layout DBUserName { get; set; } /// <summary> /// Gets or sets the database password. If the ConnectionString is not provided /// this value will be used to construct the "Password=" part of the /// connection string. /// </summary> /// <docgen category='Connection Options' order='50' /> public Layout DBPassword { get => _dbPassword; set { _dbPassword = value; if (value is SimpleLayout simpleLayout && simpleLayout.IsFixedText) _dbPasswordFixed = EscapeValueForConnectionString(simpleLayout.OriginalText); else _dbPasswordFixed = null; } } private Layout _dbPassword; private string _dbPasswordFixed; /// <summary> /// Gets or sets the database name. If the ConnectionString is not provided /// this value will be used to construct the "Database=" part of the /// connection string. /// </summary> /// <docgen category='Connection Options' order='50' /> public Layout DBDatabase { get; set; } /// <summary> /// Gets or sets the text of the SQL command to be run on each log level. /// </summary> /// <remarks> /// Typically this is a SQL INSERT statement or a stored procedure call. /// It should use the database-specific parameters (marked as <c>@parameter</c> /// for SQL server or <c>:parameter</c> for Oracle, other data providers /// have their own notation) and not the layout renderers, /// because the latter is prone to SQL injection attacks. /// The layout renderers should be specified as &lt;parameter /&gt; elements instead. /// </remarks> /// <docgen category='SQL Statement' order='10' /> [RequiredParameter] public Layout CommandText { get; set; } /// <summary> /// Gets or sets the type of the SQL command to be run on each log level. /// </summary> /// <remarks> /// This specifies how the command text is interpreted, as "Text" (default) or as "StoredProcedure". /// When using the value StoredProcedure, the commandText-property would /// normally be the name of the stored procedure. TableDirect method is not supported in this context. /// </remarks> /// <docgen category='SQL Statement' order='11' /> [DefaultValue(CommandType.Text)] public CommandType CommandType { get; set; } /// <summary> /// Gets the collection of parameters. Each item contains a mapping /// between NLog layout and a database named or positional parameter. /// </summary> /// <docgen category='SQL Statement' order='14' /> [ArrayParameter(typeof(DatabaseParameterInfo), "parameter")] public IList<DatabaseParameterInfo> Parameters { get; } = new List<DatabaseParameterInfo>(); /// <summary> /// Gets the collection of properties. Each item contains a mapping /// between NLog layout and a property on the DbConnection instance /// </summary> /// <docgen category='Connection Options' order='50' /> [ArrayParameter(typeof(DatabaseObjectPropertyInfo), "connectionproperty")] public IList<DatabaseObjectPropertyInfo> ConnectionProperties { get; } = new List<DatabaseObjectPropertyInfo>(); /// <summary> /// Gets the collection of properties. Each item contains a mapping /// between NLog layout and a property on the DbCommand instance /// </summary> /// <docgen category='Connection Options' order='50' /> [ArrayParameter(typeof(DatabaseObjectPropertyInfo), "commandproperty")] public IList<DatabaseObjectPropertyInfo> CommandProperties { get; } = new List<DatabaseObjectPropertyInfo>(); /// <summary> /// Configures isolated transaction batch writing. If supported by the database, then it will improve insert performance. /// </summary> /// <docgen category='Performance Tuning Options' order='10' /> public System.Data.IsolationLevel? IsolationLevel { get; set; } #if !NETSTANDARD internal DbProviderFactory ProviderFactory { get; set; } // this is so we can mock the connection string without creating sub-processes internal ConnectionStringSettingsCollection ConnectionStringsSettings { get; set; } #endif internal Type ConnectionType { get; private set; } /// <summary> /// Performs installation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Install(InstallationContext installationContext) { RunInstallCommands(installationContext, InstallDdlCommands); } /// <summary> /// Performs uninstallation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Uninstall(InstallationContext installationContext) { RunInstallCommands(installationContext, UninstallDdlCommands); } /// <summary> /// Determines whether the item is installed. /// </summary> /// <param name="installationContext">The installation context.</param> /// <returns> /// Value indicating whether the item is installed or null if it is not possible to determine. /// </returns> public bool? IsInstalled(InstallationContext installationContext) { return null; } internal IDbConnection OpenConnection(string connectionString, LogEventInfo logEventInfo) { IDbConnection connection; #if !NETSTANDARD if (ProviderFactory != null) { connection = ProviderFactory.CreateConnection(); } else #endif { connection = (IDbConnection)Activator.CreateInstance(ConnectionType); } if (connection is null) { throw new NLogRuntimeException("Creation of connection failed"); } connection.ConnectionString = connectionString; if (ConnectionProperties?.Count > 0) { ApplyDatabaseObjectProperties(connection, ConnectionProperties, logEventInfo ?? LogEventInfo.CreateNullEvent()); } connection.Open(); return connection; } private void ApplyDatabaseObjectProperties(object databaseObject, IList<DatabaseObjectPropertyInfo> objectProperties, LogEventInfo logEventInfo) { for (int i = 0; i < objectProperties.Count; ++i) { var propertyInfo = objectProperties[i]; try { var propertyValue = propertyInfo.RenderValue(logEventInfo); if (!propertyInfo.SetPropertyValue(databaseObject, propertyValue)) { InternalLogger.Warn("{0}: Failed to lookup property {1} on {2}", this, propertyInfo.Name, databaseObject.GetType()); } } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed to assign value for property {1} on {2}", this, propertyInfo.Name, databaseObject.GetType()); if (LogManager.ThrowExceptions) throw; } } } /// <inheritdoc/> protected override void InitializeTarget() { base.InitializeTarget(); bool foundProvider = false; string providerName = string.Empty; #if !NETSTANDARD if (!string.IsNullOrEmpty(ConnectionStringName)) { // read connection string and provider factory from the configuration file var cs = ConnectionStringsSettings[ConnectionStringName]; if (cs is null) { throw new NLogConfigurationException($"Connection string '{ConnectionStringName}' is not declared in <connectionStrings /> section."); } if (!string.IsNullOrEmpty(cs.ConnectionString?.Trim())) { ConnectionString = SimpleLayout.Escape(cs.ConnectionString.Trim()); } providerName = cs.ProviderName?.Trim() ?? string.Empty; } #endif if (ConnectionString != null) { providerName = InitConnectionString(providerName); } #if !NETSTANDARD if (string.IsNullOrEmpty(providerName)) { providerName = GetProviderNameFromDbProviderFactories(providerName); } if (!string.IsNullOrEmpty(providerName)) { foundProvider = InitProviderFactory(providerName); } #endif if (!foundProvider) { try { SetConnectionType(); if (ConnectionType is null) { InternalLogger.Warn("{0}: No ConnectionType created from DBProvider={1}", this, DBProvider); } } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed to create ConnectionType from DBProvider={1}", this, DBProvider); throw; } } } private string InitConnectionString(string providerName) { try { var connectionString = BuildConnectionString(LogEventInfo.CreateNullEvent()); var dbConnectionStringBuilder = new DbConnectionStringBuilder { ConnectionString = connectionString }; if (dbConnectionStringBuilder.TryGetValue("provider connection string", out var connectionStringValue)) { // Special Entity Framework Connection String if (dbConnectionStringBuilder.TryGetValue("provider", out var providerValue)) { // Provider was overriden by ConnectionString providerName = providerValue.ToString()?.Trim() ?? string.Empty; } // ConnectionString was overriden by ConnectionString :) ConnectionString = SimpleLayout.Escape(connectionStringValue.ToString()); } } catch (Exception ex) { #if !NETSTANDARD if (!string.IsNullOrEmpty(ConnectionStringName)) InternalLogger.Warn(ex, "{0}: DbConnectionStringBuilder failed to parse '{1}' ConnectionString", this, ConnectionStringName); else #endif InternalLogger.Warn(ex, "{0}: DbConnectionStringBuilder failed to parse ConnectionString", this); } return providerName; } #if !NETSTANDARD private bool InitProviderFactory(string providerName) { bool foundProvider; try { ProviderFactory = DbProviderFactories.GetFactory(providerName); foundProvider = true; } catch (Exception ex) { InternalLogger.Error(ex, "{0}: DbProviderFactories failed to get factory from ProviderName={1}", this, providerName); throw; } return foundProvider; } private string GetProviderNameFromDbProviderFactories(string providerName) { string dbProvider = DBProvider?.Trim() ?? string.Empty; if (!string.IsNullOrEmpty(dbProvider)) { foreach (DataRow row in DbProviderFactories.GetFactoryClasses().Rows) { var invariantname = (string)row["InvariantName"]; if (string.Equals(invariantname, dbProvider, StringComparison.OrdinalIgnoreCase)) { providerName = invariantname; break; } } } return providerName; } #endif /// <summary> /// Set the <see cref="ConnectionType"/> to use it for opening connections to the database. /// </summary> private void SetConnectionType() { switch (DBProvider.ToUpperInvariant()) { case "SQLSERVER": case "MSSQL": case "MICROSOFT": case "MSDE": #if NETSTANDARD { try { var assembly = Assembly.Load(new AssemblyName("Microsoft.Data.SqlClient")); ConnectionType = assembly.GetType("Microsoft.Data.SqlClient.SqlConnection", true, true); } catch (Exception ex) { InternalLogger.Warn(ex, "{0}: Failed to load assembly 'Microsoft.Data.SqlClient'. Falling back to 'System.Data.SqlClient'.", this); var assembly = Assembly.Load(new AssemblyName("System.Data.SqlClient")); ConnectionType = assembly.GetType("System.Data.SqlClient.SqlConnection", true, true); } break; } case "SYSTEM.DATA.SQLCLIENT": { var assembly = Assembly.Load(new AssemblyName("System.Data.SqlClient")); ConnectionType = assembly.GetType("System.Data.SqlClient.SqlConnection", true, true); break; } #else case "SYSTEM.DATA.SQLCLIENT": { var assembly = typeof(IDbConnection).GetAssembly(); ConnectionType = assembly.GetType("System.Data.SqlClient.SqlConnection", true, true); break; } #endif case "MICROSOFT.DATA.SQLCLIENT": { var assembly = Assembly.Load(new AssemblyName("Microsoft.Data.SqlClient")); ConnectionType = assembly.GetType("Microsoft.Data.SqlClient.SqlConnection", true, true); break; } #if !NETSTANDARD case "OLEDB": { var assembly = typeof(IDbConnection).GetAssembly(); ConnectionType = assembly.GetType("System.Data.OleDb.OleDbConnection", true, true); break; } #endif case "ODBC": case "SYSTEM.DATA.ODBC": { #if NETSTANDARD var assembly = Assembly.Load(new AssemblyName("System.Data.Odbc")); #else var assembly = typeof(IDbConnection).GetAssembly(); #endif ConnectionType = assembly.GetType("System.Data.Odbc.OdbcConnection", true, true); break; } default: ConnectionType = Type.GetType(DBProvider, true, true); break; } } /// <inheritdoc/> protected override void CloseTarget() { base.CloseTarget(); InternalLogger.Trace("{0}: Close connection because of CloseTarget", this); CloseConnection(); } /// <summary> /// Writes the specified logging event to the database. It creates /// a new database command, prepares parameters for it by calculating /// layouts and executes the command. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(LogEventInfo logEvent) { try { WriteLogEventSuppressTransactionScope(logEvent, BuildConnectionString(logEvent)); } finally { if (!KeepConnection) { InternalLogger.Trace("{0}: Close connection (KeepConnection = false).", this); CloseConnection(); } } } /// <summary> /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected override void Write(IList<AsyncLogEventInfo> logEvents) { var buckets = GroupInBuckets(logEvents); if (buckets.Count == 1) { var firstBucket = System.Linq.Enumerable.First(buckets); WriteLogEventsToDatabase(firstBucket.Value, firstBucket.Key); } else { foreach (var bucket in buckets) WriteLogEventsToDatabase(bucket.Value, bucket.Key); } } private ICollection<KeyValuePair<string, IList<AsyncLogEventInfo>>> GroupInBuckets(IList<AsyncLogEventInfo> logEvents) { if (logEvents.Count == 0) { #if !NET35 && !NET45 return Array.Empty<KeyValuePair<string, IList<AsyncLogEventInfo>>>(); #else return new KeyValuePair<string, IList<AsyncLogEventInfo>>[0]; #endif } string firstConnectionString = BuildConnectionString(logEvents[0].LogEvent); IDictionary<string, IList<AsyncLogEventInfo>> dictionary = null; for (int i = 1; i < logEvents.Count; ++i) { var connectionString = BuildConnectionString(logEvents[i].LogEvent); if (dictionary is null) { if (connectionString == firstConnectionString) continue; var firstBucket = new List<AsyncLogEventInfo>(i); for (int j = 0; j < i; ++j) firstBucket.Add(logEvents[j]); dictionary = new Dictionary<string, IList<AsyncLogEventInfo>>(StringComparer.Ordinal) { { firstConnectionString, firstBucket } }; } if (!dictionary.TryGetValue(connectionString, out var bucket)) bucket = dictionary[connectionString] = new List<AsyncLogEventInfo>(); bucket.Add(logEvents[i]); } return (ICollection<KeyValuePair<string, IList<AsyncLogEventInfo>>>)dictionary ?? new KeyValuePair<string, IList<AsyncLogEventInfo>>[] { new KeyValuePair<string, IList<AsyncLogEventInfo>>(firstConnectionString, logEvents) }; } private void WriteLogEventsToDatabase(IList<AsyncLogEventInfo> logEvents, string connectionString) { try { if (IsolationLevel.HasValue && logEvents.Count > 1) { WriteLogEventsWithTransactionScope(logEvents, connectionString); } else { WriteLogEventsSuppressTransactionScope(logEvents, connectionString); } } finally { if (!KeepConnection) { InternalLogger.Trace("{0}: Close connection because of KeepConnection=false", this); CloseConnection(); } } } private void WriteLogEventsSuppressTransactionScope(IList<AsyncLogEventInfo> logEvents, string connectionString) { for (int i = 0; i < logEvents.Count; i++) { try { WriteLogEventSuppressTransactionScope(logEvents[i].LogEvent, connectionString); logEvents[i].Continuation(null); } catch (Exception exception) { if (LogManager.ThrowExceptions) throw; logEvents[i].Continuation(exception); } } } private void WriteLogEventsWithTransactionScope(IList<AsyncLogEventInfo> logEvents, string connectionString) { try { //Always suppress transaction so that the caller does not rollback logging if they are rolling back their transaction. using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Suppress)) { EnsureConnectionOpen(connectionString, logEvents.Count > 0 ? logEvents[0].LogEvent : null); var dbTransaction = _activeConnection.BeginTransaction(IsolationLevel.Value); try { for (int i = 0; i < logEvents.Count; ++i) { ExecuteDbCommandWithParameters(logEvents[i].LogEvent, _activeConnection, dbTransaction); } dbTransaction?.Commit(); for (int i = 0; i < logEvents.Count; i++) { logEvents[i].Continuation(null); } dbTransaction?.Dispose(); // Can throw error on dispose, so no using transactionScope.Complete(); //not really needed as there is no transaction at all. } catch { try { if (dbTransaction?.Connection != null) { dbTransaction?.Rollback(); } dbTransaction?.Dispose(); } catch (Exception exception) { InternalLogger.Error(exception, "{0}: Error during rollback of batch writing {1} logevents to database.", this, logEvents.Count); if (LogManager.ThrowExceptions) throw; } throw; } } } catch (Exception exception) { InternalLogger.Error(exception, "{0}: Error when batch writing {1} logevents to database.", this, logEvents.Count); if (LogManager.ThrowExceptions) throw; InternalLogger.Trace("{0}: Close connection because of error", this); CloseConnection(); for (int i = 0; i < logEvents.Count; i++) { logEvents[i].Continuation(exception); } } } private void WriteLogEventSuppressTransactionScope(LogEventInfo logEvent, string connectionString) { try { //Always suppress transaction so that the caller does not rollback logging if they are rolling back their transaction. using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Suppress)) { EnsureConnectionOpen(connectionString, logEvent); ExecuteDbCommandWithParameters(logEvent, _activeConnection, null); transactionScope.Complete(); //not really needed as there is no transaction at all. } } catch (Exception exception) { InternalLogger.Error(exception, "{0}: Error when writing to database.", this); if (LogManager.ThrowExceptions) throw; InternalLogger.Trace("{0}: Close connection because of error", this); CloseConnection(); throw; } } /// <summary> /// Write logEvent to database /// </summary> private void ExecuteDbCommandWithParameters(LogEventInfo logEvent, IDbConnection dbConnection, IDbTransaction dbTransaction) { using (IDbCommand command = CreateDbCommand(logEvent, dbConnection)) { if (dbTransaction != null) command.Transaction = dbTransaction; int result = command.ExecuteNonQuery(); InternalLogger.Trace("{0}: Finished execution, result = {1}", this, result); } } internal IDbCommand CreateDbCommand(LogEventInfo logEvent, IDbConnection dbConnection) { var commandText = RenderLogEvent(CommandText, logEvent); InternalLogger.Trace("{0}: Executing {1}: {2}", this, CommandType, commandText); return CreateDbCommandWithParameters(logEvent, dbConnection, CommandType, commandText, Parameters); } private IDbCommand CreateDbCommandWithParameters(LogEventInfo logEvent, IDbConnection dbConnection, CommandType commandType, string dbCommandText, IList<DatabaseParameterInfo> databaseParameterInfos) { var dbCommand = dbConnection.CreateCommand(); dbCommand.CommandType = commandType; if (CommandProperties?.Count > 0) { ApplyDatabaseObjectProperties(dbCommand, CommandProperties, logEvent); } dbCommand.CommandText = dbCommandText; for (int i = 0; i < databaseParameterInfos.Count; ++i) { var parameterInfo = databaseParameterInfos[i]; var dbParameter = CreateDatabaseParameter(dbCommand, parameterInfo); var dbParameterValue = GetDatabaseParameterValue(logEvent, parameterInfo); dbParameter.Value = dbParameterValue; dbCommand.Parameters.Add(dbParameter); InternalLogger.Trace(" DatabaseTarget: Parameter: '{0}' = '{1}' ({2})", dbParameter.ParameterName, dbParameter.Value, dbParameter.DbType); } return dbCommand; } /// <summary> /// Build the connectionstring from the properties. /// </summary> /// <remarks> /// Using <see cref="ConnectionString"/> at first, and falls back to the properties <see cref="DBHost"/>, /// <see cref="DBUserName"/>, <see cref="DBPassword"/> and <see cref="DBDatabase"/> /// </remarks> /// <param name="logEvent">Event to render the layout inside the properties.</param> /// <returns></returns> protected string BuildConnectionString(LogEventInfo logEvent) { if (ConnectionString != null) { return RenderLogEvent(ConnectionString, logEvent); } var sb = new StringBuilder(); sb.Append("Server="); sb.Append(RenderLogEvent(DBHost, logEvent)); sb.Append(";"); var dbUserName = RenderLogEvent(DBUserName, logEvent); if (string.IsNullOrEmpty(dbUserName)) { sb.Append("Trusted_Connection=SSPI;"); } else { sb.Append("User id="); sb.Append(dbUserName); sb.Append(";Password="); var password = _dbPasswordFixed ?? EscapeValueForConnectionString(_dbPassword.Render(logEvent)); sb.Append(password); sb.Append(";"); } var dbDatabase = RenderLogEvent(DBDatabase, logEvent); if (!string.IsNullOrEmpty(dbDatabase)) { sb.Append("Database="); sb.Append(dbDatabase); } return sb.ToString(); } /// <summary> /// Escape quotes and semicolons. /// See https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms722656(v=vs.85)#setting-values-that-use-reserved-characters /// </summary> private static string EscapeValueForConnectionString(string value) { if (string.IsNullOrEmpty(value)) return value; const char singleQuote = '\''; if (value.IndexOf(singleQuote) == 0 && (value.LastIndexOf(singleQuote) == value.Length - 1)) { // already escaped return value; } const char doubleQuote = '\"'; if (value.IndexOf(doubleQuote) == 0 && (value.LastIndexOf(doubleQuote) == value.Length - 1)) { // already escaped return value; } var containsSingle = value.IndexOf(singleQuote) >= 0; var containsDouble = value.IndexOf(doubleQuote) >= 0; if (containsSingle || containsDouble || value.IndexOf(';') >= 0) { if (!containsSingle) { return singleQuote + value + singleQuote; } if (!containsDouble) { return doubleQuote + value + doubleQuote; } // both single and double var escapedValue = value.Replace("\"", "\"\""); return doubleQuote + escapedValue + doubleQuote; } return value; } private void EnsureConnectionOpen(string connectionString, LogEventInfo logEventInfo) { if (_activeConnection != null && _activeConnectionString != connectionString) { InternalLogger.Trace("{0}: Close connection because of opening new.", this); CloseConnection(); } if (_activeConnection != null) { return; } InternalLogger.Trace("{0}: Open connection.", this); _activeConnection = OpenConnection(connectionString, logEventInfo); _activeConnectionString = connectionString; } private void CloseConnection() { try { var activeConnection = _activeConnection; if (activeConnection != null) { activeConnection.Close(); activeConnection.Dispose(); } } catch (Exception ex) { InternalLogger.Warn(ex, "{0}: Error while closing connection.", this); } finally { _activeConnectionString = null; _activeConnection = null; } } private void RunInstallCommands(InstallationContext installationContext, IEnumerable<DatabaseCommandInfo> commands) { // create log event that will be used to render all layouts LogEventInfo logEvent = installationContext.CreateLogEvent(); try { foreach (var commandInfo in commands) { var connectionString = GetConnectionStringFromCommand(commandInfo, logEvent); // Set ConnectionType if it has not been initialized already if (ConnectionType is null) { SetConnectionType(); } EnsureConnectionOpen(connectionString, logEvent); string commandText = RenderLogEvent(commandInfo.Text, logEvent); installationContext.Trace("DatabaseTarget(Name={0}) - Executing {1} '{2}'", Name, commandInfo.CommandType, commandText); using (IDbCommand command = CreateDbCommandWithParameters(logEvent, _activeConnection, commandInfo.CommandType, commandText, commandInfo.Parameters)) { try { command.ExecuteNonQuery(); } catch (Exception exception) { if (LogManager.ThrowExceptions) throw; if (commandInfo.IgnoreFailures || installationContext.IgnoreFailures) { installationContext.Warning(exception.Message); } else { installationContext.Error(exception.Message); throw; } } } } } finally { InternalLogger.Trace("{0}: Close connection after install.", this); CloseConnection(); } } private string GetConnectionStringFromCommand(DatabaseCommandInfo commandInfo, LogEventInfo logEvent) { string connectionString; if (commandInfo.ConnectionString != null) { // if there is connection string specified on the command info, use it connectionString = RenderLogEvent(commandInfo.ConnectionString, logEvent); } else if (InstallConnectionString != null) { // next, try InstallConnectionString connectionString = RenderLogEvent(InstallConnectionString, logEvent); } else { // if it's not defined, fall back to regular connection string connectionString = BuildConnectionString(logEvent); } return connectionString; } /// <summary> /// Create database parameter /// </summary> /// <param name="command">Current command.</param> /// <param name="parameterInfo">Parameter configuration info.</param> protected virtual IDbDataParameter CreateDatabaseParameter(IDbCommand command, DatabaseParameterInfo parameterInfo) { IDbDataParameter dbParameter = command.CreateParameter(); dbParameter.Direction = ParameterDirection.Input; if (parameterInfo.Name != null) { dbParameter.ParameterName = parameterInfo.Name; } if (parameterInfo.Size != 0) { dbParameter.Size = parameterInfo.Size; } if (parameterInfo.Precision != 0) { dbParameter.Precision = parameterInfo.Precision; } if (parameterInfo.Scale != 0) { dbParameter.Scale = parameterInfo.Scale; } try { if (!parameterInfo.SetDbType(dbParameter)) { InternalLogger.Warn(" DatabaseTarget: Parameter: '{0}' - Failed to assign DbType={1}", parameterInfo.Name, parameterInfo.DbType); } } catch (Exception ex) { InternalLogger.Error(ex, " DatabaseTarget: Parameter: '{0}' - Failed to assign DbType={1}", parameterInfo.Name, parameterInfo.DbType); if (LogManager.ThrowExceptions) throw; } return dbParameter; } /// <summary> /// Extract parameter value from the logevent /// </summary> /// <param name="logEvent">Current logevent.</param> /// <param name="parameterInfo">Parameter configuration info.</param> protected internal virtual object GetDatabaseParameterValue(LogEventInfo logEvent, DatabaseParameterInfo parameterInfo) { var value = parameterInfo.RenderValue(logEvent); if (parameterInfo.AllowDbNull && string.Empty.Equals(value)) return DBNull.Value; else return value; } #if NETSTANDARD1_3 || NETSTANDARD1_5 /// <summary> /// Fake transaction /// /// Transactions aren't in .NET Core: https://github.com/dotnet/corefx/issues/2949 /// </summary> private sealed class TransactionScope : IDisposable { private readonly TransactionScopeOption _suppress; public TransactionScope(TransactionScopeOption suppress) { _suppress = suppress; } public void Complete() { // Fake scope for compatibility, so nothing to do } public void Dispose() { // Fake scope for compatibility, so nothing to do } } /// <summary> /// Fake option /// </summary> private enum TransactionScopeOption { Required, RequiresNew, Suppress, } #endif } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Linq; using NLog.Internal; using Xunit; namespace NLog.UnitTests.Internal { public class StringSplitterTests { private const char SingleQuote = '\''; private const char Backslash = '\\'; [Theory] [InlineData("abc", ';', "abc")] [InlineData(" abc", ';', " abc")] [InlineData(null, ';', "")] [InlineData("", ';', "")] [InlineData(";", ';', ",")] [InlineData("a;", ';', "a,")] [InlineData("a; ", ';', "a, ")] [InlineData(" ", ';', " ")] [InlineData(@"a;b;;c", ';', @"a,b,,c")] [InlineData(@"a;b;;;;c", ';', @"a,b,,,,c")] [InlineData(@"a;;b", ';', @"a,,b")] [InlineData(@"a'b'c''d", SingleQuote, @"a,b,c,,d")] [InlineData(@"'a", SingleQuote, @",a")] void SplitStringWithSelfEscape(string input, char splitChar, string output) { var quoteChar = splitChar == SingleQuote ? '"' : SingleQuote; var strings = StringSplitter.SplitQuoted(input, splitChar, quoteChar, quoteChar).ToArray(); var result = string.Join(",", strings); Assert.Equal(output, result); } [Theory] [InlineData("abc", "abc")] [InlineData(" abc", " abc")] [InlineData(null, "")] [InlineData("", "")] [InlineData(" ", " ")] [InlineData(@"a;b;c", "a,b,c")] [InlineData(@"a;b;c;", "a,b,c,")] [InlineData(@"a;", "a,")] [InlineData(@";", ",")] [InlineData(@";a;b;c", ",a,b,c")] [InlineData(@"a;;b;c;", "a,,b,c,")] [InlineData(@"a\b;c", @"a\b,c")] [InlineData(@"a;b;c\", @"a,b,c\")] [InlineData(@"a;b;c\;", @"a,b,c\,")] [InlineData(@"a;b;c\;;", @"a,b,c\,,")] [InlineData(@"a\;b;c", @"a\,b,c")] [InlineData(@"a\;b\;c", @"a\,b\,c")] [InlineData(@"a\;b\;c;d", @"a\,b\,c,d")] [InlineData(@"a\;b;c\;d", @"a\,b,c\,d")] [InlineData(@"abc\;", @"abc\,")] void SplitStringWithEscape(string input, string output) { // Not possible to escape the splitter without using quotes SplitStringWithEscape2(input, ';', Backslash, output); } [Theory] [InlineData(@"abc", ';', ',', "abc")] void SplitStringWithEscape2(string input, char splitChar, char escapeChar, string output) { var strings = StringSplitter.SplitQuoted(input, splitChar, SingleQuote, escapeChar).ToArray(); var result = string.Join(",", strings); Assert.Equal(output, result); } /// <summary> /// Tests with ; as separator, quoted and escaped with ' /// </summary> [Theory] [InlineData(@";", @",")] [InlineData(@";;", @",,")] [InlineData(@"a;", @"a,")] [InlineData(@"a;''b;c", "a,'b,c")] [InlineData(@"a;''b;c'", "a,'b,c'")] [InlineData(@"abc", "abc")] [InlineData(@"abc'", "abc'")] [InlineData(@"''abc'", "'abc'")] [InlineData(@"'abc'", "abc")] [InlineData(@"'ab;c'", "ab;c")] [InlineData(@"'ab\c'", @"ab\c")] [InlineData(@"'", @"'")] [InlineData(@"'a", @"'a")] [InlineData(@"a'", @"a'")] [InlineData(@"\", @"\")] [InlineData(@"a\", @"a\")] [InlineData(@"\b", @"\b")] void SplitStringWithQuotes_selfQuoted(string input, string output) { SplitStringWithQuotes(input, ';', SingleQuote, SingleQuote, output); } /// <summary> /// Tests with ; as separator, quoted with single quote and escaped with backslash /// </summary> [Theory] [InlineData(null, "")] [InlineData(@"\", @"\")] [InlineData(@"'", @"'")] [InlineData(@"' ", @"' ")] [InlineData(@"a'", "a'")] [InlineData(@" ' ", @" ' ")] [InlineData(@" ; ", @" , ")] [InlineData(@";", @",")] [InlineData(@";;", @",,")] [InlineData(@"abc", "abc")] [InlineData(@"abc;", "abc,")] [InlineData(@"abc'", "abc'")] [InlineData(@"abc\", @"abc\")] [InlineData(@"abc\\", @"abc\\")] [InlineData(@"abc\b", @"abc\b")] [InlineData(@"a;b;c", "a,b,c")] [InlineData(@"a;'b;c'", "a,b;c")] [InlineData(@"a;'b;c", "a,'b;c")] [InlineData(@"a;b'c;d", "a,b'c,d")] [InlineData(@"a;\'b;c", "a,'b,c")] [InlineData(@"\b", @"\b")] [InlineData(@"'\'", @"''")] //todo check case (How to handle escape before last quote?) [InlineData(@"'\\'", @"'\'")] //todo check case (How to handle escape before last quote?) [InlineData(@"'\\\'", @"'\\'")] //todo check case (How to handle escape before last quote?) [InlineData(@"'\''", @"'")] [InlineData(@"'\\''", @"\'")] void SplitStringWithQuotes_escaped(string input, string output) { SplitStringWithQuotes(input, ';', SingleQuote, Backslash, output); } private static void SplitStringWithQuotes(string input, char splitChar, char quoteChar, char escapeChar, string output) { var strings = StringSplitter.SplitQuoted(input, splitChar, quoteChar, escapeChar).ToArray(); var result = string.Join(",", strings); Assert.Equal(output, result); } [Theory] [InlineData(';', ';', Backslash)] [InlineData(';', Backslash, ';')] void SplitStringNotSupported(char splitChar, char quoteChar, char escapeChar) { Assert.Throws<NotSupportedException>(() => StringSplitter.SplitQuoted("dont care", splitChar, quoteChar, escapeChar)); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Text; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.LayoutRenderers; /// <summary> /// Represents a string with embedded placeholders that can render contextual information. /// </summary> /// <remarks> /// <para> /// This layout is not meant to be used explicitly. Instead you can just use a string containing layout /// renderers everywhere the layout is required. /// </para> /// <a href="https://github.com/NLog/NLog/wiki/SimpleLayout">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/NLog/NLog/wiki/SimpleLayout">Documentation on NLog Wiki</seealso> [Layout("SimpleLayout")] [ThreadAgnostic] [AppDomainFixedOutput] public class SimpleLayout : Layout, IUsesStackTrace { private string _fixedText; private string _layoutText; private IRawValue _rawValueRenderer; private IStringValueRenderer _stringValueRenderer; private readonly ConfigurationItemFactory _configurationItemFactory; /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout" /> class. /// </summary> public SimpleLayout() : this(string.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout" /> class. /// </summary> /// <param name="txt">The layout string to parse.</param> public SimpleLayout([Localizable(false)] string txt) : this(txt, ConfigurationItemFactory.Default) { } /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout"/> class. /// </summary> /// <param name="txt">The layout string to parse.</param> /// <param name="configurationItemFactory">The NLog factories to use when creating references to layout renderers.</param> public SimpleLayout([Localizable(false)] string txt, ConfigurationItemFactory configurationItemFactory) :this(txt, configurationItemFactory, null) { } /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout"/> class. /// </summary> /// <param name="txt">The layout string to parse.</param> /// <param name="configurationItemFactory">The NLog factories to use when creating references to layout renderers.</param> /// <param name="throwConfigExceptions">Whether <see cref="NLogConfigurationException"/> should be thrown on parse errors.</param> internal SimpleLayout([Localizable(false)] string txt, ConfigurationItemFactory configurationItemFactory, bool? throwConfigExceptions) { _configurationItemFactory = configurationItemFactory; SetLayoutText(txt, throwConfigExceptions); } internal SimpleLayout(LayoutRenderer[] renderers, [Localizable(false)] string text, ConfigurationItemFactory configurationItemFactory) { _configurationItemFactory = configurationItemFactory; OriginalText = text; SetLayoutRenderers(renderers, text); } /// <summary> /// Original text before compile to Layout renderes /// </summary> public string OriginalText { get; private set; } /// <summary> /// Gets or sets the layout text. /// </summary> /// <docgen category='Layout Options' order='10' /> public string Text { get => _layoutText; set => SetLayoutText(value); } private void SetLayoutText(string value, bool? throwConfigExceptions = null) { OriginalText = value; var renderers = LayoutParser.CompileLayout(value, _configurationItemFactory, throwConfigExceptions, out var txt); SetLayoutRenderers(renderers, txt); } /// <summary> /// Is the message fixed? (no Layout renderers used) /// </summary> public bool IsFixedText => _fixedText != null; /// <summary> /// Get the fixed text. Only set when <see cref="IsFixedText"/> is <c>true</c> /// </summary> public string FixedText => _fixedText; /// <summary> /// Is the message a simple formatted string? (Can skip StringBuilder) /// </summary> internal bool IsSimpleStringText => _stringValueRenderer != null; /// <summary> /// Gets a collection of <see cref="LayoutRenderer"/> objects that make up this layout. /// </summary> [NLogConfigurationIgnoreProperty] public ReadOnlyCollection<LayoutRenderer> Renderers => _renderers ?? (_renderers = new ReadOnlyCollection<LayoutRenderer>(_layoutRenderers)); private ReadOnlyCollection<LayoutRenderer> _renderers; private LayoutRenderer[] _layoutRenderers; /// <summary> /// Gets a collection of <see cref="LayoutRenderer"/> objects that make up this layout. /// </summary> public IEnumerable<LayoutRenderer> LayoutRenderers => _layoutRenderers; /// <summary> /// Gets the level of stack trace information required for rendering. /// </summary> public new StackTraceUsage StackTraceUsage => base.StackTraceUsage; /// <summary> /// Converts a text to a simple layout. /// </summary> /// <param name="text">Text to be converted.</param> /// <returns>A <see cref="SimpleLayout"/> object.</returns> public static implicit operator SimpleLayout([Localizable(false)] string text) { if (text is null) return null; return new SimpleLayout(text); } /// <summary> /// Escapes the passed text so that it can /// be used literally in all places where /// layout is normally expected without being /// treated as layout. /// </summary> /// <param name="text">The text to be escaped.</param> /// <returns>The escaped text.</returns> /// <remarks> /// Escaping is done by replacing all occurrences of /// '${' with '${literal:text=${}' /// </remarks> public static string Escape([Localizable(false)] string text) { return text.Replace("${", @"${literal:text=\$\{}"); } /// <summary> /// Evaluates the specified text by expanding all layout renderers. /// </summary> /// <param name="text">The text to be evaluated.</param> /// <param name="logEvent">Log event to be used for evaluation.</param> /// <returns>The input text with all occurrences of ${} replaced with /// values provided by the appropriate layout renderers.</returns> public static string Evaluate([Localizable(false)] string text, LogEventInfo logEvent) { var layout = new SimpleLayout(text); return layout.Render(logEvent); } /// <summary> /// Evaluates the specified text by expanding all layout renderers /// in new <see cref="LogEventInfo" /> context. /// </summary> /// <param name="text">The text to be evaluated.</param> /// <returns>The input text with all occurrences of ${} replaced with /// values provided by the appropriate layout renderers.</returns> public static string Evaluate([Localizable(false)] string text) { return Evaluate(text, LogEventInfo.CreateNullEvent()); } /// <inheritdoc/> public override string ToString() { if (string.IsNullOrEmpty(Text) && !IsFixedText && _layoutRenderers.Length > 0) { return ToStringWithNestedItems(_layoutRenderers, r => r.ToString()); } return Text ?? _fixedText ?? string.Empty; } internal void SetLayoutRenderers(LayoutRenderer[] layoutRenderers, string text) { _layoutRenderers = layoutRenderers ?? ArrayHelper.Empty<LayoutRenderer>(); _renderers = null; _fixedText = null; _rawValueRenderer = null; _stringValueRenderer = null; if (_layoutRenderers.Length == 0) { _fixedText = string.Empty; } else if (_layoutRenderers.Length == 1) { if (_layoutRenderers[0] is LiteralLayoutRenderer renderer) { _fixedText = renderer.Text; } else if (_layoutRenderers[0] is IStringValueRenderer stringValueRenderer) { _stringValueRenderer = stringValueRenderer; } if (_layoutRenderers[0] is IRawValue rawValueRenderer) { _rawValueRenderer = rawValueRenderer; } } _layoutText = text; if (LoggingConfiguration != null) { PerformObjectScanning(); } } /// <inheritdoc/> protected override void InitializeLayout() { for (int i = 0; i < _layoutRenderers.Length; i++) { LayoutRenderer renderer = _layoutRenderers[i]; try { renderer.Initialize(LoggingConfiguration); } catch (Exception exception) { //also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error //check for performance if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(exception, "Exception in '{0}.InitializeLayout()'", renderer.GetType().FullName); } if (exception.MustBeRethrown()) { throw; } } } base.InitializeLayout(); } /// <inheritdoc/> public override void Precalculate(LogEventInfo logEvent) { if (!IsLogEventMutableSafe(logEvent)) { Render(logEvent); } } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { if (!IsLogEventMutableSafe(logEvent)) { PrecalculateBuilderInternal(logEvent, target, null); } } private bool IsLogEventMutableSafe(LogEventInfo logEvent) { if (_rawValueRenderer != null) { try { if (!IsInitialized) { Initialize(LoggingConfiguration); } if (ThreadAgnostic) { if (MutableUnsafe) { // If raw value doesn't have the ability to mutate, then we can skip precalculate var success = _rawValueRenderer.TryGetRawValue(logEvent, out var value); if (success && IsObjectValueMutableSafe(value)) return true; } else { return true; } } return false; } catch (Exception exception) { //also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error //check for performance if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(exception, "Exception in precalculate using '{0}.TryGetRawValue()'", _rawValueRenderer?.GetType()); } if (exception.MustBeRethrown()) { throw; } } } return ThreadAgnostic && !MutableUnsafe; } private static bool IsObjectValueMutableSafe(object value) { return value != null && (Convert.GetTypeCode(value) != TypeCode.Object || value.GetType().IsValueType()); } /// <inheritdoc/> internal override bool TryGetRawValue(LogEventInfo logEvent, out object rawValue) { if (_rawValueRenderer != null) { try { if (!IsInitialized) { Initialize(LoggingConfiguration); } if ((!ThreadAgnostic || MutableUnsafe) && logEvent.TryGetCachedLayoutValue(this, out _)) { rawValue = null; return false; // Raw-Value has been precalculated, so not available } var success = _rawValueRenderer.TryGetRawValue(logEvent, out rawValue); return success; } catch (Exception exception) { //also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error //check for performance if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(exception, "Exception in TryGetRawValue using '{0}.TryGetRawValue()'", _rawValueRenderer?.GetType()); } if (exception.MustBeRethrown()) { throw; } } } rawValue = null; return false; } /// <inheritdoc/> protected override string GetFormattedMessage(LogEventInfo logEvent) { if (IsFixedText) { return _fixedText; } if (_stringValueRenderer != null) { try { string stringValue = _stringValueRenderer.GetFormattedString(logEvent); if (stringValue != null) return stringValue; _stringValueRenderer = null; // Optimization is not possible } catch (Exception exception) { //also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error //check for performance if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(exception, "Exception in '{0}.GetFormattedString()'", _stringValueRenderer.GetType().FullName); } if (exception.MustBeRethrown()) { throw; } } } return RenderAllocateBuilder(logEvent); } private void RenderAllRenderers(LogEventInfo logEvent, StringBuilder target) { //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < _layoutRenderers.Length; i++) { LayoutRenderer renderer = _layoutRenderers[i]; try { renderer.RenderAppendBuilder(logEvent, target); } catch (Exception exception) { //also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error //check for performance if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(exception, "Exception in '{0}.Append()'", renderer.GetType().FullName); } if (exception.MustBeRethrown()) { throw; } } } } /// <inheritdoc/> protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { if (IsFixedText) { target.Append(_fixedText); return; } RenderAllRenderers(logEvent, target); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 #define SupportsMutex #endif namespace NLog.Internal.FileAppenders { using System; using System.IO; using System.Security; using System.Threading; using System.Text; using JetBrains.Annotations; #if SupportsMutex #if !NETSTANDARD using System.Security.AccessControl; using System.Security.Principal; #endif using System.Security.Cryptography; #endif using Common; /// <summary> /// Base class for optimized file appenders which require the usage of a mutex. /// /// It is possible to use this class as replacement of BaseFileAppender and the mutex functionality /// is not enforced to the implementing subclasses. /// </summary> [SecuritySafeCritical] internal abstract class BaseMutexFileAppender : BaseFileAppender { /// <summary> /// Initializes a new instance of the <see cref="BaseMutexFileAppender" /> class. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="createParameters">The create parameters.</param> protected BaseMutexFileAppender(string fileName, ICreateFileParameters createParameters) : base(fileName, createParameters) { if (createParameters.IsArchivingEnabled && createParameters.ConcurrentWrites) { if (MutexDetector.SupportsSharableMutex) { #if SupportsMutex ArchiveMutex = CreateArchiveMutex(); #endif } else { InternalLogger.Debug("{0}: Mutex for file archive not supported", CreateFileParameters); } } } #if SupportsMutex /// <summary> /// Gets the mutually-exclusive lock for archiving files. /// </summary> /// <value>The mutex for archiving.</value> [CanBeNull] public Mutex ArchiveMutex { get; private set; } private Mutex CreateArchiveMutex() { try { return CreateSharableMutex("FileArchiveLock"); } catch (Exception ex) { if (ex is SecurityException || ex is UnauthorizedAccessException || ex is NotSupportedException || ex is NotImplementedException || ex is PlatformNotSupportedException) { InternalLogger.Warn(ex, "{0}: Failed to create global archive mutex: {1}", CreateFileParameters, FileName); return new Mutex(); } InternalLogger.Error(ex, "{0}: Failed to create global archive mutex: {1}", CreateFileParameters, FileName); if (ex.MustBeRethrown()) throw; return new Mutex(); } } /// <inheritdoc/> protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { ArchiveMutex?.Close(); // Only closed on dispose, Mutex must survive, when closing FileAppender before archive } } /// <summary> /// Creates a mutex that is sharable by more than one process. /// </summary> /// <param name="mutexNamePrefix">The prefix to use for the name of the mutex.</param> /// <returns>A <see cref="Mutex"/> object which is sharable by multiple processes.</returns> protected Mutex CreateSharableMutex(string mutexNamePrefix) { if (!MutexDetector.SupportsSharableMutex) throw new NotSupportedException("Creating Mutex not supported"); var name = GetMutexName(mutexNamePrefix); return ForceCreateSharableMutex(name); } internal static Mutex ForceCreateSharableMutex(string name) { #if !NETSTANDARD // Creates a mutex sharable by more than one process var mutexSecurity = new MutexSecurity(); var everyoneSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); mutexSecurity.AddAccessRule(new MutexAccessRule(everyoneSid, MutexRights.FullControl, AccessControlType.Allow)); // The constructor will either create new mutex or open // an existing one, in a thread-safe manner return new Mutex(false, name, out _, mutexSecurity); #else //Mutex with 4 args has keyword "unsafe" return new Mutex(false, name); #endif } private string GetMutexName(string mutexNamePrefix) { const string mutexNameFormatString = @"Global\NLog-File{0}-{1}"; const int maxMutexNameLength = 260; string canonicalName = Path.GetFullPath(FileName).ToLowerInvariant(); // Mutex names must not contain a slash, it's the namespace separator, // but all other are OK canonicalName = canonicalName.Replace('\\', '_'); canonicalName = canonicalName.Replace('/', '_'); string mutexName = string.Format(mutexNameFormatString, mutexNamePrefix, canonicalName); // A mutex name must not exceed MAX_PATH (260) characters if (mutexName.Length <= maxMutexNameLength) { return mutexName; } // The unusual case of the path being too long; let's hash the canonical name, // so it can be safely shortened and still remain unique string hash; using (MD5 md5 = MD5.Create()) { byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(canonicalName)); hash = Convert.ToBase64String(bytes); } // The hash makes the name unique, but also add the end of the path, // so the end of the name tells us which file it is (for debugging) mutexName = string.Format(mutexNameFormatString, mutexNamePrefix, hash); int cutOffIndex = canonicalName.Length - (maxMutexNameLength - mutexName.Length); return mutexName + canonicalName.Substring(cutOffIndex); } #endif } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Config; namespace NLog.UnitTests.LayoutRenderers.Wrappers { using NLog; using NLog.LayoutRenderers.Wrappers; using NLog.Layouts; using NLog.Targets; using System; using System.Collections.Generic; using Xunit; public class ReplaceTests : NLogTestBase { [Fact] public void ReplaceTestWithoutRegEx() { // Arrange SimpleLayout layout = @"${replace:inner=${message}:searchFor=foo:replaceWith=BAR}"; // Act var result = layout.Render(new LogEventInfo(LogLevel.Info, "Test", " foo bar bar foo bar FOO")); // Assert Assert.Equal(" BAR bar bar BAR bar FOO", result); } [Fact] public void ReplaceTestWithSimpleRegEx() { // Arrange SimpleLayout layout = @"${replace:inner=${message}:searchFor=\\r\\n|\\s:replaceWith= :regex=true}"; // Act var result = layout.Render(new LogEventInfo(LogLevel.Info, "Test", "\r\nfoo\rbar\nbar\tbar bar \n bar")); // Assert Assert.Equal(" foo bar bar bar bar bar", result); } [Fact] public void ReplaceTestWithSimpleRegExFromConfig() { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <target name='d1' type='Debug' layout='${replace:inner=${message}:searchFor=\\r\\n|\\s:replaceWith= :regex=true}' /> </targets> <rules> <logger name=""*"" minlevel=""Trace"" writeTo=""d1"" /> </rules> </nlog>"); var d1 = configuration.FindTargetByName("d1") as DebugTarget; Assert.NotNull(d1); var layout = d1.Layout as SimpleLayout; Assert.NotNull(layout); var result = layout.Render(new LogEventInfo(LogLevel.Info, "Test", "\r\nfoo\rbar\nbar\tbar bar \n bar")); Assert.Equal(" foo bar bar bar bar bar", result); } [Fact] public void ReplaceTestWithSimpleRegExFromConfig2() { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <variable name=""whitespace"" value=""\\r\\n|\\s"" /> <variable name=""oneLineMessage"" value=""${replace:inner=${message}:searchFor=${whitespace}:replaceWith= :regex=true}"" /> <targets> <target name=""d1"" type=""Debug"" layout=""${oneLineMessage}"" /> </targets> <rules> <logger name=""*"" minlevel=""Trace"" writeTo=""d1"" /> </rules> </nlog>"); var d1 = configuration.FindTargetByName("d1") as DebugTarget; Assert.NotNull(d1); var layout = d1.Layout as SimpleLayout; Assert.NotNull(layout); var result = layout.Render(new LogEventInfo(LogLevel.Info, "Test", "\r\nfoo\rbar\nbar\tbar bar \n bar")); Assert.Equal(" foo bar bar bar bar bar", result); } [Fact] public void ReplaceTestWithComplexRegEx() { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <variable name=""searchExp"" value=""(?&lt;!\\d[ -]*)(?\:(?&lt;digits&gt;\\d)[ -]*)\{8,16\}(?=(\\d[ -]*)\{3\}(\\d)(?![ -]\\d))"" /> <variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=X:replaceGroupName=digits:regex=true:ignorecase=true}"" /> <targets> <target name=""d1"" type=""Debug"" layout=""${message1}"" /> </targets> <rules> <logger name=""*"" minlevel=""Trace"" writeTo=""d1"" /> </rules> </nlog>"); var d1 = configuration.FindTargetByName("d1") as DebugTarget; Assert.NotNull(d1); var layout = d1.Layout as SimpleLayout; Assert.NotNull(layout); var testCases = new List<Tuple<string, string>> { Tuple.Create("1234", "1234"), Tuple.Create("1234-5678-1234-5678", "XXXX-XXXX-XXXX-5678"), }; foreach (var testCase in testCases) { var result = layout.Render(new LogEventInfo(LogLevel.Info, "Test", testCase.Item1)); Assert.Equal(testCase.Item2, result); } } [Fact] public void ReplaceNamedGroupTests() { var pattern = @"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]*\d))"; var groupName = @"digits"; var regex = new System.Text.RegularExpressions.Regex( pattern, System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase); var testCases = new List<Tuple<string, string, string>> { Tuple.Create("1234", "1234", "X"), Tuple.Create("1234-5678-1234-5678", "XXXX-XXXX-XXXX-5678", "X"), Tuple.Create("1234 5678 1234 5678", "XXXX XXXX XXXX 5678", "X"), Tuple.Create("1234567812345678", "XXXXXXXXXXXX5678", "X"), Tuple.Create("ABCD-1234-5678-1234-5678", "ABCD-XXXX-XXXX-XXXX-5678", "X"), Tuple.Create("1234-5678-1234-5678-ABCD", "XXXX-XXXX-XXXX-5678-ABCD", "X"), Tuple.Create("ABCD-1234-5678-1234-5678-ABCD", "ABCD-XXXX-XXXX-XXXX-5678-ABCD", "X"), Tuple.Create("ABCD-1234-5678-1234-5678-ABCD", "ABCD-XXXXXXXX-XXXXXXXX-XXXXXXXX-5678-ABCD", "XX"), }; foreach (var testCase in testCases) { var input = testCase.Item1; var replacement = testCase.Item3; var result = regex.Replace( input, m => ReplaceLayoutRendererWrapper.ReplaceNamedGroup(groupName, replacement, m)); Assert.Equal(testCase.Item2, result); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LayoutRenderers { using System; using System.IO; using System.Threading.Tasks; using NLog.Internal; using Xunit; public class CallSiteFileNameLayoutTests : NLogTestBase { #if !MONO [Fact] #else [Fact(Skip = "MONO is not good with callsite line numbers")] #endif public void ShowFileNameOnlyTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite-filename:includeSourcePath=False}|${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); var lastMessage = GetDebugLastMessage("debug", logFactory); var lastMessageArray = lastMessage.Split('|'); Assert.Equal("CallSiteFileNameLayoutTests.cs", lastMessageArray[0]); Assert.Equal("msg", lastMessageArray[1]); } #if !MONO [Fact] #else [Fact(Skip = "MONO is not good with callsite line numbers")] #endif public void CallSiteFileNameNoCaptureStackTraceTest() { // Arrange var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite-filename:captureStackTrace=False}|${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; // Act logFactory.GetLogger("A").Debug("msg"); // Assert logFactory.AssertDebugLastMessage("|msg"); } #if !MONO [Fact] #else [Fact(Skip = "MONO is not good with callsite line numbers")] #endif public void CallSiteFileNameNoCaptureStackTraceWithStackTraceTest() { // Arrange var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite-filename:captureStackTrace=False}|${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; // Act var logEvent = new LogEventInfo(LogLevel.Info, null, "msg"); logEvent.SetStackTrace(new System.Diagnostics.StackTrace(true), 0); logFactory.GetLogger("A").Log(logEvent); // Assert var lastMessage = GetDebugLastMessage("debug", logFactory); var lastMessageArray = lastMessage.Split('|'); Assert.Contains("CallSiteFileNameLayoutTests.cs", lastMessageArray[0]); Assert.Equal("msg", lastMessageArray[1]); } #if !MONO [Fact] #else [Fact(Skip = "MONO is not good with callsite line numbers")] #endif public void ShowFullPathTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite-filename:includeSourcePath=True}|${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); var lastMessage = GetDebugLastMessage("debug", logFactory); var lastMessageArray = lastMessage.Split('|'); Assert.Contains("CallSiteFileNameLayoutTests.cs", lastMessageArray[0]); Assert.False(lastMessageArray[0].StartsWith("CallSiteFileNameLayoutTests.cs")); Assert.True(Path.IsPathRooted(lastMessageArray[0])); Assert.Equal("msg", lastMessageArray[1]); } #if !MONO [Fact] #else [Fact(Skip = "MONO is not good with callsite line numbers")] #endif public void ShowFileNameOnlyAsyncTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite-filename:includeSourcePath=False}|${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; AsyncMethod(logFactory).Wait(); var lastMessage = GetDebugLastMessage("debug", logFactory); var lastMessageArray = lastMessage.Split('|'); Assert.Equal("CallSiteFileNameLayoutTests.cs", lastMessageArray[0]); Assert.Equal("msg", lastMessageArray[1]); } #if !MONO [Fact] #else [Fact(Skip = "MONO is not good with callsite line numbers")] #endif public void ShowFullPathAsyncTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite-filename:includeSourcePath=True}|${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); AsyncMethod(logFactory).Wait(); var lastMessage = GetDebugLastMessage("debug", logFactory); var lastMessageArray = lastMessage.Split('|'); Assert.Contains("CallSiteFileNameLayoutTests.cs", lastMessageArray[0]); Assert.False(lastMessageArray[0].StartsWith("CallSiteFileNameLayoutTests.cs")); Assert.True(Path.IsPathRooted(lastMessageArray[0])); Assert.Equal("msg", lastMessageArray[1]); } private async Task AsyncMethod(LogFactory logFactory) { var logger = logFactory.GetCurrentClassLogger(); logger.Warn("msg"); var reader = new StreamReader(new MemoryStream(ArrayHelper.Empty<byte>())); await reader.ReadLineAsync(); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using Conditions; using Config; /// <summary> /// Filtering rule for <see cref="PostFilteringTargetWrapper"/>. /// </summary> [NLogConfigurationItem] public class FilteringRule { /// <summary> /// Initializes a new instance of the FilteringRule class. /// </summary> public FilteringRule() : this(null, null) { } /// <summary> /// Initializes a new instance of the FilteringRule class. /// </summary> /// <param name="whenExistsExpression">Condition to be tested against all events.</param> /// <param name="filterToApply">Filter to apply to all log events when the first condition matches any of them.</param> public FilteringRule(ConditionExpression whenExistsExpression, ConditionExpression filterToApply) { Exists = whenExistsExpression; Filter = filterToApply; } /// <summary> /// Gets or sets the condition to be tested. /// </summary> /// <docgen category='Filtering Options' order='10' /> [RequiredParameter] public ConditionExpression Exists { get; set; } /// <summary> /// Gets or sets the resulting filter to be applied when the condition matches. /// </summary> /// <docgen category='Filtering Options' order='10' /> [RequiredParameter] public ConditionExpression Filter { get; set; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if NETSTANDARD1_3 || NETSTANDARD1_5 using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace NLog.Internal.Fakeables { [Obsolete("For unit testing only. Marked obsolete on NLog 5.0")] internal class FakeAppDomain : IAppDomain { #if NETSTANDARD1_5 private readonly System.Runtime.Loader.AssemblyLoadContext _defaultContext; #endif /// <summary>Initializes a new instance of the <see cref="FakeAppDomain" /> class.</summary> public FakeAppDomain() { BaseDirectory = AppContext.BaseDirectory; #if NETSTANDARD1_5 _defaultContext = System.Runtime.Loader.AssemblyLoadContext.Default; try { FriendlyName = GetFriendlyNameFromEntryAssembly() ?? GetFriendlyNameFromProcessName() ?? "UnknownAppDomain"; } catch { FriendlyName = "UnknownAppDomain"; } #endif } #region Implementation of IAppDomain #if NETSTANDARD1_5 private static string GetFriendlyNameFromEntryAssembly() { try { string assemblyName = Assembly.GetEntryAssembly()?.GetName()?.Name; return string.IsNullOrEmpty(assemblyName) ? null : assemblyName; } catch { return null; } } private static string GetFriendlyNameFromProcessName() { try { string processName = System.Diagnostics.Process.GetCurrentProcess().ProcessName; return string.IsNullOrEmpty(processName) ? null : processName; } catch { return null; } } #endif /// <summary> /// Gets or sets the base directory that the assembly resolver uses to probe for assemblies. /// </summary> public string BaseDirectory { get; private set; } /// <summary> /// Gets or sets the name of the configuration file for an application domain. /// </summary> public string ConfigurationFile { get; set; } /// <summary> /// Gets or sets the list of directories under the application base directory that are probed for private assemblies. /// </summary> public IEnumerable<string> PrivateBinPath { get; set; } /// <summary> /// Gets or set the friendly name. /// </summary> public string FriendlyName { get; set; } /// <summary> /// Gets an integer that uniquely identifies the application domain within the process. /// </summary> public int Id { get; set; } /// <summary> /// Gets the assemblies that have been loaded into the execution context of this application domain. /// </summary> /// <returns>A list of assemblies in this application domain.</returns> public IEnumerable<Assembly> GetAssemblies() { return Internal.ArrayHelper.Empty<Assembly>(); } /// <summary> /// Process exit event. /// </summary> public event EventHandler<EventArgs> ProcessExit { add { #if NETSTANDARD1_5 if (_contextUnloadingEvent == null && _defaultContext != null) _defaultContext.Unloading += OnContextUnloading; _contextUnloadingEvent += value; #endif } remove { #if NETSTANDARD1_5 _contextUnloadingEvent -= value; if (_contextUnloadingEvent == null && _defaultContext != null) _defaultContext.Unloading -= OnContextUnloading; #endif } } /// <summary> /// Domain unloaded event. /// </summary> public event EventHandler<EventArgs> DomainUnload { add { #if NETSTANDARD1_5 if (_contextUnloadingEvent == null && _defaultContext != null) _defaultContext.Unloading += OnContextUnloading; _contextUnloadingEvent += value; #endif } remove { #if NETSTANDARD1_5 _contextUnloadingEvent -= value; if (_contextUnloadingEvent == null && _defaultContext != null) _defaultContext.Unloading -= OnContextUnloading; #endif } } #if NETSTANDARD1_5 private event EventHandler<EventArgs> _contextUnloadingEvent; private void OnContextUnloading(System.Runtime.Loader.AssemblyLoadContext context) { var handler = _contextUnloadingEvent; if (handler != null) handler.Invoke(context, EventArgs.Empty); } #endif #endregion } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Internal; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace NLog.MessageTemplates { /// <summary> /// Parse templates. /// </summary> internal struct TemplateEnumerator : IEnumerator<LiteralHole> { private static readonly char[] HoleDelimiters = { '}', ':', ',' }; private static readonly char[] TextDelimiters = { '{', '}' }; private string _template; private int _length; private int _position; private int _literalLength; private LiteralHole _current; private const short Zero = 0; /// <summary> /// Parse a template. /// </summary> /// <param name="template">Template to be parsed.</param> /// <exception cref="ArgumentNullException">When <paramref name="template"/> is null.</exception> /// <returns>Template, never null</returns> public TemplateEnumerator(string template) { _template = Guard.ThrowIfNull(template); _length = _template.Length; _position = 0; _literalLength = 0; _current = default(LiteralHole); } /// <summary> /// Gets the current literal/hole in the template /// </summary> public LiteralHole Current => _current; object System.Collections.IEnumerator.Current => _current; /// <summary> /// Clears the enumerator /// </summary> public void Dispose() { _template = string.Empty; _length = 0; Reset(); } /// <summary> /// Restarts the enumerator of the template /// </summary> public void Reset() { _position = 0; _literalLength = 0; _current = default(LiteralHole); } /// <summary> /// Moves to the next literal/hole in the template /// </summary> /// <returns>Found new element [true/false]</returns> public bool MoveNext() { try { while (_position < _length) { char c = Peek(); if (c == '{') { ParseOpenBracketPart(); return true; } else if (c == '}') { ParseCloseBracketPart(); return true; } else ParseTextPart(); } if (_literalLength != 0) { AddLiteral(); return true; } return false; } catch (IndexOutOfRangeException) { throw new TemplateParserException("Unexpected end of template.", _position, _template); } } private void AddLiteral() { _current = new LiteralHole(new Literal(_literalLength, Zero), default(Hole)); _literalLength = 0; } private void ParseTextPart() { _literalLength = SkipUntil(TextDelimiters, required: false); } private void ParseOpenBracketPart() { Skip('{'); char c = Peek(); switch (c) { case '{': Skip('{'); _literalLength++; AddLiteral(); return; case '@': Skip('@'); ParseHole(CaptureType.Serialize); return; case '$': Skip('$'); ParseHole(CaptureType.Stringify); return; default: ParseHole(CaptureType.Normal); return; } } private void ParseCloseBracketPart() { Skip('}'); if (Read() != '}') throw new TemplateParserException("Unexpected '}}' ", _position - 2, _template); _literalLength++; AddLiteral(); } private void ParseHole(CaptureType type) { int start = _position; string name = ParseName(out var parameterIndex); int alignment = 0; string format = null; if (Peek() != '}') { alignment = Peek() == ',' ? ParseAlignment() : 0; format = Peek() == ':' ? ParseFormat() : null; Skip('}'); } else { _position++; } int literalSkip = _position - start + (type == CaptureType.Normal ? 1 : 2); // Account for skipped '{', '{$' or '{@' _current = new LiteralHole(new Literal(_literalLength, literalSkip), new Hole( name, format, type, (short)parameterIndex, (short)alignment )); _literalLength = 0; } private string ParseName(out int parameterIndex) { parameterIndex = -1; char c = Peek(); // If the name matches /^\d+ *$/ we consider it positional if (c >= '0' && c <= '9') { int start = _position; int parsedIndex = ReadInt(); c = Peek(); if (c == '}' || c == ':' || c == ',') { // Non-allocating positional hole-name-parsing parameterIndex = parsedIndex; return ParameterIndexToString(parameterIndex); } if (c == ' ') { SkipSpaces(); c = Peek(); if (c == '}' || c == ':' || c == ',') parameterIndex = parsedIndex; } _position = start; } return ReadUntil(HoleDelimiters); } private static string ParameterIndexToString(int parameterIndex) { switch (parameterIndex) { case 0: return "0"; case 1: return "1"; case 2: return "2"; case 3: return "3"; case 4: return "4"; case 5: return "5"; case 6: return "6"; case 7: return "7"; case 8: return "8"; case 9: return "9"; } return parameterIndex.ToString(System.Globalization.CultureInfo.InvariantCulture); } /// <summary> /// Parse format after hole name/index. Handle the escaped { and } in the format. Don't read the last } /// </summary> /// <returns></returns> private string ParseFormat() { Skip(':'); string format = ReadUntil(TextDelimiters); while (true) { var c = Read(); switch (c) { case '}': { if (_position < _length && Peek() == '}') { //this is an escaped } and need to be added to the format. Skip('}'); format += "}"; } else { //done. unread the '}' . _position--; //done return format; } break; } case '{': { //we need a second {, otherwise this format is wrong. var next = Peek(); if (next == '{') { //this is an escaped } and need to be added to the format. Skip('{'); format += "{"; } else { throw new TemplateParserException($"Expected '{{' but found '{next}' instead in format.", _position, _template); } break; } } format += ReadUntil(TextDelimiters); } } private int ParseAlignment() { Skip(','); SkipSpaces(); int i = ReadInt(); SkipSpaces(); char next = Peek(); if (next != ':' && next != '}') throw new TemplateParserException($"Expected ':' or '}}' but found '{next}' instead.", _position, _template); return i; } private char Peek() => _template[_position]; private char Read() => _template[_position++]; // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local private void Skip(char c) { // Can be out of bounds, but never in correct use (expects a required char). Debug.Assert(_template[_position] == c); _position++; } private void SkipSpaces() { // Can be out of bounds, but never in correct use (inside a hole). while (_template[_position] == ' ') _position++; } private int SkipUntil(char[] search, bool required = true) { int start = _position; int i = _template.IndexOfAny(search, _position); if (i == -1 && required) { var formattedChars = string.Join(", ", search.Select(c => string.Concat("'", c.ToString(), "'")).ToArray()); throw new TemplateParserException($"Reached end of template while expecting one of {formattedChars}.", _position, _template); } _position = i == -1 ? _length : i; return _position - start; } private int ReadInt() { bool negative = false; int i = 0; for (int x = 0; x < 12; ++x) { char c = Peek(); if (c < '0' || c > '9') { if (x > 0 && !negative) return i; if (x > 1 && negative) return -i; if (x == 0 && c == '-') { negative = true; _position++; continue; } break; } _position++; i = i * 10 + (c - '0'); } throw new TemplateParserException("An integer is expected", _position, _template); } private string ReadUntil(char[] search, bool required = true) { int start = _position; return _template.Substring(start, SkipUntil(search, required)); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests { using System; using NLog.Time; using Xunit; public sealed class TimeSourceTests : NLogTestBase, IDisposable { public void Dispose() { TimeSource.Current = new FastLocalTimeSource(); } [Fact] public void AccurateLocalTest() { TestTimeSource(new AccurateLocalTimeSource(), DateTime.Now, DateTimeKind.Local); } [Fact] public void AccurateUtcTest() { TestTimeSource(new AccurateUtcTimeSource(), DateTime.UtcNow, DateTimeKind.Utc); } [Fact] public void FastLocalTest() { TestTimeSource(new FastLocalTimeSource(), DateTime.Now, DateTimeKind.Local); } [Fact] public void FastUtcTest() { TestTimeSource(new FastUtcTimeSource(), DateTime.UtcNow, DateTimeKind.Utc); } [Fact] public void CustomTimeSourceTest() { TestTimeSource(new CustomTimeSource(), DateTime.UtcNow.AddHours(1), DateTimeKind.Unspecified); } [Theory] [InlineData("FastUTC", typeof(FastUtcTimeSource))] [InlineData("FastLocal", typeof(FastLocalTimeSource))] [InlineData("AccurateUTC", typeof(AccurateUtcTimeSource))] [InlineData("AccurateLocal", typeof(AccurateLocalTimeSource))] public void ToStringDefaultImplementationsTest(string expectedName, Type timeSourceType) { var instance = Activator.CreateInstance(timeSourceType) as TimeSource; var actual = instance.ToString(); Assert.Equal(expectedName + " (time source)", actual); } [Theory] [InlineData(typeof(CustomTimeSource))] public void ToStringNoImplementationTest(Type timeSourceType) { var instance = Activator.CreateInstance(timeSourceType) as TimeSource; var expected = timeSourceType.Name; var actual = instance.ToString(); Assert.Equal(expected, actual); } class CustomTimeSource : TimeSource { public override DateTime Time => FromSystemTime(DateTime.UtcNow); public override DateTime FromSystemTime(DateTime systemTime) { return new DateTime(systemTime.ToUniversalTime().AddHours(1).Ticks, DateTimeKind.Unspecified); } } internal class ShiftedTimeSource : TimeSource { private readonly DateTimeKind kind; private DateTimeOffset sourceTime; private TimeSpan systemTimeDelta; public ShiftedTimeSource(DateTimeKind kind) { this.kind = kind; sourceTime = DateTimeOffset.UtcNow; systemTimeDelta = TimeSpan.Zero; } public override DateTime Time => ConvertToKind(sourceTime); public DateTime SystemTime => ConvertToKind(sourceTime - systemTimeDelta); public override DateTime FromSystemTime(DateTime systemTime) { return ConvertToKind(systemTime + systemTimeDelta); } private DateTime ConvertToKind(DateTimeOffset value) { return kind == DateTimeKind.Local ? value.LocalDateTime : value.UtcDateTime; } public void AddToSystemTime(TimeSpan delta) { systemTimeDelta += delta; } public void AddToLocalTime(TimeSpan delta) { sourceTime += delta; } } private static void TestTimeSource(TimeSource source, DateTime expected, DateTimeKind kind) { Assert.IsType<FastLocalTimeSource>(TimeSource.Current); TimeSource.Current = source; Assert.Same(source, TimeSource.Current); var evt = new LogEventInfo(LogLevel.Info, "logger", "msg"); Assert.Equal(kind, evt.TimeStamp.Kind); Assert.True((expected - evt.TimeStamp).Duration() < TimeSpan.FromSeconds(5)); Assert.True((source.Time - source.FromSystemTime(DateTime.UtcNow)).Duration() < TimeSpan.FromSeconds(5)); LogEventInfo evt2; do { evt2 = new LogEventInfo(LogLevel.Info, "logger", "msg"); } while (evt.TimeStamp == evt2.TimeStamp); Assert.Equal(kind, evt2.TimeStamp.Kind); Assert.True(evt2.TimeStamp > evt.TimeStamp); Assert.True(evt2.TimeStamp - evt.TimeStamp <= TimeSpan.FromSeconds(1)); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD || WindowsEventLogPackage namespace NLog.Targets { using System; using System.Diagnostics; using NLog.Common; using NLog.Config; using NLog.Layouts; /// <summary> /// Writes log message to the Event Log. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/EventLog-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/EventLog-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/EventLog/NLog.config" /> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/EventLog/Simple/Example.cs" /> /// </example> [Target("EventLog")] public class EventLogTarget : TargetWithLayout, IInstallable { /// <summary> /// Max size in characters (limitation of the EventLog API). /// </summary> /// <seealso href="https://docs.microsoft.com/en-gb/windows/win32/api/winbase/nf-winbase-reporteventw"/> internal const int EventLogMaxMessageLength = 30000; private readonly IEventLogWrapper _eventLogWrapper; /// <summary> /// Initializes a new instance of the <see cref="EventLogTarget"/> class. /// </summary> public EventLogTarget() : this(null, null) { } /// <summary> /// Initializes a new instance of the <see cref="EventLogTarget"/> class. /// </summary> /// <param name="name">Name of the target.</param> public EventLogTarget(string name) : this(null, null) { Name = name; } /// <summary> /// Initializes a new instance of the <see cref="EventLogTarget"/> class. /// </summary> internal EventLogTarget(IEventLogWrapper eventLogWrapper, string sourceName) { _eventLogWrapper = eventLogWrapper ?? new EventLogWrapper(); Source = sourceName ?? AppDomain.CurrentDomain.FriendlyName; } /// <summary> /// Gets or sets the name of the machine on which Event Log service is running. /// </summary> /// <docgen category='Event Log Options' order='10' /> public string MachineName { get; set; } = "."; /// <summary> /// Gets or sets the layout that renders event ID. /// </summary> /// <docgen category='Event Log Options' order='10' /> public Layout<int> EventId { get; set; } = "${event-properties:item=EventId}"; /// <summary> /// Gets or sets the layout that renders event Category. /// </summary> /// <docgen category='Event Log Options' order='10' /> public Layout<short> Category { get; set; } /// <summary> /// Optional entry type. When not set, or when not convertible to <see cref="EventLogEntryType"/> then determined by <see cref="NLog.LogLevel"/> /// </summary> /// <docgen category='Event Log Options' order='10' /> public Layout<EventLogEntryType> EntryType { get; set; } /// <summary> /// Gets or sets the value to be used as the event Source. /// </summary> /// <remarks> /// By default this is the friendly name of the current AppDomain. /// </remarks> /// <docgen category='Event Log Options' order='10' /> [RequiredParameter] public Layout Source { get; set; } /// <summary> /// Gets or sets the name of the Event Log to write to. This can be System, Application or any user-defined name. /// </summary> /// <docgen category='Event Log Options' order='10' /> public string Log { get; set; } = "Application"; /// <summary> /// Gets or sets the message length limit to write to the Event Log. /// </summary> /// <remarks><value>MaxMessageLength</value> cannot be zero or negative</remarks> /// <docgen category='Event Log Options' order='10' /> public int MaxMessageLength { get => _maxMessageLength; set { if (value <= 0) throw new ArgumentException("MaxMessageLength cannot be zero or negative."); _maxMessageLength = value; } } private int _maxMessageLength = EventLogMaxMessageLength; /// <summary> /// Gets or sets the maximum Event log size in kilobytes. /// </summary> /// <remarks> /// <value>MaxKilobytes</value> cannot be less than 64 or greater than 4194240 or not a multiple of 64. /// If <c>null</c>, the value will not be specified while creating the Event log. /// </remarks> /// <docgen category='Event Log Options' order='10' /> public long? MaxKilobytes { get => _maxKilobytes; set { if (value != null && (value < 64 || value > 4194240 || (value % 64 != 0))) // Event log API restrictions throw new ArgumentException("MaxKilobytes must be a multiple of 64, and between 64 and 4194240"); _maxKilobytes = value; } } private long? _maxKilobytes; /// <summary> /// Gets or sets the action to take if the message is larger than the <see cref="MaxMessageLength"/> option. /// </summary> /// <docgen category='Event Log Options' order='100' /> public EventLogTargetOverflowAction OnOverflow { get; set; } = EventLogTargetOverflowAction.Truncate; /// <summary> /// Performs installation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Install(InstallationContext installationContext) { // always throw error to keep backwards compatible behavior. CreateEventSourceIfNeeded(GetFixedSource(), true); } /// <summary> /// Performs uninstallation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Uninstall(InstallationContext installationContext) { var fixedSource = GetFixedSource(); if (string.IsNullOrEmpty(fixedSource)) { InternalLogger.Debug("{0}: Skipping removing of event source because it contains layout renderers", this); } else { _eventLogWrapper.DeleteEventSource(fixedSource, MachineName); } } /// <summary> /// Determines whether the item is installed. /// </summary> /// <param name="installationContext">The installation context.</param> /// <returns> /// Value indicating whether the item is installed or null if it is not possible to determine. /// </returns> public bool? IsInstalled(InstallationContext installationContext) { var fixedSource = GetFixedSource(); if (!string.IsNullOrEmpty(fixedSource)) { return _eventLogWrapper.SourceExists(fixedSource, MachineName); } InternalLogger.Debug("{0}: Unclear if event source exists because it contains layout renderers", this); return null; //unclear! } /// <inheritdoc/> protected override void InitializeTarget() { base.InitializeTarget(); CreateEventSourceIfNeeded(GetFixedSource(), false); } /// <inheritdoc/> protected override void Write(LogEventInfo logEvent) { string message = RenderLogEvent(Layout, logEvent); EventLogEntryType entryType = GetEntryType(logEvent); int eventId = RenderLogEvent(EventId, logEvent, defaultValue: 0); var category = RenderLogEvent(Category, logEvent, defaultValue: default(short)); var eventLogSource = RenderLogEvent(Source, logEvent); if (string.IsNullOrEmpty(eventLogSource)) { InternalLogger.Warn("{0}: WriteEntry discarded because Source rendered as empty string", this); return; } // limitation of EventLog API if (message.Length > MaxMessageLength) { if (OnOverflow == EventLogTargetOverflowAction.Truncate) { message = message.Substring(0, MaxMessageLength); WriteEntry(eventLogSource, message, entryType, eventId, category); } else if (OnOverflow == EventLogTargetOverflowAction.Split) { for (int offset = 0; offset < message.Length; offset += MaxMessageLength) { string chunk = message.Substring(offset, Math.Min(MaxMessageLength, (message.Length - offset))); WriteEntry(eventLogSource, chunk, entryType, eventId, category); } } else if (OnOverflow == EventLogTargetOverflowAction.Discard) { // message should not be written InternalLogger.Debug("{0}: WriteEntry discarded because too big message size: {1}", this, message.Length); } } else { WriteEntry(eventLogSource, message, entryType, eventId, category); } } private void WriteEntry(string eventLogSource, string message, EventLogEntryType entryType, int eventId, short category) { var isCacheUpToDate = _eventLogWrapper.IsEventLogAssociated && _eventLogWrapper.Log == Log && _eventLogWrapper.MachineName == MachineName && _eventLogWrapper.Source == eventLogSource; if (!isCacheUpToDate) { InternalLogger.Debug("{0}: Refresh EventLog Source {1} and Log {2}", this, eventLogSource, Log); _eventLogWrapper.AssociateNewEventLog(Log, MachineName, eventLogSource); try { if (!_eventLogWrapper.SourceExists(eventLogSource, MachineName)) { InternalLogger.Warn("{0}: Source {1} does not exist", this, eventLogSource); } else { var currentLogName = _eventLogWrapper.LogNameFromSourceName(eventLogSource, MachineName); if (!currentLogName.Equals(Log, StringComparison.OrdinalIgnoreCase)) { InternalLogger.Debug("{0}: Source {1} should be mapped to Log {2}, but EventLog.LogNameFromSourceName returns {3}", this, eventLogSource, Log, currentLogName); } } } catch (Exception ex) { if (LogManager.ThrowExceptions) throw; InternalLogger.Warn(ex, "{0}: Exception thrown when checking if Source {1} and LogName {2} are valid", this, eventLogSource, Log); } } _eventLogWrapper.WriteEntry(message, entryType, eventId, category); } /// <summary> /// Get the entry type for logging the message. /// </summary> /// <param name="logEvent">The logging event - for rendering the <see cref="EntryType"/></param> private EventLogEntryType GetEntryType(LogEventInfo logEvent) { var eventLogEntryType = RenderLogEvent(EntryType, logEvent, (EventLogEntryType)0); if (eventLogEntryType != (EventLogEntryType)0) { return eventLogEntryType; } // determine auto if (logEvent.Level >= LogLevel.Error) { return EventLogEntryType.Error; } if (logEvent.Level >= LogLevel.Warn) { return EventLogEntryType.Warning; } return EventLogEntryType.Information; } /// <summary> /// Get the source, if and only if the source is fixed. /// </summary> /// <returns><c>null</c> when not <see cref="SimpleLayout.IsFixedText"/></returns> /// <remarks>Internal for unit tests</remarks> internal string GetFixedSource() { if (Source is SimpleLayout simpleLayout && simpleLayout.IsFixedText) { return simpleLayout.FixedText; } return null; } /// <summary> /// (re-)create an event source, if it isn't there. Works only with fixed source names. /// </summary> /// <param name="fixedSource">The source name. If source is not fixed (see <see cref="SimpleLayout.IsFixedText"/>, then pass <c>null</c> or <see cref="string.Empty"/>.</param> /// <param name="alwaysThrowError">always throw an Exception when there is an error</param> private void CreateEventSourceIfNeeded(string fixedSource, bool alwaysThrowError) { if (string.IsNullOrEmpty(fixedSource)) { InternalLogger.Debug("{0}: Skipping creation of event source because it contains layout renderers", this); // we can only create event sources if the source is fixed (no layout) return; } // if we throw anywhere, we remain non-operational try { if (_eventLogWrapper.SourceExists(fixedSource, MachineName)) { string currentLogName = _eventLogWrapper.LogNameFromSourceName(fixedSource, MachineName); if (!currentLogName.Equals(Log, StringComparison.OrdinalIgnoreCase)) { InternalLogger.Debug("{0}: Updating source {1} to use log {2}, instead of {3} (Computer restart is needed)", this, fixedSource, Log, currentLogName); // re-create the association between Log and Source _eventLogWrapper.DeleteEventSource(fixedSource, MachineName); var eventSourceCreationData = new EventSourceCreationData(fixedSource, Log) { MachineName = MachineName }; _eventLogWrapper.CreateEventSource(eventSourceCreationData); } } else { InternalLogger.Debug("{0}: Creating source {1} to use log {2}", this, fixedSource, Log); var eventSourceCreationData = new EventSourceCreationData(fixedSource, Log) { MachineName = MachineName }; _eventLogWrapper.CreateEventSource(eventSourceCreationData); } _eventLogWrapper.AssociateNewEventLog(Log, MachineName, fixedSource); if (MaxKilobytes.HasValue && _eventLogWrapper.MaximumKilobytes < MaxKilobytes) { _eventLogWrapper.MaximumKilobytes = MaxKilobytes.Value; } } catch (Exception exception) { InternalLogger.Error(exception, "{0}: Error when connecting to EventLog. Source={1} in Log={2}", this, fixedSource, Log); if (alwaysThrowError || LogManager.ThrowExceptions) { throw; } } } /// <summary> /// A wrapper for Windows event log. /// </summary> internal interface IEventLogWrapper { #region Instance methods /// <summary> /// A wrapper for the property <see cref="EventLog.Source"/>. /// </summary> string Source { get; } /// <summary> /// A wrapper for the property <see cref="EventLog.Log"/>. /// </summary> string Log { get; } /// <summary> /// A wrapper for the property <see cref="EventLog.MachineName"/>. /// </summary> string MachineName { get; } /// <summary> /// A wrapper for the property <see cref="EventLog.MaximumKilobytes"/>. /// </summary> long MaximumKilobytes { get; set; } /// <summary> /// Indicates whether an event log instance is associated. /// </summary> bool IsEventLogAssociated { get; } /// <summary> /// A wrapper for the method <see cref="EventLog.WriteEntry(string, EventLogEntryType, int, short)"/>. /// </summary> void WriteEntry(string message, EventLogEntryType entryType, int eventId, short category); #endregion #region "Static" methods /// <summary> /// Creates a new association with an instance of the event log. /// </summary> void AssociateNewEventLog(string logName, string machineName, string source); /// <summary> /// A wrapper for the static method <see cref="EventLog.DeleteEventSource(string, string)"/>. /// </summary> void DeleteEventSource(string source, string machineName); /// <summary> /// A wrapper for the static method <see cref="EventLog.SourceExists(string, string)"/>. /// </summary> bool SourceExists(string source, string machineName); /// <summary> /// A wrapper for the static method <see cref="EventLog.LogNameFromSourceName(string, string)"/>. /// </summary> string LogNameFromSourceName(string source, string machineName); /// <summary> /// A wrapper for the static method <see cref="EventLog.CreateEventSource(EventSourceCreationData)"/>. /// </summary> void CreateEventSource(EventSourceCreationData sourceData); #endregion } /// <summary> /// The implementation of <see cref="IEventLogWrapper"/>, that uses Windows <see cref="EventLog"/>. /// </summary> private sealed class EventLogWrapper : IEventLogWrapper, IDisposable { private EventLog _windowsEventLog; public string Source { get; private set; } public string Log { get; private set; } public string MachineName { get; private set; } public long MaximumKilobytes { get => _windowsEventLog.MaximumKilobytes; set => _windowsEventLog.MaximumKilobytes = value; } public bool IsEventLogAssociated => _windowsEventLog != null; public void WriteEntry(string message, EventLogEntryType entryType, int eventId, short category) => _windowsEventLog.WriteEntry(message, entryType, eventId, category); /// <summary> /// Creates a new association with an instance of Windows <see cref="EventLog"/>. /// </summary> public void AssociateNewEventLog(string logName, string machineName, string source) { var windowsEventLog = _windowsEventLog; _windowsEventLog = new EventLog(logName, machineName, source); Source = source; Log = logName; MachineName = machineName; windowsEventLog?.Dispose(); } public void DeleteEventSource(string source, string machineName) => EventLog.DeleteEventSource(source, machineName); public bool SourceExists(string source, string machineName) => EventLog.SourceExists(source, machineName); public string LogNameFromSourceName(string source, string machineName) => EventLog.LogNameFromSourceName(source, machineName); public void CreateEventSource(EventSourceCreationData sourceData) => EventLog.CreateEventSource(sourceData); public void Dispose() { _windowsEventLog?.Dispose(); _windowsEventLog = null; } } } } #endif <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Common { /// <summary> /// Represents the logging event with asynchronous continuation. /// </summary> public struct AsyncLogEventInfo : System.IEquatable<AsyncLogEventInfo> { /// <summary> /// Initializes a new instance of the <see cref="AsyncLogEventInfo"/> struct. /// </summary> /// <param name="logEvent">The log event.</param> /// <param name="continuation">The continuation.</param> public AsyncLogEventInfo(LogEventInfo logEvent, AsyncContinuation continuation) { LogEvent = logEvent; Continuation = continuation; } /// <summary> /// Gets the log event. /// </summary> public LogEventInfo LogEvent { get; } /// <summary> /// Gets the continuation. /// </summary> public AsyncContinuation Continuation { get; } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="eventInfo1">The event info1.</param> /// <param name="eventInfo2">The event info2.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(AsyncLogEventInfo eventInfo1, AsyncLogEventInfo eventInfo2) { return eventInfo1.Equals(eventInfo2); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="eventInfo1">The event info1.</param> /// <param name="eventInfo2">The event info2.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(AsyncLogEventInfo eventInfo1, AsyncLogEventInfo eventInfo2) { return !eventInfo1.Equals(eventInfo2); } /// <inheritdoc/> public bool Equals(AsyncLogEventInfo other) => ReferenceEquals(Continuation, other.Continuation) && ReferenceEquals(LogEvent, other.LogEvent); /// <inheritdoc/> public override bool Equals(object obj) => obj is AsyncLogEventInfo other && Equals(other); /// <inheritdoc/> public override int GetHashCode() { return LogEvent.GetHashCode() ^ Continuation.GetHashCode(); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.IO; using System.Security; using System.Xml; using NLog.Common; using NLog.Internal; using NLog.Internal.Fakeables; using NLog.Targets; /// <summary> /// Enables loading of NLog configuration from a file /// </summary> internal class LoggingConfigurationFileLoader : ILoggingConfigurationLoader { private readonly IAppEnvironment _appEnvironment; public LoggingConfigurationFileLoader(IAppEnvironment appEnvironment) { _appEnvironment = appEnvironment; } public virtual LoggingConfiguration Load(LogFactory logFactory, string filename = null) { if (string.IsNullOrEmpty(filename) || FilePathLayout.DetectFilePathKind(filename) == FilePathKind.Relative) { return TryLoadFromFilePaths(logFactory, filename); } else if (TryLoadLoggingConfiguration(logFactory, filename, out var config)) { return config; } return null; } public virtual void Activated(LogFactory logFactory, LoggingConfiguration config) { // Nothing to do } private LoggingConfiguration TryLoadFromFilePaths(LogFactory logFactory, string filename) { #pragma warning disable CS0618 // Type or member is obsolete var configFileNames = logFactory.GetCandidateConfigFilePaths(filename); #pragma warning restore CS0618 // Type or member is obsolete foreach (string configFile in configFileNames) { if (TryLoadLoggingConfiguration(logFactory, configFile, out var config)) return config; } return null; } private bool TryLoadLoggingConfiguration(LogFactory logFactory, string configFile, out LoggingConfiguration config) { try { if (_appEnvironment.FileExists(configFile)) { config = LoadXmlLoggingConfigurationFile(logFactory, configFile); return true; // File exists, and maybe the config is valid, stop search } else { InternalLogger.Debug("No file exists at candidate config file location: {0}", configFile); } } catch (IOException ex) { InternalLogger.Warn(ex, "Skipping invalid config file location: {0}", configFile); } catch (UnauthorizedAccessException ex) { InternalLogger.Warn(ex, "Skipping inaccessible config file location: {0}", configFile); } catch (SecurityException ex) { InternalLogger.Warn(ex, "Skipping inaccessible config file location: {0}", configFile); } catch (Exception ex) { InternalLogger.Error(ex, "Failed loading from config file location: {0}", configFile); if ((logFactory.ThrowConfigExceptions ?? logFactory.ThrowExceptions) || ex.MustBeRethrown()) throw; } config = null; return false; // No valid file found } private LoggingConfiguration LoadXmlLoggingConfigurationFile(LogFactory logFactory, string configFile) { InternalLogger.Debug("Reading config from XML file: {0}", configFile); using (var xmlReader = _appEnvironment.LoadXmlFile(configFile)) { return LoadXmlLoggingConfiguration(xmlReader, configFile, logFactory); } } private LoggingConfiguration LoadXmlLoggingConfiguration(XmlReader xmlReader, string configFile, LogFactory logFactory) { try { var newConfig = new XmlLoggingConfiguration(xmlReader, configFile, logFactory); if (newConfig.InitializeSucceeded != true) { if (ThrowXmlConfigExceptions(configFile, xmlReader, logFactory, out var autoReload)) { using (var xmlReaderRetry = _appEnvironment.LoadXmlFile(configFile)) { newConfig = new XmlLoggingConfiguration(xmlReaderRetry, configFile, logFactory); // Scan again after having updated LogFactory, to throw correct exception } } else if (autoReload && !newConfig.AutoReload) { return CreateEmptyDefaultConfig(configFile, logFactory, autoReload); } } return newConfig; } catch (Exception ex) { if (ex.MustBeRethrown() || (logFactory.ThrowConfigExceptions ?? logFactory.ThrowExceptions)) throw; if (ThrowXmlConfigExceptions(configFile, xmlReader, logFactory, out var autoReload)) throw; return CreateEmptyDefaultConfig(configFile, logFactory, autoReload); } } private static LoggingConfiguration CreateEmptyDefaultConfig(string configFile, LogFactory logFactory, bool autoReload) { return new XmlLoggingConfiguration($"<nlog autoReload='{autoReload}'></nlog>", configFile, logFactory); // Empty default config, but monitors file } private bool ThrowXmlConfigExceptions(string configFile, XmlReader xmlReader, LogFactory logFactory, out bool autoReload) { autoReload = false; try { if (string.IsNullOrEmpty(configFile)) return false; var fileContent = File.ReadAllText(configFile); if (xmlReader.ReadState == ReadState.Error) { // Avoid reacting to throwExceptions="true" that only exists in comments, only check when invalid xml if (ScanForBooleanParameter(fileContent, "throwExceptions", true)) { logFactory.ThrowExceptions = true; return true; } if (ScanForBooleanParameter(fileContent, "throwConfigExceptions", true)) { logFactory.ThrowConfigExceptions = true; return true; } } if (ScanForBooleanParameter(fileContent, "autoReload", true)) { autoReload = true; } return false; } catch (Exception ex) { InternalLogger.Error(ex, "Failed to scan content of config file: {0}", configFile); return false; } } private static bool ScanForBooleanParameter(string fileContent, string parameterName, bool parameterValue) { return fileContent.IndexOf($"{parameterName}=\"{parameterValue}", StringComparison.OrdinalIgnoreCase) >= 0 || fileContent.IndexOf($"{parameterName}='{parameterValue}", StringComparison.OrdinalIgnoreCase) >= 0; } /// <summary> /// Get default file paths (including filename) for possible NLog config files. /// </summary> public IEnumerable<string> GetDefaultCandidateConfigFilePaths(string filename = null) { string baseDirectory = PathHelpers.TrimDirectorySeparators(_appEnvironment.AppDomainBaseDirectory); #if !NETSTANDARD1_3 string entryAssemblyLocation = PathHelpers.TrimDirectorySeparators(_appEnvironment.EntryAssemblyLocation); #else string entryAssemblyLocation = string.Empty; #endif if (filename is null) { // Scan for process specific nlog-files foreach (var filePath in GetAppSpecificNLogLocations(baseDirectory, entryAssemblyLocation)) yield return filePath; } // NLog.config from application directory string nlogConfigFile = filename ?? "NLog.config"; if (!string.IsNullOrEmpty(baseDirectory)) yield return Path.Combine(baseDirectory, nlogConfigFile); string nLogConfigFileLowerCase = nlogConfigFile.ToLower(); bool platformFileSystemCaseInsensitive = nlogConfigFile == nLogConfigFileLowerCase || PlatformDetector.IsWin32; if (!platformFileSystemCaseInsensitive && !string.IsNullOrEmpty(baseDirectory)) yield return Path.Combine(baseDirectory, nLogConfigFileLowerCase); if (!string.IsNullOrEmpty(entryAssemblyLocation) && !string.Equals(entryAssemblyLocation, baseDirectory, StringComparison.OrdinalIgnoreCase)) { yield return Path.Combine(entryAssemblyLocation, nlogConfigFile); if (!platformFileSystemCaseInsensitive) yield return Path.Combine(entryAssemblyLocation, nLogConfigFileLowerCase); } if (string.IsNullOrEmpty(baseDirectory)) { yield return nlogConfigFile; if (!platformFileSystemCaseInsensitive) yield return nLogConfigFileLowerCase; } foreach (var filePath in GetPrivateBinPathNLogLocations(baseDirectory, nlogConfigFile, platformFileSystemCaseInsensitive ? nLogConfigFileLowerCase : string.Empty)) yield return filePath; string nlogAssemblyLocation = filename is null ? LookupNLogAssemblyLocation() : null; if (!string.IsNullOrEmpty(nlogAssemblyLocation)) yield return nlogAssemblyLocation + ".nlog"; } private string LookupNLogAssemblyLocation() { #if !NETSTANDARD1_3 var nlogAssembly = typeof(LogFactory).GetAssembly(); // Get path to NLog.dll.nlog only if the assembly is not in the GAC var nlogAssemblyLocation = nlogAssembly.Location; if (!string.IsNullOrEmpty(nlogAssemblyLocation)) { #if !NETSTANDARD if (nlogAssembly.GlobalAssemblyCache) { return null; } #endif return nlogAssemblyLocation; } #endif return null; } /// <summary> /// Get default file paths (including filename) for possible NLog config files. /// </summary> public IEnumerable<string> GetAppSpecificNLogLocations(string baseDirectory, string entryAssemblyLocation) { // Current config file with .config renamed to .nlog string configurationFile = _appEnvironment.AppDomainConfigurationFile; if (!StringHelpers.IsNullOrWhiteSpace(configurationFile)) { yield return Path.ChangeExtension(configurationFile, ".nlog"); // .nlog file based on the non-vshost version of the current config file const string vshostSubStr = ".vshost."; if (configurationFile.Contains(vshostSubStr)) { yield return Path.ChangeExtension(configurationFile.Replace(vshostSubStr, "."), ".nlog"); } } #if NETSTANDARD && !NETSTANDARD1_3 else { if (string.IsNullOrEmpty(entryAssemblyLocation)) entryAssemblyLocation = baseDirectory; if (PathHelpers.IsTempDir(entryAssemblyLocation, _appEnvironment.UserTempFilePath)) { // Handle Single File Published on NetCore 3.1 and loading side-by-side exe.nlog (Not relevant for Net5.0 and newer) string processFilePath = _appEnvironment.CurrentProcessFilePath; if (!string.IsNullOrEmpty(processFilePath)) { yield return processFilePath + ".nlog"; } } if (!string.IsNullOrEmpty(entryAssemblyLocation)) { string assemblyFileName = _appEnvironment.EntryAssemblyFileName; if (!string.IsNullOrEmpty(assemblyFileName)) { var assemblyBaseName = Path.GetFileNameWithoutExtension(assemblyFileName); if (!string.IsNullOrEmpty(assemblyBaseName)) { // Handle unpublished .NET Core Application, where assembly-filename has dll-extension yield return Path.Combine(entryAssemblyLocation, assemblyBaseName + ".exe.nlog"); } yield return Path.Combine(entryAssemblyLocation, assemblyFileName + ".nlog"); } } } #endif } private IEnumerable<string> GetPrivateBinPathNLogLocations(string baseDirectory, string nlogConfigFile, string nLogConfigFileLowerCase) { IEnumerable<string> privateBinPaths = _appEnvironment.AppDomainPrivateBinPath; if (privateBinPaths != null) { foreach (var privatePath in privateBinPaths) { var path = PathHelpers.TrimDirectorySeparators(privatePath); if (!StringHelpers.IsNullOrWhiteSpace(path) && !string.Equals(path, baseDirectory, StringComparison.OrdinalIgnoreCase)) { yield return Path.Combine(path, nlogConfigFile); if (!string.IsNullOrEmpty(nLogConfigFileLowerCase)) yield return Path.Combine(path, nLogConfigFileLowerCase); } } } } protected virtual void Dispose(bool disposing) { // Nothing to dispose } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets { #if !NET35 using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using NLog.Config; using NLog.Internal; using NLog.Targets; using Xunit; public class AsyncTaskTargetTest : NLogTestBase { [Target("AsyncTaskTest")] class AsyncTaskTestTarget : AsyncTaskTarget { private readonly AutoResetEvent _writeEvent = new AutoResetEvent(false); internal readonly ConcurrentQueue<string> Logs = new ConcurrentQueue<string>(); internal int WriteTasks => _writeTasks; protected int _writeTasks; public Type RequiredDependency { get; set; } public bool WaitForWriteEvent(int timeoutMilliseconds = 1000) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) timeoutMilliseconds = timeoutMilliseconds * 60; #endif if (_writeEvent.WaitOne(TimeSpan.FromMilliseconds(timeoutMilliseconds))) { Thread.Sleep(25); return true; } return false; } protected override void InitializeTarget() { base.InitializeTarget(); if (RequiredDependency != null) { try { var resolveServiceMethod = typeof(Target).GetMethod(nameof(ResolveService), System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); resolveServiceMethod = resolveServiceMethod.MakeGenericMethod(new[] { RequiredDependency }); resolveServiceMethod.Invoke(this, NLog.Internal.ArrayHelper.Empty<object>()); } catch (System.Reflection.TargetInvocationException ex) { throw ex.InnerException; } } } protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token) { Interlocked.Increment(ref _writeTasks); return WriteLogQueue(logEvent, token); } protected async Task WriteLogQueue(LogEventInfo logEvent, CancellationToken token) { if (logEvent.Message == "EXCEPTION") throw new InvalidOperationException("AsyncTaskTargetTest Failure"); else if (logEvent.Message == "ASYNCEXCEPTION") await Task.Delay(10, token).ContinueWith((t) => { throw new InvalidOperationException("AsyncTaskTargetTest Async Failure"); }).ConfigureAwait(false); else if (logEvent.Message == "TIMEOUT") await Task.Delay(15000, token).ConfigureAwait(false); else { if (logEvent.Message == "SLEEP") Task.Delay(5000, token).GetAwaiter().GetResult(); await Task.Delay(10, token).ContinueWith((t) => Logs.Enqueue(RenderLogEvent(Layout, logEvent)), token).ContinueWith(async (t) => await Task.Delay(10).ConfigureAwait(false)).ConfigureAwait(false); } _writeEvent.Set(); } } class AsyncTaskBatchTestTarget : AsyncTaskTestTarget { protected override async Task WriteAsyncTask(IList<LogEventInfo> logEvents, CancellationToken cancellationToken) { Interlocked.Increment(ref _writeTasks); for (int i = 0; i < logEvents.Count; ++i) await WriteLogQueue(logEvents[i], cancellationToken); } protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken) { throw new NotImplementedException(); } } class AsyncTaskBatchExceptionTestTarget : AsyncTaskTestTarget { public List<int> retryDelayLog = new List<int>(); protected override async Task WriteAsyncTask(IList<LogEventInfo> logEvents, CancellationToken cancellationToken) { await Task.Delay(50); throw new Exception("Failed to write to message queue, or something"); } protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken) { throw new NotImplementedException(); } protected override bool RetryFailedAsyncTask(Exception exception, CancellationToken cancellationToken, int retryCountRemaining, out TimeSpan retryDelay) { var shouldRetry = base.RetryFailedAsyncTask(exception, cancellationToken, retryCountRemaining, out retryDelay); retryDelayLog.Add((int)retryDelay.TotalMilliseconds); return shouldRetry; } } [Fact] public void AsyncTaskTarget_TestLogging() { var asyncTarget = new AsyncTaskTestTarget { Layout = "${threadid}|${level}|${message}|${mdlc:item=Test}" }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(asyncTarget); }).GetCurrentClassLogger(); int managedThreadId = 0; Task task; using (ScopeContext.PushProperty("Test", 42)) { task = Task.Run(() => { managedThreadId = Thread.CurrentThread.ManagedThreadId; logger.Trace("TTT"); logger.Debug("DDD"); logger.Info("III"); logger.Warn("WWW"); logger.Error("EEE"); logger.Fatal("FFF"); }); } Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); task.Wait(); logger.Factory.Flush(); Assert.Equal(6, asyncTarget.Logs.Count); while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { Assert.Equal(0, logEventMessage.IndexOf(managedThreadId.ToString() + "|")); Assert.EndsWith("|42", logEventMessage); } logger.Factory.Configuration = null; } [Fact] public void AsyncTaskTarget_SkipAsyncTargetWrapper() { var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterTarget<AsyncTaskTestTarget>("AsyncTaskTest")) .LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets async='true'> <target name='asyncDebug' type='AsyncTaskTest' /> <target name='debug' type='Debug' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; Assert.NotNull(logFactory.Configuration.FindTargetByName<AsyncTaskTestTarget>("asyncDebug")); Assert.NotNull(logFactory.Configuration.FindTargetByName<NLog.Targets.Wrappers.AsyncTargetWrapper>("debug")); } [Fact] public void AsyncTaskTarget_SkipDefaultAsyncWrapper() { var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterTarget<AsyncTaskTestTarget>("AsyncTaskTest")) .LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <default-wrapper type='AsyncWrapper' /> <target name='asyncDebug' type='AsyncTaskTest' /> <target name='debug' type='Debug' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; Assert.NotNull(logFactory.Configuration.FindTargetByName<AsyncTaskTestTarget>("asyncDebug")); Assert.NotNull(logFactory.Configuration.FindTargetByName<NLog.Targets.Wrappers.AsyncTargetWrapper>("debug")); } [Fact] public void AsyncTaskTarget_AllowDefaultBufferWrapper() { var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterTarget<AsyncTaskTestTarget>("AsyncTaskTest")) .LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <default-wrapper type='BufferingWrapper' /> <target name='asyncDebug' type='AsyncTaskTest' /> <target name='debug' type='Debug' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; Assert.NotNull(logFactory.Configuration.FindTargetByName<NLog.Targets.Wrappers.BufferingTargetWrapper>("asyncDebug")); Assert.NotNull(logFactory.Configuration.FindTargetByName<NLog.Targets.Wrappers.BufferingTargetWrapper>("debug")); } [Fact] public void AsyncTaskTarget_TestAsyncException() { var asyncTarget = new AsyncTaskTestTarget { Layout = "${level}", RetryDelayMilliseconds = 50 }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(asyncTarget); }).GetCurrentClassLogger(); foreach (var logLevel in LogLevel.AllLoggingLevels) logger.Log(logLevel, logLevel == LogLevel.Debug ? "ASYNCEXCEPTION" : logLevel.Name.ToUpperInvariant()); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); logger.Factory.Flush(); Assert.Equal(LogLevel.MaxLevel.Ordinal, asyncTarget.Logs.Count); int ordinal = 0; while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { var logLevel = LogLevel.FromString(logEventMessage); Assert.NotEqual(LogLevel.Debug, logLevel); Assert.Equal(ordinal++, logLevel.Ordinal); if (ordinal == LogLevel.Debug.Ordinal) ++ordinal; } logger.Factory.Configuration = null; } [Fact] public void AsyncTaskTarget_TestTimeout() { RetryingIntegrationTest(3, () => { var asyncTarget = new AsyncTaskTestTarget { Layout = "${level}", TaskTimeoutSeconds = 1 }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(asyncTarget); }).GetCurrentClassLogger(); logger.Trace("TTT"); logger.Debug("TIMEOUT"); logger.Info("III"); logger.Warn("WWW"); logger.Error("EEE"); logger.Fatal("FFF"); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); logger.Factory.Flush(); Assert.Equal(5, asyncTarget.Logs.Count); while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { Assert.Equal(-1, logEventMessage.IndexOf("Debug|")); } logger.Factory.Configuration = null; }); } [Fact] public void AsyncTaskTarget_TestRetryAsyncException() { var asyncTarget = new AsyncTaskTestTarget { Layout = "${level}", RetryDelayMilliseconds = 10, RetryCount = 3 }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(asyncTarget); }).GetCurrentClassLogger(); foreach (var logLevel in LogLevel.AllLoggingLevels) logger.Log(logLevel, logLevel == LogLevel.Debug ? "ASYNCEXCEPTION" : logLevel.Name.ToUpperInvariant()); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); logger.Factory.Flush(); Assert.Equal(LogLevel.MaxLevel.Ordinal, asyncTarget.Logs.Count); Assert.Equal(LogLevel.MaxLevel.Ordinal + 4, asyncTarget.WriteTasks); int ordinal = 0; while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { var logLevel = LogLevel.FromString(logEventMessage); Assert.NotEqual(LogLevel.Debug, logLevel); Assert.Equal(ordinal++, logLevel.Ordinal); if (ordinal == LogLevel.Debug.Ordinal) ++ordinal; } logger.Factory.Configuration = null; } [Fact] public void AsyncTaskTarget_TestRetryException() { var asyncTarget = new AsyncTaskTestTarget { Layout = "${level}", RetryDelayMilliseconds = 10, RetryCount = 3 }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(asyncTarget); }).GetCurrentClassLogger(); foreach (var logLevel in LogLevel.AllLoggingLevels) logger.Log(logLevel, logLevel == LogLevel.Debug ? "EXCEPTION" : logLevel.Name.ToUpperInvariant()); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); logger.Factory.Flush(); Assert.Equal(LogLevel.MaxLevel.Ordinal, asyncTarget.Logs.Count); Assert.Equal(LogLevel.MaxLevel.Ordinal + 4, asyncTarget.WriteTasks); int ordinal = 0; while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { var logLevel = LogLevel.FromString(logEventMessage); Assert.NotEqual(LogLevel.Debug, logLevel); Assert.Equal(ordinal++, logLevel.Ordinal); if (ordinal == LogLevel.Debug.Ordinal) ++ordinal; } logger.Factory.Configuration = null; } [Fact] public void AsyncTaskTarget_TestFallbackException() { var asyncTarget = new AsyncTaskTestTarget { Layout = "${level}", RetryDelayMilliseconds = 10, RetryCount = 1 }; var fallbacKTarget = new MemoryTarget() { Layout = "${level}" }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(asyncTarget).WithFallback(fallbacKTarget); }).GetCurrentClassLogger(); foreach (var logLevel in LogLevel.AllLoggingLevels) logger.Log(logLevel, logLevel == LogLevel.Debug ? "EXCEPTION" : logLevel.Name.ToUpperInvariant()); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); logger.Factory.Flush(); Assert.Equal(LogLevel.MaxLevel.Ordinal, asyncTarget.Logs.Count); Assert.Equal(LogLevel.MaxLevel.Ordinal + 2, asyncTarget.WriteTasks); Assert.Single(fallbacKTarget.Logs); Assert.Equal(LogLevel.Debug.ToString(), fallbacKTarget.Logs[0]); int ordinal = 0; while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { var logLevel = LogLevel.FromString(logEventMessage); Assert.NotEqual(LogLevel.Debug, logLevel); Assert.Equal(ordinal++, logLevel.Ordinal); if (ordinal == LogLevel.Debug.Ordinal) ++ordinal; } logger.Factory.Configuration = null; } [Fact] public void AsyncTaskTarget_TestBatchWriting() { var asyncTarget = new AsyncTaskBatchTestTarget { Layout = "${level}", BatchSize = 3, TaskDelayMilliseconds = 10 }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(asyncTarget); }).GetCurrentClassLogger(); foreach (var logLevel in LogLevel.AllLoggingLevels) logger.Log(logLevel, logLevel.Name.ToUpperInvariant()); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); logger.Factory.Flush(); Assert.Equal(LogLevel.MaxLevel.Ordinal + 1, asyncTarget.Logs.Count); Assert.Equal(LogLevel.MaxLevel.Ordinal / 2, asyncTarget.WriteTasks); int ordinal = 0; while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { var logLevel = LogLevel.FromString(logEventMessage); Assert.Equal(ordinal++, logLevel.Ordinal); } logger.Factory.Configuration = null; } [Fact] public void AsyncTaskTarget_TestBatchRetryTimings() { var asyncTarget = new AsyncTaskBatchExceptionTestTarget { Layout = "${level}", BatchSize = 10, TaskDelayMilliseconds = 10, RetryCount = 5, RetryDelayMilliseconds = 3 }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(asyncTarget); }).GetCurrentClassLogger(); logger.Log(LogLevel.Info, "test"); logger.Factory.Flush(); // The zero at the end of the array is used when there will be no more retries. Assert.Equal(new[] { 3, 6, 12, 24, 48, 0 }, asyncTarget.retryDelayLog); logger.Factory.Configuration = null; } [Fact] public void AsyncTaskTarget_TestFakeBatchWriting() { var asyncTarget = new AsyncTaskTestTarget { Layout = "${level}", BatchSize = 3, TaskDelayMilliseconds = 10 }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(asyncTarget); }).GetCurrentClassLogger(); foreach (var logLevel in LogLevel.AllLoggingLevels) logger.Log(logLevel, logLevel.Name.ToUpperInvariant()); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); logger.Factory.Flush(); Assert.Equal(LogLevel.MaxLevel.Ordinal + 1, asyncTarget.Logs.Count); Assert.Equal(LogLevel.MaxLevel.Ordinal + 1, asyncTarget.WriteTasks); int ordinal = 0; while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { var logLevel = LogLevel.FromString(logEventMessage); Assert.Equal(ordinal++, logLevel.Ordinal); } logger.Factory.Configuration = null; } [Fact] public void AsyncTaskTarget_TestSlowBatchWriting() { var asyncTarget = new AsyncTaskBatchTestTarget { Layout = "${level}", TaskDelayMilliseconds = 200 }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(asyncTarget); }).GetCurrentClassLogger(); DateTime utcNow = DateTime.UtcNow; logger.Log(LogLevel.Info, LogLevel.Info.ToString().ToUpperInvariant()); logger.Log(LogLevel.Fatal, "SLEEP"); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.Single(asyncTarget.Logs); logger.Log(LogLevel.Error, LogLevel.Error.ToString().ToUpperInvariant()); asyncTarget.Dispose(); // Trigger fast shutdown logger.Factory.Configuration = null; TimeSpan shutdownTime = DateTime.UtcNow - utcNow; Assert.True(shutdownTime < TimeSpan.FromSeconds(4), $"Shutdown took {shutdownTime.TotalMilliseconds} msec"); } [Fact] public void AsyncTaskTarget_TestThrottleOnTaskDelay() { var asyncTarget = new AsyncTaskBatchTestTarget { Layout = "${level}", TaskDelayMilliseconds = 50, BatchSize = 10, }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(asyncTarget); }).GetCurrentClassLogger(); for (int i = 0; i < 5; ++i) { for (int j = 0; j < 10; ++j) { logger.Log(LogLevel.Info, i.ToString()); Thread.Sleep(20); } Assert.True(asyncTarget.WaitForWriteEvent()); } Assert.True(asyncTarget.Logs.Count > 25, $"{asyncTarget.Logs.Count} LogEvents are too few after {asyncTarget.WriteTasks} writes"); Assert.True(asyncTarget.WriteTasks < 20, $"{asyncTarget.WriteTasks} writes are too many."); } [Fact] public void AsynTaskTarget_AutoFlushWrapper() { var asyncTarget = new AsyncTaskBatchTestTarget { Layout = "${level}", TaskDelayMilliseconds = 5000, BatchSize = 10, }; var autoFlush = new NLog.Targets.Wrappers.AutoFlushTargetWrapper("autoflush", asyncTarget); autoFlush.Condition = "level > LogLevel.Warn"; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(autoFlush); }).GetCurrentClassLogger(); logger.Info("Hello World"); Assert.Empty(asyncTarget.Logs); logger.Error("Goodbye World"); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); } [Fact] public void AsyncTaskTarget_FlushWhenBlocked() { // Arrange var logFactory = new LogFactory(); var logConfig = new LoggingConfiguration(logFactory); var asyncTarget = new AsyncTaskBatchTestTarget { Layout = "${level}", TaskDelayMilliseconds = 10000, BatchSize = 10, QueueLimit = 10, OverflowAction = NLog.Targets.Wrappers.AsyncTargetWrapperOverflowAction.Block, }; logConfig.AddRuleForAllLevels(asyncTarget); logFactory.Configuration = logConfig; var logger = logFactory.GetLogger(nameof(AsyncTaskTarget_FlushWhenBlocked)); // Act for (int i = 0; i < 10; ++i) logger.Info("Testing {0}", i); logFactory.Flush(TimeSpan.FromSeconds(5)); // Assert Assert.Equal(1, asyncTarget.WriteTasks); } [Fact] public void AsyncTaskTarget_MissingDependency_EnqueueLogEvents() { using (new NoThrowNLogExceptions()) { // Arrange var logFactory = new LogFactory(); logFactory.ThrowConfigExceptions = true; var logConfig = new LoggingConfiguration(logFactory); var asyncTarget = new AsyncTaskTestTarget() { Name = "asynctarget", RequiredDependency = typeof(IMisingDependencyClass) }; logConfig.AddRuleForAllLevels(asyncTarget); logFactory.Configuration = logConfig; var logger = logFactory.GetLogger(nameof(AsyncTaskTarget_MissingDependency_EnqueueLogEvents)); // Act logger.Info("Hello World"); Assert.False(asyncTarget.WaitForWriteEvent(50)); logFactory.ServiceRepository.RegisterService(typeof(IMisingDependencyClass), new MisingDependencyClass()); // Assert Assert.True(asyncTarget.WaitForWriteEvent()); } } private interface IMisingDependencyClass { } private class MisingDependencyClass : IMisingDependencyClass { } } #endif }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Common { using JetBrains.Annotations; using System; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using NLog.Internal; using NLog.Time; /// <summary> /// NLog internal logger. /// /// Writes to file, console or custom text writer (see <see cref="InternalLogger.LogWriter"/>) /// </summary> /// <remarks> /// Don't use <see cref="ExceptionHelper.MustBeRethrown"/> as that can lead to recursive calls - stackoverflow /// </remarks> public static partial class InternalLogger { private static readonly object LockObject = new object(); private static string _logFile; /// <summary> /// Set the config of the InternalLogger with defaults and config. /// </summary> public static void Reset() { // TODO: Extract class - InternalLoggerConfigurationReader LogToConsole = GetSetting("nlog.internalLogToConsole", "NLOG_INTERNAL_LOG_TO_CONSOLE", false); LogToConsoleError = GetSetting("nlog.internalLogToConsoleError", "NLOG_INTERNAL_LOG_TO_CONSOLE_ERROR", false); LogLevel = GetSetting("nlog.internalLogLevel", "NLOG_INTERNAL_LOG_LEVEL", LogLevel.Off); LogFile = GetSetting("nlog.internalLogFile", "NLOG_INTERNAL_LOG_FILE", string.Empty); LogToTrace = GetSetting("nlog.internalLogToTrace", "NLOG_INTERNAL_LOG_TO_TRACE", false); IncludeTimestamp = GetSetting("nlog.internalLogIncludeTimestamp", "NLOG_INTERNAL_INCLUDE_TIMESTAMP", true); Info("NLog internal logger initialized."); ExceptionThrowWhenWriting = false; LogWriter = null; LogMessageReceived = null; } /// <summary> /// Gets or sets the minimal internal log level. /// </summary> /// <example>If set to <see cref="NLog.LogLevel.Info"/>, then messages of the levels <see cref="NLog.LogLevel.Info"/>, <see cref="NLog.LogLevel.Error"/> and <see cref="NLog.LogLevel.Fatal"/> will be written.</example> public static LogLevel LogLevel { get => _logLevel; set => _logLevel = value ?? LogLevel.Off; } private static LogLevel _logLevel = LogLevel.Off; /// <summary> /// Gets or sets a value indicating whether internal messages should be written to the console output stream. /// </summary> /// <remarks>Your application must be a console application.</remarks> public static bool LogToConsole { get; set; } /// <summary> /// Gets or sets a value indicating whether internal messages should be written to the console error stream. /// </summary> /// <remarks>Your application must be a console application.</remarks> public static bool LogToConsoleError { get; set; } /// <summary> /// Gets or sets a value indicating whether internal messages should be written to the <see cref="System.Diagnostics"/>.Trace /// </summary> public static bool LogToTrace { get; set; } /// <summary> /// Gets or sets the file path of the internal log file. /// </summary> /// <remarks>A value of <see langword="null" /> value disables internal logging to a file.</remarks> public static string LogFile { get { return _logFile; } set { _logFile = value; if (!string.IsNullOrEmpty(value)) { _logFile = ExpandFilePathVariables(value); CreateDirectoriesIfNeeded(_logFile); } } } /// <summary> /// Gets or sets the text writer that will receive internal logs. /// </summary> public static TextWriter LogWriter { get; set; } /// <summary> /// Event written to the internal log. /// </summary> /// <remarks> /// EventHandler will only be triggered for events, where severity matches the configured <see cref="LogLevel"/>. /// /// Avoid using/calling NLog Logger-objects when handling these internal events, as it will lead to deadlock / stackoverflow. /// </remarks> public static event EventHandler<InternalLoggerMessageEventArgs> LogMessageReceived; /// <summary> /// Gets or sets a value indicating whether timestamp should be included in internal log output. /// </summary> public static bool IncludeTimestamp { get; set; } = true; /// <summary> /// Is there an <see cref="Exception"/> thrown when writing the message? /// </summary> internal static bool ExceptionThrowWhenWriting { get; private set; } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the specified level. /// </summary> /// <param name="level">Log level.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Log(LogLevel level, [Localizable(false)] string message, params object[] args) { Write(null, level, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the specified level. /// </summary> /// <param name="level">Log level.</param> /// <param name="message">Log message.</param> public static void Log(LogLevel level, [Localizable(false)] string message) { Write(null, level, message, null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the specified level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level <paramref name="level"/>. /// </summary> /// <param name="level">Log level.</param> /// <param name="messageFunc">Function that returns the log message.</param> public static void Log(LogLevel level, [Localizable(false)] Func<string> messageFunc) { if (IsLogLevelEnabled(level)) { Write(null, level, messageFunc(), null); } } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the specified level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level <paramref name="level"/>. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="level">Log level.</param> /// <param name="messageFunc">Function that returns the log message.</param> public static void Log(Exception ex, LogLevel level, [Localizable(false)] Func<string> messageFunc) { if (IsLogLevelEnabled(level)) { Write(ex, level, messageFunc(), null); } } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the specified level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="level">Log level.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Log(Exception ex, LogLevel level, [Localizable(false)] string message, params object[] args) { Write(ex, level, message, args); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the specified level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="level">Log level.</param> /// <param name="message">Log message.</param> public static void Log(Exception ex, LogLevel level, [Localizable(false)] string message) { Write(ex, level, message, null); } /// <summary> /// Write to internallogger. /// </summary> /// <param name="ex">optional exception to be logged.</param> /// <param name="level">level</param> /// <param name="message">message</param> /// <param name="args">optional args for <paramref name="message"/></param> private static void Write([CanBeNull]Exception ex, LogLevel level, string message, [CanBeNull]object[] args) { if (!IsLogLevelEnabled(level)) { return; } if (IsSeriousException(ex)) { //no logging! return; } var hasActiveLoggersWithLine = HasActiveLoggersWithLine(); var hasEventListeners = HasEventListeners(); if (!hasActiveLoggersWithLine && !hasEventListeners) { return; } string fullMessage = message; try { fullMessage = CreateFullMessage(message, args); } catch (Exception exception) { if (ex is null) ex = exception; if (LogLevel.Error > level) level = LogLevel.Error; } try { if (hasActiveLoggersWithLine) { WriteLogLine(ex, level, fullMessage); } if (hasEventListeners) { var loggerContext = args?.Length > 0 ? args[0] as IInternalLoggerContext : null; var loggerContextName = string.IsNullOrEmpty(loggerContext?.Name) ? loggerContext?.ToString() : loggerContext.Name; LogMessageReceived?.Invoke(null, new InternalLoggerMessageEventArgs(fullMessage, level, ex, loggerContext?.GetType(), loggerContextName)); ex?.MarkAsLoggedToInternalLogger(); } } catch (Exception exception) { ExceptionThrowWhenWriting = true; // no log looping. // we have no place to log the message to so we ignore it if (exception.MustBeRethrownImmediately()) { throw; } } } private static void WriteLogLine(Exception ex, LogLevel level, string message) { try { string line = CreateLogLine(ex, level, message); WriteToLogFile(line); WriteToTextWriter(line); #if !NETSTANDARD1_3 WriteToConsole(line); WriteToErrorConsole(line); WriteToTrace(line); #endif ex?.MarkAsLoggedToInternalLogger(); } catch (Exception exception) { ExceptionThrowWhenWriting = true; // no log looping. // we have no place to log the message to so we ignore it if (exception.MustBeRethrownImmediately()) { throw; } } } /// <summary> /// Create log line with timestamp, exception message etc (if configured) /// </summary> private static string CreateLogLine([CanBeNull]Exception ex, LogLevel level, string fullMessage) { const string timeStampFormat = "yyyy-MM-dd HH:mm:ss.ffff"; const string fieldSeparator = " "; if (IncludeTimestamp) { return string.Concat( TimeSource.Current.Time.ToString(timeStampFormat, CultureInfo.InvariantCulture), fieldSeparator, level.ToString(), fieldSeparator, fullMessage, ex != null ? " Exception: " : "", ex?.ToString() ?? ""); } else { return string.Concat( level.ToString(), fieldSeparator, fullMessage, ex != null ? " Exception: " : "", ex?.ToString() ?? ""); } } private static string CreateFullMessage(string message, object[] args) { var formattedMessage = (args is null) ? message : string.Format(CultureInfo.InvariantCulture, message, args); return formattedMessage; } /// <summary> /// Determine if logging should be avoided because of exception type. /// </summary> /// <param name="exception">The exception to check.</param> /// <returns><c>true</c> if logging should be avoided; otherwise, <c>false</c>.</returns> private static bool IsSeriousException(Exception exception) { return exception != null && exception.MustBeRethrownImmediately(); } /// <summary> /// Determine if logging is enabled for given LogLevel /// </summary> /// <param name="logLevel">The <see cref="LogLevel"/> for the log event.</param> /// <returns><c>true</c> if logging is enabled; otherwise, <c>false</c>.</returns> private static bool IsLogLevelEnabled(LogLevel logLevel) { return !ReferenceEquals(_logLevel, LogLevel.Off) && _logLevel.CompareTo(logLevel) <= 0; } /// <summary> /// Determine if logging is enabled. /// </summary> /// <returns><c>true</c> if logging is enabled; otherwise, <c>false</c>.</returns> internal static bool HasActiveLoggers() { return HasActiveLoggersWithLine() || HasEventListeners(); } private static bool HasEventListeners() { return LogMessageReceived != null; } internal static bool HasActiveLoggersWithLine() { return !string.IsNullOrEmpty(LogFile) || LogToConsole || LogToConsoleError || LogToTrace || LogWriter != null; } /// <summary> /// Write internal messages to the log file defined in <see cref="LogFile"/>. /// </summary> /// <param name="message">Message to write.</param> /// <remarks> /// Message will be logged only when the property <see cref="LogFile"/> is not <c>null</c>, otherwise the /// method has no effect. /// </remarks> private static void WriteToLogFile(string message) { var logFile = LogFile; if (string.IsNullOrEmpty(logFile)) { return; } lock (LockObject) { using (var textWriter = File.AppendText(logFile)) { textWriter.WriteLine(message); } } } /// <summary> /// Write internal messages to the <see cref="System.IO.TextWriter"/> defined in <see cref="LogWriter"/>. /// </summary> /// <param name="message">Message to write.</param> /// <remarks> /// Message will be logged only when the property <see cref="LogWriter"/> is not <c>null</c>, otherwise the /// method has no effect. /// </remarks> private static void WriteToTextWriter(string message) { var writer = LogWriter; if (writer is null) { return; } lock (LockObject) { writer.WriteLine(message); } } #if !NETSTANDARD1_3 /// <summary> /// Write internal messages to the <see cref="System.Console"/>. /// </summary> /// <param name="message">Message to write.</param> /// <remarks> /// Message will be logged only when the property <see cref="LogToConsole"/> is <c>true</c>, otherwise the /// method has no effect. /// </remarks> private static void WriteToConsole(string message) { if (!LogToConsole) { return; } NLog.Targets.ConsoleTargetHelper.WriteLineThreadSafe(Console.Out, message); } #endif #if !NETSTANDARD1_3 /// <summary> /// Write internal messages to the <see cref="System.Console.Error"/>. /// </summary> /// <param name="message">Message to write.</param> /// <remarks> /// Message will be logged when the property <see cref="LogToConsoleError"/> is <c>true</c>, otherwise the /// method has no effect. /// </remarks> private static void WriteToErrorConsole(string message) { if (!LogToConsoleError) { return; } NLog.Targets.ConsoleTargetHelper.WriteLineThreadSafe(Console.Error, message); } /// <summary> /// Write internal messages to the <see cref="System.Diagnostics.Trace"/>. /// </summary> /// <param name="message">A message to write.</param> /// <remarks> /// Works when property <see cref="LogToTrace"/> set to true. /// The <see cref="System.Diagnostics.Trace"/> is used in Debug and Release configuration. /// The <see cref="System.Diagnostics.Debug"/> works only in Debug configuration and this is reason why is replaced by <see cref="System.Diagnostics.Trace"/>. /// in DEBUG /// </remarks> private static void WriteToTrace(string message) { if (!LogToTrace) { return; } System.Diagnostics.Trace.WriteLine(message, "NLog"); } #endif /// <summary> /// Logs the assembly version and file version of the given Assembly. /// </summary> /// <param name="assembly">The assembly to log.</param> public static void LogAssemblyVersion(Assembly assembly) { try { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 var fileVersionInfo = !string.IsNullOrEmpty(assembly.Location) ? System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location) : null; var globalAssemblyCache = false; #if !NETSTANDARD if (assembly.GlobalAssemblyCache) globalAssemblyCache = true; #endif Info("{0}. File version: {1}. Product version: {2}. GlobalAssemblyCache: {3}", assembly.FullName, fileVersionInfo?.FileVersion, fileVersionInfo?.ProductVersion, globalAssemblyCache); #else Info(assembly.FullName); #endif } catch (Exception ex) { Error(ex, "Error logging version of assembly {0}.", assembly?.FullName); } } private static string GetAppSettings(string configName) { #if !NETSTANDARD try { return System.Configuration.ConfigurationManager.AppSettings[configName]; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } } #endif return null; } private static string GetSettingString(string configName, string envName) { try { string settingValue = GetAppSettings(configName); if (settingValue != null) return settingValue; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } } try { string settingValue = EnvironmentHelper.GetSafeEnvironmentVariable(envName); if (!string.IsNullOrEmpty(settingValue)) return settingValue; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } } return null; } private static LogLevel GetSetting(string configName, string envName, LogLevel defaultValue) { string value = GetSettingString(configName, envName); if (value is null) { return defaultValue; } try { return LogLevel.FromString(value); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } return defaultValue; } } private static T GetSetting<T>(string configName, string envName, T defaultValue) { string value = GetSettingString(configName, envName); if (value is null) { return defaultValue; } try { return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } return defaultValue; } } private static void CreateDirectoriesIfNeeded(string filename) { try { if (LogLevel == LogLevel.Off) { return; } string parentDirectory = Path.GetDirectoryName(filename); if (!string.IsNullOrEmpty(parentDirectory)) { Directory.CreateDirectory(parentDirectory); } } catch (Exception exception) { Error(exception, "Cannot create needed directories to '{0}'.", filename); if (exception.MustBeRethrownImmediately()) { throw; } } } private static string ExpandFilePathVariables(string internalLogFile) { try { if (ContainsSubStringIgnoreCase(internalLogFile, "${currentdir}", out string currentDirToken)) internalLogFile = internalLogFile.Replace(currentDirToken, System.IO.Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar.ToString()); if (ContainsSubStringIgnoreCase(internalLogFile, "${basedir}", out string baseDirToken)) internalLogFile = internalLogFile.Replace(baseDirToken, LogManager.LogFactory.CurrentAppEnvironment.AppDomainBaseDirectory + System.IO.Path.DirectorySeparatorChar.ToString()); if (ContainsSubStringIgnoreCase(internalLogFile, "${tempdir}", out string tempDirToken)) internalLogFile = internalLogFile.Replace(tempDirToken, LogManager.LogFactory.CurrentAppEnvironment.UserTempFilePath + System.IO.Path.DirectorySeparatorChar.ToString()); #if !NETSTANDARD1_3 if (ContainsSubStringIgnoreCase(internalLogFile, "${processdir}", out string processDirToken)) internalLogFile = internalLogFile.Replace(processDirToken, System.IO.Path.GetDirectoryName(LogManager.LogFactory.CurrentAppEnvironment.CurrentProcessFilePath) + System.IO.Path.DirectorySeparatorChar.ToString()); #endif #if !NETSTANDARD1_3 && !NETSTANDARD1_5 if (ContainsSubStringIgnoreCase(internalLogFile, "${commonApplicationDataDir}", out string commonAppDataDirToken)) internalLogFile = internalLogFile.Replace(commonAppDataDirToken, NLog.LayoutRenderers.SpecialFolderLayoutRenderer.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + System.IO.Path.DirectorySeparatorChar.ToString()); if (ContainsSubStringIgnoreCase(internalLogFile, "${userApplicationDataDir}", out string appDataDirToken)) internalLogFile = internalLogFile.Replace(appDataDirToken, NLog.LayoutRenderers.SpecialFolderLayoutRenderer.GetFolderPath(Environment.SpecialFolder.ApplicationData) + System.IO.Path.DirectorySeparatorChar.ToString()); if (ContainsSubStringIgnoreCase(internalLogFile, "${userLocalApplicationDataDir}", out string localapplicationdatadir)) internalLogFile = internalLogFile.Replace(localapplicationdatadir, NLog.LayoutRenderers.SpecialFolderLayoutRenderer.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + System.IO.Path.DirectorySeparatorChar.ToString()); #endif if (internalLogFile.IndexOf('%') >= 0) internalLogFile = Environment.ExpandEnvironmentVariables(internalLogFile); return internalLogFile; } catch { return internalLogFile; } } private static bool ContainsSubStringIgnoreCase(string haystack, string needle, out string result) { int needlePos = haystack.IndexOf(needle, StringComparison.OrdinalIgnoreCase); result = needlePos >= 0 ? haystack.Substring(needlePos, needle.Length) : null; return result != null; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using NLog.Common; using NLog.Config; using NLog.Internal; /// <summary> /// Render environmental information related to logging events. /// </summary> [NLogConfigurationItem] public abstract class LayoutRenderer : ISupportsInitialize, IRenderable { private const int MaxInitialRenderBufferLength = 16384; private int _maxRenderedLength; private bool _isInitialized; private IValueFormatter _valueFormatter; /// <summary> /// Gets the logging configuration this target is part of. /// </summary> protected LoggingConfiguration LoggingConfiguration { get; private set; } /// <summary> /// Value formatter /// </summary> protected IValueFormatter ValueFormatter => _valueFormatter ?? (_valueFormatter = ResolveService<IValueFormatter>()); /// <inheritdoc/> public override string ToString() { var lra = GetType().GetFirstCustomAttribute<LayoutRendererAttribute>(); if (lra != null) { return $"Layout Renderer: ${{{lra.Name}}}"; } return GetType().Name; } /// <summary> /// Renders the value of layout renderer in the context of the specified log event. /// </summary> /// <param name="logEvent">The log event.</param> /// <returns>String representation of a layout renderer.</returns> public string Render(LogEventInfo logEvent) { int initialLength = _maxRenderedLength; if (initialLength > MaxInitialRenderBufferLength) { initialLength = MaxInitialRenderBufferLength; } var builder = new StringBuilder(initialLength); RenderAppendBuilder(logEvent, builder); if (builder.Length > _maxRenderedLength) { _maxRenderedLength = builder.Length; } return builder.ToString(); } /// <inheritdoc/> void ISupportsInitialize.Initialize(LoggingConfiguration configuration) { Initialize(configuration); } /// <inheritdoc/> void ISupportsInitialize.Close() { Close(); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> internal void Initialize(LoggingConfiguration configuration) { if (LoggingConfiguration is null) LoggingConfiguration = configuration; if (!_isInitialized) { Initialize(); } } private void Initialize() { try { PropertyHelper.CheckRequiredParameters(ConfigurationItemFactory.Default, this); InitializeLayoutRenderer(); } catch (Exception ex) { InternalLogger.Error(ex, "Exception in layout renderer initialization."); if (ex.MustBeRethrown()) { throw; } } finally { _isInitialized = true; // Only one attempt, must Close to retry } } /// <summary> /// Closes this instance. /// </summary> internal void Close() { if (_isInitialized) { LoggingConfiguration = null; _valueFormatter = null; _isInitialized = false; CloseLayoutRenderer(); } } /// <summary> /// Renders the value of layout renderer in the context of the specified log event. /// </summary> /// <param name="logEvent">The log event.</param> /// <param name="builder">The layout render output is appended to builder</param> internal void RenderAppendBuilder(LogEventInfo logEvent, StringBuilder builder) { if (!_isInitialized) { Initialize(); } try { Append(builder, logEvent); } catch (Exception exception) { InternalLogger.Warn(exception, "Exception in layout renderer."); if (exception.MustBeRethrown()) { throw; } } } /// <summary> /// Renders the value of layout renderer in the context of the specified log event into <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected abstract void Append(StringBuilder builder, LogEventInfo logEvent); /// <summary> /// Initializes the layout renderer. /// </summary> protected virtual void InitializeLayoutRenderer() { } /// <summary> /// Closes the layout renderer. /// </summary> protected virtual void CloseLayoutRenderer() { } /// <summary> /// Get the <see cref="IFormatProvider"/> for rendering the messages to a <see cref="string"/> /// </summary> /// <param name="logEvent">LogEvent with culture</param> /// <param name="layoutCulture">Culture in on Layout level</param> /// <returns></returns> protected IFormatProvider GetFormatProvider(LogEventInfo logEvent, IFormatProvider layoutCulture = null) { return logEvent.FormatProvider ?? layoutCulture ?? LoggingConfiguration?.DefaultCultureInfo; } /// <summary> /// Get the <see cref="CultureInfo"/> for rendering the messages to a <see cref="string"/> /// </summary> /// <param name="logEvent">LogEvent with culture</param> /// <param name="layoutCulture">Culture in on Layout level</param> /// <returns></returns> /// <remarks> /// <see cref="GetFormatProvider"/> is preferred /// </remarks> protected CultureInfo GetCulture(LogEventInfo logEvent, CultureInfo layoutCulture = null) { return logEvent.FormatProvider as CultureInfo ?? layoutCulture ?? LoggingConfiguration?.DefaultCultureInfo; } /// <summary> /// Register a custom layout renderer. /// </summary> /// <remarks>Short-cut for registering to default <see cref="ConfigurationItemFactory"/></remarks> /// <typeparam name="T">Type of the layout renderer.</typeparam> /// <param name="name">The layout-renderer type-alias for use in NLog configuration - without '${ }'</param> [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public static void Register<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(string name) where T : LayoutRenderer { var layoutRendererType = typeof(T); Register(name, layoutRendererType); } /// <summary> /// Register a custom layout renderer. /// </summary> /// <remarks>Short-cut for registering to default <see cref="ConfigurationItemFactory"/></remarks> /// <param name="layoutRendererType"> Type of the layout renderer.</param> /// <param name="name">The layout-renderer type-alias for use in NLog configuration - without '${ }'</param> [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public static void Register(string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type layoutRendererType) { Guard.ThrowIfNull(layoutRendererType); Guard.ThrowIfNullOrEmpty(name); ConfigurationItemFactory.Default.GetLayoutRendererFactory().RegisterDefinition(name, layoutRendererType); } /// <summary> /// Register a custom layout renderer with a callback function <paramref name="func"/>. The callback receives the logEvent. /// </summary> /// <param name="name">The layout-renderer type-alias for use in NLog configuration - without '${ }'</param> /// <param name="func">Callback that returns the value for the layout renderer.</param> [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public static void Register(string name, Func<LogEventInfo, object> func) { Guard.ThrowIfNull(func); Register(name, (info, configuration) => func(info)); } /// <summary> /// Register a custom layout renderer with a callback function <paramref name="func"/>. The callback receives the logEvent and the current configuration. /// </summary> /// <param name="name">The layout-renderer type-alias for use in NLog configuration - without '${ }'</param> /// <param name="func">Callback that returns the value for the layout renderer.</param> [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public static void Register(string name, Func<LogEventInfo, LoggingConfiguration, object> func) { Guard.ThrowIfNull(func); var layoutRenderer = new FuncLayoutRenderer(name, func); Register(layoutRenderer); } /// <summary> /// Register a custom layout renderer with a callback function <paramref name="layoutRenderer"/>. The callback receives the logEvent and the current configuration. /// </summary> /// <param name="layoutRenderer">Renderer with callback func</param> [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public static void Register(FuncLayoutRenderer layoutRenderer) { Guard.ThrowIfNull(layoutRenderer); ConfigurationItemFactory.Default.GetLayoutRendererFactory().RegisterFuncLayout(layoutRenderer.LayoutRendererName, layoutRenderer); } /// <summary> /// Resolves the interface service-type from the service-repository /// </summary> protected T ResolveService<T>() where T : class { return LoggingConfiguration.GetServiceProvider().ResolveService<T>(_isInitialized); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { /// <summary> /// Colored console output color. /// </summary> /// <remarks> /// Note that this enumeration is defined to be binary compatible with /// .NET 2.0 System.ConsoleColor + some additions /// </remarks> public enum ConsoleOutputColor { /// <summary> /// Black Color (#000000). /// </summary> Black = 0, /// <summary> /// Dark blue Color (#000080). /// </summary> DarkBlue = 1, /// <summary> /// Dark green Color (#008000). /// </summary> DarkGreen = 2, /// <summary> /// Dark Cyan Color (#008080). /// </summary> DarkCyan = 3, /// <summary> /// Dark Red Color (#800000). /// </summary> DarkRed = 4, /// <summary> /// Dark Magenta Color (#800080). /// </summary> DarkMagenta = 5, /// <summary> /// Dark Yellow Color (#808000). /// </summary> DarkYellow = 6, /// <summary> /// Gray Color (#C0C0C0). /// </summary> Gray = 7, /// <summary> /// Dark Gray Color (#808080). /// </summary> DarkGray = 8, /// <summary> /// Blue Color (#0000FF). /// </summary> Blue = 9, /// <summary> /// Green Color (#00FF00). /// </summary> Green = 10, /// <summary> /// Cyan Color (#00FFFF). /// </summary> Cyan = 11, /// <summary> /// Red Color (#FF0000). /// </summary> Red = 12, /// <summary> /// Magenta Color (#FF00FF). /// </summary> Magenta = 13, /// <summary> /// Yellow Color (#FFFF00). /// </summary> Yellow = 14, /// <summary> /// White Color (#FFFFFF). /// </summary> White = 15, /// <summary> /// Don't change the color. /// </summary> NoChange = 16, } }<file_sep>using System; using NLog; using NLog.Targets; using NLog.Win32.Targets; using System.Diagnostics; class Example { static void Main(string[] args) { PerfCounterTarget target = new PerfCounterTarget(); target.AutoCreate = true; target.CategoryName = "My category"; target.CounterName = "My counter"; target.CounterType = PerformanceCounterType.NumberOfItems32; target.InstanceName = "My instance"; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.Linq; using NLog.Internal; /// <summary> /// Nested Diagnostics Context - a thread-local structure that keeps a stack /// of strings and provides methods to output them in layouts /// </summary> [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public static class NestedDiagnosticsContext { /// <summary> /// Gets the top NDC message but doesn't remove it. /// </summary> /// <returns>The top message. .</returns> [Obsolete("Replaced by ScopeContext.PeekNestedState. Marked obsolete on NLog 5.0")] public static string TopMessage => FormatHelper.ConvertToString(TopObject, null); /// <summary> /// Gets the top NDC object but doesn't remove it. /// </summary> /// <returns>The object at the top of the NDC stack if defined; otherwise <c>null</c>.</returns> [Obsolete("Replaced by ScopeContext.PeekNestedState. Marked obsolete on NLog 5.0")] public static object TopObject => PeekObject(); /// <summary> /// Pushes the specified text on current thread NDC. /// </summary> /// <param name="text">The text to be pushed.</param> /// <returns>An instance of the object that implements IDisposable that returns the stack to the previous level when IDisposable.Dispose() is called. To be used with C# using() statement.</returns> [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public static IDisposable Push(string text) { return ScopeContext.PushNestedState(text); } /// <summary> /// Pushes the specified object on current thread NDC. /// </summary> /// <param name="value">The object to be pushed.</param> /// <returns>An instance of the object that implements IDisposable that returns the stack to the previous level when IDisposable.Dispose() is called. To be used with C# using() statement.</returns> [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public static IDisposable Push(object value) { return ScopeContext.PushNestedState(value); } /// <summary> /// Pops the top message off the NDC stack. /// </summary> /// <returns>The top message which is no longer on the stack.</returns> [Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")] public static string Pop() { return Pop(null); } /// <summary> /// Pops the top message from the NDC stack. /// </summary> /// <param name="formatProvider">The <see cref="IFormatProvider"/> to use when converting the value to a string.</param> /// <returns>The top message, which is removed from the stack, as a string value.</returns> [Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")] public static string Pop(IFormatProvider formatProvider) { return FormatHelper.ConvertToString(PopObject() ?? string.Empty, formatProvider); } /// <summary> /// Pops the top object off the NDC stack. /// </summary> /// <returns>The object from the top of the NDC stack, if defined; otherwise <c>null</c>.</returns> [Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")] public static object PopObject() { return ScopeContext.PopNestedContextLegacy(); } /// <summary> /// Peeks the first object on the NDC stack /// </summary> /// <returns>The object from the top of the NDC stack, if defined; otherwise <c>null</c>.</returns> [Obsolete("Replaced by ScopeContext.PeekNestedState. Marked obsolete on NLog 5.0")] public static object PeekObject() { return ScopeContext.PeekNestedState(); } /// <summary> /// Clears current thread NDC stack. /// </summary> [Obsolete("Replaced by ScopeContext.Clear. Marked obsolete on NLog 5.0")] public static void Clear() { ScopeContext.ClearNestedContextLegacy(); } /// <summary> /// Gets all messages on the stack. /// </summary> /// <returns>Array of strings on the stack.</returns> [Obsolete("Replaced by ScopeContext.GetAllNestedStates. Marked obsolete on NLog 5.0")] public static string[] GetAllMessages() { return GetAllMessages(null); } /// <summary> /// Gets all messages from the stack, without removing them. /// </summary> /// <param name="formatProvider">The <see cref="IFormatProvider"/> to use when converting a value to a string.</param> /// <returns>Array of strings.</returns> [Obsolete("Replaced by ScopeContext.GetAllNestedStates. Marked obsolete on NLog 5.0")] public static string[] GetAllMessages(IFormatProvider formatProvider) { var stack = GetAllObjects(); if (stack.Length == 0) return ArrayHelper.Empty<string>(); else return stack.Select((o) => FormatHelper.ConvertToString(o, formatProvider)).ToArray(); } /// <summary> /// Gets all objects on the stack. /// </summary> /// <returns>Array of objects on the stack.</returns> [Obsolete("Replaced by ScopeContext.GetAllNestedStates. Marked obsolete on NLog 5.0")] public static object[] GetAllObjects() { return ScopeContext.GetAllNestedStates(); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NET35 && !NET40 && !NET45 namespace NLog.Internal { using System; using System.Collections.Generic; /// <summary> /// Immutable state that combines ScopeContext MDLC + NDLC for <see cref="System.Threading.AsyncLocal{T}"/> /// </summary> internal abstract class ScopeContextAsyncState : IDisposable { public IScopeContextAsyncState Parent { get; } private bool _disposed; protected ScopeContextAsyncState(IScopeContextAsyncState parent) { Parent = parent; } void IDisposable.Dispose() { if (!_disposed) { ScopeContext.SetAsyncLocalContext(Parent); _disposed = true; } } } /// <summary> /// Immutable state that combines ScopeContext MDLC + NDLC for <see cref="System.Threading.AsyncLocal{T}"/> /// </summary> internal interface IScopeContextAsyncState : IDisposable { IScopeContextAsyncState Parent { get; } object NestedState { get; } long NestedStateTimestamp { get; } IReadOnlyCollection<KeyValuePair<string, object>> CaptureContextProperties(ref ScopeContextPropertyCollector contextCollector); IList<object> CaptureNestedContext(ref ScopeContextNestedStateCollector contextCollector); } struct ScopeContextPropertyCollector { IReadOnlyCollection<KeyValuePair<string, object>> _allProperties; List<KeyValuePair<string, object>> _propertyCollector; public bool IsCollectorEmpty => _allProperties is null || (_allProperties.Count == 0 && _propertyCollector is null); public bool IsCollectorInactive => _allProperties is null; public ScopeContextPropertyCollector(List<KeyValuePair<string, object>> propertyCollector = null) { _allProperties = _propertyCollector = propertyCollector; } public IReadOnlyCollection<KeyValuePair<string, object>> StartCaptureProperties(IScopeContextAsyncState state) { while (state != null) { var result = state.CaptureContextProperties(ref this); if (result != null) return result; state = state.Parent; } return CaptureCompleted(null); } public IReadOnlyCollection<KeyValuePair<string, object>> CaptureCompleted(IReadOnlyCollection<KeyValuePair<string, object>> properties) { if (_allProperties?.Count > 0) { if (properties?.Count > 0) { if (_propertyCollector is null) { return _allProperties = MergeUniqueProperties(properties); } AddProperties(properties); } return _allProperties = EnsureUniqueProperties(_allProperties); } else { if (properties?.Count > 0) return _allProperties = EnsureUniqueProperties(properties); else return _allProperties = Array.Empty<KeyValuePair<string, object>>(); } } private IReadOnlyCollection<KeyValuePair<string, object>> MergeUniqueProperties(IReadOnlyCollection<KeyValuePair<string, object>> properties) { var scopeProperties = new Dictionary<string, object>(_allProperties.Count + properties.Count, ScopeContext.DefaultComparer); ScopeContextPropertyEnumerator<object>.CopyScopePropertiesToDictionary(properties, scopeProperties); ScopeContextPropertyEnumerator<object>.CopyScopePropertiesToDictionary(_allProperties, scopeProperties); return scopeProperties; } private static IReadOnlyCollection<KeyValuePair<string, object>> EnsureUniqueProperties(IReadOnlyCollection<KeyValuePair<string, object>> properties) { if (properties.Count > 1) { // Must validate that collected properties are unique if (properties is Dictionary<string, object> dictionary && ReferenceEquals(dictionary.Comparer, ScopeContext.DefaultComparer)) { return properties; } else if (properties.Count > 10 || !ScopeContextPropertyEnumerator<object>.HasUniqueCollectionKeys(properties, ScopeContext.DefaultComparer)) { var scopeProperties = new Dictionary<string, object>(Math.Min(properties.Count, 10), ScopeContext.DefaultComparer); ScopeContextPropertyEnumerator<object>.CopyScopePropertiesToDictionary(properties, scopeProperties); return scopeProperties; } } return properties; } public void AddProperty(string propertyName, object propertyValue) { if (IsCollectorEmpty) { _allProperties = new[] { new KeyValuePair<string, object>(propertyName, propertyValue) }; } else { if (_propertyCollector is null) { _propertyCollector = new List<KeyValuePair<string, object>>(Math.Max(4, _allProperties.Count + 1)); _propertyCollector.Add(new KeyValuePair<string, object>(propertyName, propertyValue)); CollectProperties(_allProperties); _allProperties = _propertyCollector; } else { _propertyCollector.Insert(0, new KeyValuePair<string, object>(propertyName, propertyValue)); } } } public void AddProperties(IReadOnlyCollection<KeyValuePair<string, object>> properties) { if (IsCollectorEmpty) { _allProperties = properties; } else if (properties?.Count > 0) { if (_propertyCollector is null) { _propertyCollector = new List<KeyValuePair<string, object>>(Math.Max(4, _allProperties.Count + properties.Count)); CollectProperties(properties); CollectProperties(_allProperties); _allProperties = _propertyCollector; } else if (_propertyCollector.Count == 0) { CollectProperties(properties); } else { int insertPosition = 0; using (var scopeEnumerator = new ScopeContextPropertyEnumerator<object>(properties)) { while (scopeEnumerator.MoveNext()) { var property = scopeEnumerator.Current; _propertyCollector.Insert(insertPosition++, property); } } } } } private void CollectProperties(IReadOnlyCollection<KeyValuePair<string, object>> properties) { using (var scopeEnumerator = new ScopeContextPropertyEnumerator<object>(properties)) { while (scopeEnumerator.MoveNext()) { var property = scopeEnumerator.Current; _propertyCollector.Add(property); } } } } struct ScopeContextNestedStateCollector { private IList<object> _allNestedStates; private List<object> _nestedStateCollector; public bool IsCollectorEmpty => _allNestedStates is null || (_allNestedStates.Count == 0 && _nestedStateCollector is null); public bool IsCollectorInactive => _allNestedStates is null; public IList<object> StartCaptureNestedStates(IScopeContextAsyncState state) { _allNestedStates = _allNestedStates ?? Array.Empty<object>(); while (state != null) { var result = state.CaptureNestedContext(ref this); if (result != null) return result; state = state.Parent; } return _allNestedStates; } public void PushNestedState(object state) { if (_nestedStateCollector is null) { _nestedStateCollector = new List<object>(Math.Max(4, _allNestedStates?.Count ?? 0 + 1)); if (_allNestedStates?.Count > 0) { for (int i = 0; i < _allNestedStates.Count; ++i) _nestedStateCollector.Add(_allNestedStates[i]); } _allNestedStates = _nestedStateCollector; } _nestedStateCollector.Add(state); // Collected in "reversed" order } } /// <summary> /// Immutable state for ScopeContext Mapped Context (MDLC) /// </summary> internal interface IScopeContextPropertiesAsyncState : IScopeContextAsyncState { } /// <summary> /// Immutable state for ScopeContext Nested State (NDLC) /// </summary> internal sealed class ScopedContextNestedAsyncState<T> : ScopeContextAsyncState, IScopeContextAsyncState { private readonly T _value; public ScopedContextNestedAsyncState(IScopeContextAsyncState parent, T state) :base(parent) { NestedStateTimestamp = ScopeContext.GetNestedContextTimestampNow(); _value = state; } object IScopeContextAsyncState.NestedState => _value; public long NestedStateTimestamp { get; } IList<object> IScopeContextAsyncState.CaptureNestedContext(ref ScopeContextNestedStateCollector contextCollector) { if (contextCollector.IsCollectorEmpty) { if (Parent is null) { return new object[] { _value }; // We are done } else if (contextCollector.IsCollectorInactive) { contextCollector.PushNestedState(_value); // Mark as active return contextCollector.StartCaptureNestedStates(Parent); } } contextCollector.PushNestedState(_value); return null; // continue with parent } IReadOnlyCollection<KeyValuePair<string, object>> IScopeContextAsyncState.CaptureContextProperties(ref ScopeContextPropertyCollector contextCollector) { if (contextCollector.IsCollectorInactive) { if (Parent is null) { return Array.Empty<KeyValuePair<string, object>>(); // We are done } else { contextCollector.AddProperties(Array.Empty<KeyValuePair<string, object>>()); // Mark as active return contextCollector.StartCaptureProperties(Parent); // Start parent enumeration } } else { return null; // Continue with Parent } } public override string ToString() { return _value?.ToString() ?? "null"; } } /// <summary> /// Immutable state for ScopeContext Single Property (MDLC) /// </summary> internal sealed class ScopeContextPropertyAsyncState<TValue> : ScopeContextAsyncState, IScopeContextPropertiesAsyncState { long IScopeContextAsyncState.NestedStateTimestamp => 0; object IScopeContextAsyncState.NestedState => null; public string Name { get; } public TValue Value { get; } private IReadOnlyCollection<KeyValuePair<string, object>> _allProperties; public ScopeContextPropertyAsyncState(IScopeContextAsyncState parent, string name, TValue value) : base(parent) { Name = name; Value = value; } IList<object> IScopeContextAsyncState.CaptureNestedContext(ref ScopeContextNestedStateCollector contextCollector) { if (contextCollector.IsCollectorInactive) { if (Parent is null) { return Array.Empty<object>(); // We are done } else { return contextCollector.StartCaptureNestedStates(Parent); } } return null; // Continue with Parent } IReadOnlyCollection<KeyValuePair<string, object>> IScopeContextAsyncState.CaptureContextProperties(ref ScopeContextPropertyCollector contextCollector) { if (contextCollector.IsCollectorEmpty) { if (_allProperties is null) { contextCollector.AddProperty(Name, Value); _allProperties = contextCollector.StartCaptureProperties(Parent); // Capture all properties from parents } return _allProperties; // We are done } else { if (_allProperties is null) { contextCollector.AddProperty(Name, Value); return null; // Continue with Parent } else { return contextCollector.CaptureCompleted(_allProperties); // We are done } } } public override string ToString() { return $"{Name}={Value?.ToString() ?? "null"}"; } } /// <summary> /// Immutable state for ScopeContext Multiple Properties (MDLC) /// </summary> internal sealed class ScopeContextPropertiesAsyncState<TValue> : ScopeContextAsyncState, IScopeContextPropertiesAsyncState, IReadOnlyCollection<KeyValuePair<string, object>> { public long NestedStateTimestamp { get; } public object NestedState { get; } private readonly IReadOnlyCollection<KeyValuePair<string, TValue>> _scopeProperties; private IReadOnlyCollection<KeyValuePair<string, object>> _allProperties; public ScopeContextPropertiesAsyncState(IScopeContextAsyncState parent, Dictionary<string, object> allProperties) : base(parent) { _allProperties = allProperties; // Collapsed dictionary that includes all properties from parent scopes with case-insensitive-comparer } public ScopeContextPropertiesAsyncState(IScopeContextAsyncState parent, Dictionary<string, object> allProperties, object nestedState) : base(parent) { _allProperties = allProperties; // Collapsed dictionary that includes all properties from parent scopes with case-insensitive-comparer NestedState = nestedState; NestedStateTimestamp = ScopeContext.GetNestedContextTimestampNow(); } public ScopeContextPropertiesAsyncState(IScopeContextAsyncState parent, IReadOnlyCollection<KeyValuePair<string, TValue>> scopeProperties) : base(parent) { _scopeProperties = scopeProperties; } public ScopeContextPropertiesAsyncState(IScopeContextAsyncState parent, IReadOnlyCollection<KeyValuePair<string, TValue>> scopeProperties, object nestedState) : base(parent) { _scopeProperties = scopeProperties; NestedState = nestedState; NestedStateTimestamp = ScopeContext.GetNestedContextTimestampNow(); } IList<object> IScopeContextAsyncState.CaptureNestedContext(ref ScopeContextNestedStateCollector contextCollector) { if (NestedState is null) { if (contextCollector.IsCollectorInactive) return contextCollector.StartCaptureNestedStates(Parent); else return null; // continue with parent } else { if (contextCollector.IsCollectorEmpty) { if (Parent is null) { return new object[] { NestedState }; // We are done } else if (contextCollector.IsCollectorInactive) { contextCollector.PushNestedState(NestedState); // Mark as active return contextCollector.StartCaptureNestedStates(Parent); } } contextCollector.PushNestedState(NestedState); return null; // continue with parent } } IReadOnlyCollection<KeyValuePair<string, object>> IScopeContextAsyncState.CaptureContextProperties(ref ScopeContextPropertyCollector contextCollector) { if (contextCollector.IsCollectorEmpty) { if (_allProperties is null) { contextCollector.AddProperties(_scopeProperties as IReadOnlyCollection<KeyValuePair<string, object>> ?? this); _allProperties = contextCollector.StartCaptureProperties(Parent); // Capture all properties from parents } return _allProperties; // We are done } else { if (_allProperties is null) { contextCollector.AddProperties(_scopeProperties as IReadOnlyCollection<KeyValuePair<string, object>> ?? this); return null; // Continue with Parent } else { return contextCollector.CaptureCompleted(_allProperties); // We are done } } } public override string ToString() { return NestedState?.ToString() ?? $"Count = {Count}"; } public int Count => _scopeProperties.Count; IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator() => new ScopeContextPropertyEnumerator<TValue>(_scopeProperties); System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => new ScopeContextPropertyEnumerator<TValue>(_scopeProperties); } /// <summary> /// Immutable state for ScopeContext handling legacy MDLC + NDLC operations /// </summary> [Obsolete("Replaced by ScopeContext.PushProperty / ScopeContext.PushNestedState")] internal sealed class ScopeContextLegacyAsyncState : ScopeContextAsyncState, IScopeContextAsyncState { public object[] NestedContext { get; } public IReadOnlyCollection<KeyValuePair<string, object>> MappedContext { get; } public long NestedStateTimestamp { get; } public ScopeContextLegacyAsyncState(IReadOnlyCollection<KeyValuePair<string, object>> allProperties, object[] nestedContext, long nestedContextTimestamp) :base(null) // Always top parent { MappedContext = allProperties; NestedContext = nestedContext; NestedStateTimestamp = nestedContextTimestamp; } public static void CaptureLegacyContext(IScopeContextAsyncState contextState, out Dictionary<string, object> allProperties, out object[] nestedContext, out long nestedContextTimestamp) { var nestedStateCollector = new ScopeContextNestedStateCollector(); var propertyCollector = new ScopeContextPropertyCollector(); var nestedStates = contextState?.CaptureNestedContext(ref nestedStateCollector) ?? Array.Empty<object>(); var scopeProperties = contextState?.CaptureContextProperties(ref propertyCollector) ?? Array.Empty<KeyValuePair<string, object>>(); allProperties = new Dictionary<string, object>(scopeProperties.Count, ScopeContext.DefaultComparer); ScopeContextPropertyEnumerator<object>.CopyScopePropertiesToDictionary(scopeProperties, allProperties); nestedContextTimestamp = 0L; if (nestedStates?.Count > 0) { var parent = contextState; while (parent != null) { if (parent.NestedStateTimestamp != 0L) nestedContextTimestamp = parent.NestedStateTimestamp; parent = parent.Parent; } if (nestedContextTimestamp == 0L) nestedContextTimestamp = ScopeContext.GetNestedContextTimestampNow(); nestedContext = nestedStates as object[]; if (nestedContext == null) nestedContext = System.Linq.Enumerable.ToArray(nestedStates); } else { nestedContext = Array.Empty<object>(); } } object IScopeContextAsyncState.NestedState => NestedContext?.Length > 0 ? NestedContext[0] : null; IList<object> IScopeContextAsyncState.CaptureNestedContext(ref ScopeContextNestedStateCollector contextCollector) { if (contextCollector.IsCollectorEmpty) { if (NestedContext?.Length > 0) { var nestedStates = new object[NestedContext.Length]; for (int i = 0; i < nestedStates.Length; ++i) nestedStates[i] = NestedContext[i]; return nestedStates; // We are done } else { return Array.Empty<object>(); // We are done } } else { for (int i = 0; i < NestedContext.Length; ++i) contextCollector.PushNestedState(NestedContext[i]); return contextCollector.StartCaptureNestedStates(null); // We are done } } IReadOnlyCollection<KeyValuePair<string, object>> IScopeContextAsyncState.CaptureContextProperties(ref ScopeContextPropertyCollector contextCollector) { if (contextCollector.IsCollectorEmpty) { return MappedContext; // We are done } else { return contextCollector.CaptureCompleted(MappedContext); // We are done } } public override string ToString() { if (NestedContext?.Length > 0) return NestedContext[NestedContext.Length - 1]?.ToString() ?? "null"; else return base.ToString(); } } } #endif<file_sep># Security Policy ## Supported Versions Currently being supported with security updates. | Version | Supported | | ------- | ------------------ | | 5.0.x | :white_check_mark: | | 4.7.x | :white_check_mark: | | < 4.7 | :x: | ## Reporting a Vulnerability Please open an issue, without details. We will contact you then. <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Layouts { using System; using System.Collections.Generic; using System.Globalization; using NLog.Layouts; using Xunit; public class CsvLayoutTests : NLogTestBase { [Fact] public void EndToEndTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='m' type='Memory'> <layout type='CSVLayout'> <column name='level' layout='${level}' /> <column name='message' layout='${message}' /> <column name='counter' layout='${counter}' /> <delimiter>Comma</delimiter> </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='m' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); logger.Info("msg2"); logger.Warn("Message with, a comma"); var target = logFactory.Configuration.FindTargetByName<NLog.Targets.MemoryTarget>("m"); Assert.NotNull(target); Assert.Equal(4, target.Logs.Count); Assert.Equal("level,message,counter", target.Logs[0]); Assert.Equal("Debug,msg,1", target.Logs[1]); Assert.Equal("Info,msg2,2", target.Logs[2]); Assert.Equal("Warn,\"Message with, a comma\",3", target.Logs[3]); } /// <summary> /// Custom header overwrites file headers /// /// Note: maybe changed with an option in the future /// </summary> [Fact] public void CustomHeaderTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='m' type='Memory'> <layout type='CSVLayout'> <header>headertest</header> <column name='level' layout='${level}' quoting='Nothing' /> <column name='message' layout='${message}' /> <column name='counter' layout='${counter}' /> <delimiter>Comma</delimiter> </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='m' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); logger.Info("msg2"); logger.Warn("Message with, a comma"); var target = logFactory.Configuration.FindTargetByName<NLog.Targets.MemoryTarget>("m"); Assert.NotNull(target); Assert.Equal(4, target.Logs.Count); Assert.Equal("headertest", target.Logs[0]); Assert.Equal("Debug,msg,1", target.Logs[1]); Assert.Equal("Info,msg2,2", target.Logs[2]); Assert.Equal("Warn,\"Message with, a comma\",3", target.Logs[3]); } [Fact] public void NoHeadersTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='m' type='Memory'> <layout type='CSVLayout' withHeader='false'> <delimiter>Comma</delimiter> <column name='level' layout='${level}' /> <column name='message' layout='${message}' /> <column name='counter' layout='${counter}' /> </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='m' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); logger.Info("msg2"); logger.Warn("Message with, a comma"); var target = logFactory.Configuration.FindTargetByName<NLog.Targets.MemoryTarget>("m"); Assert.NotNull(target); Assert.Equal(3, target.Logs.Count); Assert.Equal("Debug,msg,1", target.Logs[0]); Assert.Equal("Info,msg2,2", target.Logs[1]); Assert.Equal("Warn,\"Message with, a comma\",3", target.Logs[2]); } [Fact] public void CsvLayoutRenderingNoQuoting() { var delimiters = new Dictionary<CsvColumnDelimiterMode, string> { { CsvColumnDelimiterMode.Auto, CultureInfo.CurrentCulture.TextInfo.ListSeparator }, { CsvColumnDelimiterMode.Comma, "," }, { CsvColumnDelimiterMode.Semicolon, ";" }, { CsvColumnDelimiterMode.Space, " " }, { CsvColumnDelimiterMode.Tab, "\t" }, { CsvColumnDelimiterMode.Pipe, "|" }, { CsvColumnDelimiterMode.Custom, "zzz" }, }; foreach (var delim in delimiters) { var csvLayout = new CsvLayout() { Quoting = CsvQuotingMode.Nothing, Columns = { new CsvColumn("date", "${longdate}"), new CsvColumn("level", "${level}"), new CsvColumn("message;text", "${message}"), }, Delimiter = delim.Key, CustomColumnDelimiter = "zzz", }; var ev = new LogEventInfo(); ev.TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56); ev.Level = LogLevel.Info; ev.Message = string.Concat(csvLayout.QuoteChar, "hello, world", csvLayout.QuoteChar); string sep = delim.Value; Assert.Equal("2010-01-01 12:34:56.0000" + sep + "Info" + sep + "\"hello, world\"", csvLayout.Render(ev)); Assert.Equal("date" + sep + "level" + sep + "message;text", csvLayout.Header.Render(ev)); } } [Fact] public void CsvLayoutRenderingFullQuoting() { var delimiters = new Dictionary<CsvColumnDelimiterMode, string> { { CsvColumnDelimiterMode.Auto, CultureInfo.CurrentCulture.TextInfo.ListSeparator }, { CsvColumnDelimiterMode.Comma, "," }, { CsvColumnDelimiterMode.Semicolon, ";" }, { CsvColumnDelimiterMode.Space, " " }, { CsvColumnDelimiterMode.Tab, "\t" }, { CsvColumnDelimiterMode.Pipe, "|" }, { CsvColumnDelimiterMode.Custom, "zzz" }, }; foreach (var delim in delimiters) { var csvLayout = new CsvLayout() { Quoting = CsvQuotingMode.All, Columns = { new CsvColumn("date", "${longdate}"), new CsvColumn("level", "${level}"), new CsvColumn("message;text", "${message}"), }, QuoteChar = "'", Delimiter = delim.Key, CustomColumnDelimiter = "zzz", }; var ev = new LogEventInfo(); ev.TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56); ev.Level = LogLevel.Info; ev.Message = string.Concat(csvLayout.QuoteChar, "hello, world", csvLayout.QuoteChar); string sep = delim.Value; Assert.Equal("'2010-01-01 12:34:56.0000'" + sep + "'Info'" + sep + "'''hello, world'''", csvLayout.Render(ev)); Assert.Equal("'date'" + sep + "'level'" + sep + "'message;text'", csvLayout.Header.Render(ev)); } } [Fact] public void CsvLayoutRenderingAutoQuoting() { var csvLayout = new CsvLayout() { Quoting = CsvQuotingMode.Auto, Columns = { new CsvColumn("date", "${longdate}"), new CsvColumn("level", "${level}"), new CsvColumn("message;text", "${message}"), }, QuoteChar = "'", Delimiter = CsvColumnDelimiterMode.Semicolon, }; // no quoting Assert.Equal( "2010-01-01 12:34:56.0000;Info;hello, world", csvLayout.Render(new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" })); // multi-line string - requires quoting Assert.Equal( "2010-01-01 12:34:56.0000;Info;'hello\rworld'", csvLayout.Render(new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello\rworld" })); // multi-line string - requires quoting Assert.Equal( "2010-01-01 12:34:56.0000;Info;'hello\nworld'", csvLayout.Render(new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello\nworld" })); // quote character used in string, will be quoted and doubled Assert.Equal( "2010-01-01 12:34:56.0000;Info;'hello''world'", csvLayout.Render(new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello'world" })); Assert.Equal("date;level;'message;text'", csvLayout.Header.Render(LogEventInfo.CreateNullEvent())); } [Fact] public void CsvLayoutCachingTest() { var csvLayout = new CsvLayout() { Quoting = CsvQuotingMode.Auto, Columns = { new CsvColumn("date", "${longdate}"), new CsvColumn("level", "${level}"), new CsvColumn("message", "${message}"), new CsvColumn("threadid", "${threadid}"), }, QuoteChar = "'", Delimiter = CsvColumnDelimiterMode.Semicolon, }; var e1 = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" }; var e2 = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 57), Level = LogLevel.Info, Message = "hello, world" }; var r11 = csvLayout.Render(e1); var r12 = csvLayout.Render(e1); var r21 = csvLayout.Render(e2); var r22 = csvLayout.Render(e2); var h11 = csvLayout.Header.Render(e1); var h12 = csvLayout.Header.Render(e1); var h21 = csvLayout.Header.Render(e2); var h22 = csvLayout.Header.Render(e2); Assert.Same(r11, r12); Assert.Same(r21, r22); Assert.NotSame(r11, r21); Assert.NotSame(r12, r22); Assert.Equal(h11, h21); Assert.Same(h11, h12); Assert.Same(h21, h22); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using System; using System.Collections.Generic; using System.Text; using NLog.Common; /// <summary> /// A base class for targets which wrap other (multiple) targets /// and provide various forms of target routing. /// </summary> public abstract class CompoundTargetBase : Target { /// <summary> /// Initializes a new instance of the <see cref="CompoundTargetBase" /> class. /// </summary> /// <param name="targets">The targets.</param> protected CompoundTargetBase(params Target[] targets) { Targets = new List<Target>(targets); } /// <summary> /// Gets the collection of targets managed by this compound target. /// </summary> public IList<Target> Targets { get; } /// <inheritdoc/> public override string ToString() { return _tostring ?? (_tostring = GenerateTargetToString()); } private string GenerateTargetToString() { if (string.IsNullOrEmpty(Name) && Targets?.Count > 0) { string separator = string.Empty; var sb = new StringBuilder(); sb.Append(GenerateTargetToString(true)); sb.Append('['); foreach (var t in Targets) { sb.Append(separator); sb.Append(t.ToString()); separator = ", "; } sb.Append(']'); return sb.ToString(); } return GenerateTargetToString(true); } /// <inheritdoc/> protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException("This target must not be invoked in a synchronous way."); } /// <summary> /// Flush any pending log messages for all wrapped targets. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { AsyncHelpers.ForEachItemInParallel(Targets, asyncContinuation, (t, c) => t.Flush(c)); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Config; using NLog.Targets; namespace NLog.UnitTests.Layouts { using NLog.Layouts; using System; using Xunit; public class CompoundLayoutTests : NLogTestBase { [Fact] public void CodeCompoundLayoutIsRenderedCorrectly() { var compoundLayout = new CompoundLayout { Layouts = { new SimpleLayout("Long date - ${longdate}"), new SimpleLayout("|Before| "), new JsonLayout { Attributes = { new JsonAttribute("short_date", "${shortdate}"), new JsonAttribute("message", "${message}"), } }, new SimpleLayout(" |After|"), new SimpleLayout("Last - ${level}") } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 20, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" }; const string expected = "Long date - 2010-01-20 12:34:56.0000|Before| { \"short_date\": \"2010-01-20\", \"message\": \"hello, world\" } |After|Last - Info"; var actual = compoundLayout.Render(logEventInfo); Assert.Equal(expected, actual); } [Fact] public void XmlCompoundLayoutWithVariables() { const string configXml = @" <nlog> <variable name='jsonLayoutv0.1'> <layout type='JsonLayout'> <attribute name='short_date' layout='${shortdate}' /> <attribute name='message' layout='${message}' /> </layout> </variable> <variable name='compoundLayoutv0.1'> <layout type='CompoundLayout'> <layout type='SimpleLayout' text='|Before| ' /> <layout type='${jsonLayoutv0.1}' /> <layout type='SimpleLayout' text=' |After|' /> </layout> </variable> <targets> <target name='compoundFile1' type='File' fileName='log.txt'> <layout type='CompoundLayout'> <layout type='SimpleLayout' text='|Before| ' /> <layout type='${jsonLayoutv0.1}' /> <layout type='SimpleLayout' text=' |After|' /> </layout> </target> <target name='compoundFile2' type='file' fileName='other.txt'> <layout type='${compoundLayoutv0.1}' /> </target> </targets> <rules> </rules> </nlog> "; var config = XmlLoggingConfiguration.CreateFromXmlString(configXml); Assert.NotNull(config); var target = config.FindTargetByName<FileTarget>("compoundFile1"); Assert.NotNull(target); var compoundLayout = target.Layout as CompoundLayout; Assert.NotNull(compoundLayout); var layouts = compoundLayout.Layouts; Assert.Equal(3, layouts.Count); Assert.Equal(typeof(SimpleLayout), layouts[0].GetType()); Assert.Equal(typeof(JsonLayout), layouts[1].GetType()); Assert.Equal(typeof(SimpleLayout), layouts[2].GetType()); var innerJsonLayout = (JsonLayout)layouts[1]; Assert.Equal(typeof(JsonLayout), innerJsonLayout.GetType()); Assert.Equal(2, innerJsonLayout.Attributes.Count); Assert.Equal("${shortdate}", innerJsonLayout.Attributes[0].Layout.ToString()); Assert.Equal("${message}", innerJsonLayout.Attributes[1].Layout.ToString()); target = config.FindTargetByName<FileTarget>("compoundFile2"); Assert.NotNull(target); compoundLayout = target.Layout as CompoundLayout; Assert.NotNull(compoundLayout); layouts = compoundLayout.Layouts; Assert.Equal(3, layouts.Count); Assert.Equal(typeof(SimpleLayout), layouts[0].GetType()); Assert.Equal(typeof(JsonLayout), layouts[1].GetType()); Assert.Equal(typeof(SimpleLayout), layouts[2].GetType()); innerJsonLayout = (JsonLayout)layouts[1]; Assert.Equal(typeof(JsonLayout), innerJsonLayout.GetType()); Assert.Equal(2, innerJsonLayout.Attributes.Count); Assert.Equal("${shortdate}", innerJsonLayout.Attributes[0].Layout.ToString()); Assert.Equal("${message}", innerJsonLayout.Attributes[1].Layout.ToString()); } [Fact] public void XmlCompoundLayoutIsRenderedCorrectly() { const string configXml = @" <nlog> <targets> <target name='compoundFile' type='File' fileName='log.txt'> <layout type='CompoundLayout'> <layout type='SimpleLayout' text='Long date - ${longdate}' /> <layout type='SimpleLayout' text='|Before| ' /> <layout type='JsonLayout'> <attribute name='short_date' layout='${shortdate}' /> <attribute name='message' layout='${message}' /> </layout> <layout type='SimpleLayout' text=' |After|' /> <layout type='SimpleLayout' text='Last - ${level}' /> </layout> </target> </targets> <rules> </rules> </nlog> "; var config = XmlLoggingConfiguration.CreateFromXmlString(configXml); Assert.NotNull(config); var target = config.FindTargetByName<FileTarget>("compoundFile"); Assert.NotNull(target); var compoundLayout = target.Layout as CompoundLayout; Assert.NotNull(compoundLayout); var layouts = compoundLayout.Layouts; Assert.NotNull(layouts); Assert.Equal(5, layouts.Count); Assert.Equal(typeof(SimpleLayout), layouts[0].GetType()); Assert.Equal(typeof(SimpleLayout), layouts[1].GetType()); var innerJsonLayout = (JsonLayout)layouts[2]; Assert.Equal(typeof(JsonLayout), innerJsonLayout.GetType()); Assert.Equal(2, innerJsonLayout.Attributes.Count); Assert.Equal("${shortdate}", innerJsonLayout.Attributes[0].Layout.ToString()); Assert.Equal("${message}", innerJsonLayout.Attributes[1].Layout.ToString()); Assert.Equal(typeof(SimpleLayout), layouts[3].GetType()); Assert.Equal(typeof(SimpleLayout), layouts[4].GetType()); var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 20, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" }; const string expected = "Long date - 2010-01-20 12:34:56.0000|Before| { \"short_date\": \"2010-01-20\", \"message\": \"hello, world\" } |After|Last - Info"; var actual = compoundLayout.Render(logEventInfo); Assert.Equal(expected, actual); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.Linq; using System.Xml; using NLog.Internal; /// <summary> /// Represents simple XML element with case-insensitive attribute semantics. /// </summary> internal class NLogXmlElement : ILoggingConfigurationElement { /// <summary> /// Initializes a new instance of the <see cref="NLogXmlElement"/> class. /// </summary> /// <param name="reader">The reader to initialize element from.</param> public NLogXmlElement(XmlReader reader) : this(reader, false) { } public NLogXmlElement(XmlReader reader, bool nestedElement) { Parse(reader, nestedElement, out var attributes, out var children); AttributeValues = attributes ?? ArrayHelper.Empty<KeyValuePair<string, string>>(); Children = children ?? ArrayHelper.Empty<NLogXmlElement>(); } /// <summary> /// Gets the element name. /// </summary> public string LocalName { get; private set; } /// <summary> /// Gets the dictionary of attribute values. /// </summary> public IList<KeyValuePair<string,string>> AttributeValues { get; } /// <summary> /// Gets the collection of child elements. /// </summary> public IList<NLogXmlElement> Children { get; } /// <summary> /// Gets the value of the element. /// </summary> public string Value { get; private set; } public string Name => LocalName; public IEnumerable<KeyValuePair<string, string>> Values { get { for (int i = 0; i < Children.Count; ++i) { var child = Children[i]; if (SingleValueElement(child)) { // Values assigned using nested node-elements. Maybe in combination with attributes return AttributeValues.Concat(Children.Where(item => SingleValueElement(item)).Select(item => new KeyValuePair<string, string>(item.Name, item.Value))); } } return AttributeValues; } } private static bool SingleValueElement(NLogXmlElement child) { // Node-element that works like an attribute return child.Children.Count == 0 && child.AttributeValues.Count == 0 && child.Value != null; } IEnumerable<ILoggingConfigurationElement> ILoggingConfigurationElement.Children { get { for (int i = 0; i < Children.Count; ++i) { var child = Children[i]; if (!SingleValueElement(child)) return Children.Where(item => !SingleValueElement(item)).Cast<ILoggingConfigurationElement>(); } return ArrayHelper.Empty<ILoggingConfigurationElement>(); } } /// <summary> /// Returns children elements with the specified element name. /// </summary> /// <param name="elementName">Name of the element.</param> /// <returns>Children elements with the specified element name.</returns> public List<NLogXmlElement> FilterChildren(string elementName) { var result = new List<NLogXmlElement>(); foreach (var ch in Children) { if (ch.LocalName.Equals(elementName, StringComparison.OrdinalIgnoreCase)) { result.Add(ch); } } return result; } /// <summary> /// Asserts that the name of the element is among specified element names. /// </summary> /// <param name="allowedNames">The allowed names.</param> public void AssertName(params string[] allowedNames) { foreach (var en in allowedNames) { if (LocalName.Equals(en, StringComparison.OrdinalIgnoreCase)) { return; } } throw new InvalidOperationException($"Assertion failed. Expected element name '{string.Join("|", allowedNames)}', actual: '{LocalName}'."); } private void Parse(XmlReader reader, bool nestedElement, out IList<KeyValuePair<string,string>> attributes, out IList<NLogXmlElement> children) { ParseAttributes(reader, nestedElement, out attributes); LocalName = reader.LocalName; children = null; if (!reader.IsEmptyElement) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.EndElement) { break; } if (reader.NodeType == XmlNodeType.CDATA || reader.NodeType == XmlNodeType.Text) { Value += reader.Value; continue; } if (reader.NodeType == XmlNodeType.Element) { children = children ?? new List<NLogXmlElement>(); var nestedChild = nestedElement || !string.Equals(reader.LocalName, "nlog", StringComparison.OrdinalIgnoreCase); children.Add(new NLogXmlElement(reader, nestedChild)); } } } } private void ParseAttributes(XmlReader reader, bool nestedElement, out IList<KeyValuePair<string, string>> attributes) { attributes = null; if (reader.MoveToFirstAttribute()) { do { if (!nestedElement && IsSpecialXmlAttribute(reader)) { continue; } attributes = attributes ?? new List<KeyValuePair<string, string>>(); attributes.Add(new KeyValuePair<string, string>(reader.LocalName, reader.Value)); } while (reader.MoveToNextAttribute()); reader.MoveToElement(); } } /// <summary> /// Special attribute we could ignore /// </summary> private static bool IsSpecialXmlAttribute(XmlReader reader) { if (reader.LocalName?.Equals("xmlns", StringComparison.OrdinalIgnoreCase) == true) return true; if (reader.LocalName?.Equals("schemaLocation", StringComparison.OrdinalIgnoreCase) == true && !StringHelpers.IsNullOrWhiteSpace(reader.Prefix)) return true; if (reader.Prefix?.Equals("xsi", StringComparison.OrdinalIgnoreCase) == true) return true; if (reader.Prefix?.Equals("xmlns", StringComparison.OrdinalIgnoreCase) == true) return true; return false; } public override string ToString() { return Name; } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Config; using System; using System.Globalization; using Xunit; namespace NLog.UnitTests.Config { public class PropertyTypeConverterTests { private readonly PropertyTypeConverter _sut; public PropertyTypeConverterTests() { _sut = new PropertyTypeConverter(); } [Fact] public void Convert_IntToNullableIntTest() { // Act var result = _sut.Convert(123, typeof(int?), null, null); // Assert // int is correct here, see https://stackoverflow.com/questions/785358/nullable-type-is-not-a-nullable-type var resultTyped = Assert.IsType<int>(result); Assert.Equal(123, resultTyped); } [Fact] public void Convert_NullableIntToIntTest() { // Act var result = _sut.Convert((int?)123, typeof(int), null, null); // Assert // int is correct here, see https://stackoverflow.com/questions/785358/nullable-type-is-not-a-nullable-type var resultTyped = Assert.IsType<int>(result); Assert.Equal(123, resultTyped); } [Theory] [InlineData(null)] [InlineData("")] [InlineData(" ")] public void Convert_EmptyStringToNullableIntTest(string value) { // Act var result = _sut.Convert(value, typeof(int?), null, null); // Assert Assert.Null(result); } [Fact] public void Convert_StringToIntTest() { // Act var result = _sut.Convert("123", typeof(int), null, null); // Assert var resultTyped = Assert.IsType<int>(result); Assert.Equal(123, resultTyped); } [Fact] public void Convert_StringToNullableIntTest() { // Act var result = _sut.Convert("123", typeof(int?), null, null); // Assert // int is correct here, see https://stackoverflow.com/questions/785358/nullable-type-is-not-a-nullable-type var resultTyped = Assert.IsType<int>(result); Assert.Equal(123, resultTyped); } [Theory] [InlineData(typeof(DateTimeOffset?))] [InlineData(typeof(DateTime?))] [InlineData(typeof(Guid?))] [InlineData(typeof(TimeSpan?))] public void Convert_EmptyStringToNullableTypeTest(Type type) { // Act var result = _sut.Convert("", type, null, null); // Assert Assert.Null(result); } [Fact] public void Convert_StringToDecimalTest() { // Act var result = _sut.Convert("123.2", typeof(decimal), null, CultureInfo.InvariantCulture); // Assert var resultTyped = Assert.IsType<decimal>(result); Assert.Equal(123.2M, resultTyped); } [Fact] public void Convert_StringToDecimalWithCultureTest() { // Act var result = _sut.Convert("123,2", typeof(decimal), null, new CultureInfo("NL-nl")); // Assert var resultTyped = Assert.IsType<decimal>(result); Assert.Equal(123.2M, resultTyped); } [Fact] public void Convert_StringToNullableDecimalTest() { // Act var result = _sut.Convert("123.2", typeof(decimal?), null, CultureInfo.InvariantCulture); // Assert // decimal is correct here, see https://stackoverflow.com/questions/785358/nullable-type-is-not-a-nullable-type var resultTyped = Assert.IsType<decimal>(result); Assert.Equal(123.2M, resultTyped); } [Fact] public void Convert_StringToDoubleTest() { // Act var result = _sut.Convert("123.2", typeof(double), null, CultureInfo.InvariantCulture); // Assert var resultTyped = Assert.IsType<double>(result); Assert.Equal(123.2, resultTyped); } [Fact] public void Convert_StringToDoubleWithCultureTest() { // Act var result = _sut.Convert("123,2", typeof(double), null, new CultureInfo("NL-nl")); // Assert var resultTyped = Assert.IsType<double>(result); Assert.Equal(123.2, resultTyped); } [Fact] public void Convert_StringToNullableDoubleTest() { // Act var result = _sut.Convert("123.2", typeof(double?), null, CultureInfo.InvariantCulture); // Assert // double is correct here, see https://stackoverflow.com/questions/785358/nullable-type-is-not-a-nullable-type var resultTyped = Assert.IsType<double>(result); Assert.Equal(123.2, resultTyped); } [Fact] public void Convert_StringToShortTest() { // Act var result = _sut.Convert("123", typeof(short), null, CultureInfo.InvariantCulture); // Assert var resultTyped = Assert.IsType<short>(result); Assert.Equal(123, resultTyped); } [Fact] public void Convert_StringToNullableShortTest() { // Act var result = _sut.Convert("123", typeof(short), null, CultureInfo.InvariantCulture); // Assert // short is correct here, see https://stackoverflow.com/questions/785358/nullable-type-is-not-a-nullable-type var resultTyped = Assert.IsType<short>(result); Assert.Equal(123, resultTyped); } [Fact] public void Convert_FormattableToStringTest() { // Act var result = _sut.Convert(123, typeof(string), "D4", null); // Assert var resultTyped = Assert.IsType<string>(result); Assert.Equal("0123", resultTyped); } [Fact] public void Convert_NullableFormattableToStringTest() { // Arrange int? nullableInt = 123; // Act var result = _sut.Convert(nullableInt, typeof(string), "D4", null); // Assert var resultTyped = Assert.IsType<string>(result); Assert.Equal("0123", resultTyped); } [Fact] public void Convert_StringToDatetimeWithFormat() { // Arrange // Act var result = _sut.Convert("2019", typeof(DateTime), "yyyy", null); // Assert var resultTyped = Assert.IsType<DateTime>(result); Assert.Equal(new DateTime(2019, 1, 1), resultTyped); } [Fact] public void Convert_StringToNullableDatetimeWithFormat() { // Arrange // Act var result = _sut.Convert("2019", typeof(DateTime?), "yyyy", null); // Assert // datetime is correct here, see https://stackoverflow.com/questions/785358/nullable-type-is-not-a-nullable-type var resultTyped = Assert.IsType<DateTime>(result); Assert.Equal(new DateTime(2019, 1, 1), resultTyped); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.IO; using System.Linq; using System.Text; using NLog.Common; namespace NLog.Internal { /// <summary> /// Stream helpers /// </summary> internal static class StreamHelpers { /// <summary> /// Copy to output stream and skip BOM if encoding is UTF8 /// </summary> /// <param name="input"></param> /// <param name="output"></param> /// <param name="encoding"></param> public static void CopyAndSkipBom(this Stream input, Stream output, Encoding encoding) { var bomSize = EncodingHelpers.Utf8BOM.Length; var bomBuffer = new byte[bomSize]; var posBefore = input.Position; int bytesRead = input.Read(bomBuffer, 0, bomSize); //TODO support other BOMs, like UTF16 if (bytesRead == bomSize && bomBuffer.SequenceEqual(EncodingHelpers.Utf8BOM)) { InternalLogger.Debug("input has UTF8 BOM"); //already skipped due to read } else { InternalLogger.Debug("input hasn't a UTF8 BOM"); //reset position input.Position = posBefore; } Copy(input, output); } /// <summary> /// Copy stream input to output. Skip the first bytes /// </summary> /// <param name="input">stream to read from</param> /// <param name="output">stream to write to</param> /// <remarks>.net35 doesn't have a .copyto</remarks> public static void Copy(this Stream input, Stream output) { CopyWithOffset(input, output, 0); } /// <summary> /// Copy stream input to output. Skip the first bytes /// </summary> /// <param name="input">stream to read from</param> /// <param name="output">stream to write to</param> /// <param name="offset">first bytes to skip (optional)</param> public static void CopyWithOffset(this Stream input, Stream output, int offset) { if (offset < 0) { throw new ArgumentException("cannot be negative", nameof(offset)); } if (offset > 0) { //skip offset input.Seek(offset, SeekOrigin.Current); } byte[] buffer = new byte[4096]; int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, read); } } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.WindowsRegistry.Tests { using System; using Microsoft.Win32; using Xunit; #if NETSTANDARD [System.Runtime.Versioning.SupportedOSPlatform("windows")] #endif public sealed class RegistryTests : IDisposable { private const string TestKey = @"Software\NLogTest"; public RegistryTests() { LogManager.ThrowExceptions = true; var key = Registry.CurrentUser.CreateSubKey(TestKey); key.SetValue("Foo", "FooValue"); key.SetValue(null, "UnnamedValue"); //different keys because in 32bit the 64bits uses the 32 RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32).CreateSubKey("Software\\NLogTest").SetValue("view32", "reg32"); RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64).CreateSubKey("Software\\NLogTest").SetValue("view64", "reg64"); } public void Dispose() { //different keys because in 32bit the 64bits uses the 32 try { RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32).DeleteSubKey("Software\\NLogTest"); } catch (Exception) { } try { RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64).DeleteSubKey("Software\\NLogTest"); } catch (Exception) { } try { Registry.CurrentUser.DeleteSubKey(TestKey); } catch (Exception) { } } [Fact] public void RegistryNamedValueTest() { AssertLayoutRendererResult("FooValue", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=Foo}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } #if !NET35 [Fact] public void RegistryNamedValueTest_hive32() { AssertLayoutRendererResult("reg32", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=view32:view=Registry32}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } [Fact] public void RegistryNamedValueTest_hive64() { AssertLayoutRendererResult("reg64", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=view64:view=Registry64}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } #endif [Fact] public void RegistryNamedValueTest_forward_slash() { AssertLayoutRendererResult("FooValue", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NLogTest:value=Foo}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } [Fact] public void RegistryUnnamedValueTest() { AssertLayoutRendererResult("UnnamedValue", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } [Fact] public void RegistryUnnamedValueTest_forward_slash() { AssertLayoutRendererResult("UnnamedValue", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NLogTest}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } [Fact] public void RegistryKeyNotFoundTest() { AssertLayoutRendererResult("xyz", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NoSuchKey:defaultValue=xyz}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } [Fact] public void RegistryKeyNotFoundTest_forward_slash() { AssertLayoutRendererResult("xyz", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NoSuchKey:defaultValue=xyz}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } [Fact] public void RegistryValueNotFoundTest() { AssertLayoutRendererResult("xyz", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=NoSuchValue:defaultValue=xyz}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } [Fact] public void RegistryDefaultValueTest() { AssertLayoutRendererResult("logdefaultvalue", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=logdefaultvalue}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } [Fact] public void RegistryDefaultValueTest_with_colon() { AssertLayoutRendererResult("C:temp", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\:temp}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } [Fact] public void RegistryDefaultValueTest_with_slash() { AssertLayoutRendererResult("C/temp", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C/temp}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } [Fact] public void RegistryDefaultValueTest_with_foward_slash() { AssertLayoutRendererResult("C\\temp", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\\temp}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } [Fact] public void RegistryDefaultValueTest_with_foward_slash2() { AssertLayoutRendererResult("C\\temp", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\temp:requireEscapingSlashesInDefaultValue=false}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } [Fact] public void Registry_nosubky() { AssertLayoutRendererResult("", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKEY_CURRENT_CONFIG}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } [Fact] public void RegistryDefaultValueNull() { AssertLayoutRendererResult("", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } [Fact] public void RegistryTestWrongKey_no_ex() { try { LogManager.ThrowExceptions = false; AssertLayoutRendererResult("", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:value=NOT_EXISTENT:key=garabageHKLM/NOT_EXISTENT:defaultValue=empty}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } finally { LogManager.ThrowExceptions = true; } } [Fact] public void RegistryTestWrongKey_ex() { try { LogManager.ThrowExceptions = false; AssertLayoutRendererResult("", @"<nlog> <targets><target name='debug' type='Debug' layout='${registry:value=NOT_EXISTENT:key=garabageHKLM/NOT_EXISTENT:defaultValue=empty}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } finally { LogManager.ThrowExceptions = true; } } private static void AssertLayoutRendererResult(string expectedOuput, string xmlConfig) { var logFactory = new LogFactory().Setup().SetupExtensions(ext => ext.RegisterLayoutRenderer<NLog.LayoutRenderers.RegistryLayoutRenderer>("registry")). LoadConfigurationFromXml(xmlConfig).LogFactory; var debugTarget = logFactory.Configuration.FindTargetByName<NLog.Targets.DebugTarget>("debug"); logFactory.GetCurrentClassLogger().Debug("zzz"); Assert.Equal(expectedOuput, debugTarget.LastMessage); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Internal { using NLog.Internal; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; #if DEBUG public class SimpleStringReaderTests : NLogTestBase { [Theory] [InlineData("", 0, "", char.MaxValue, "" )] [InlineData("abcdef", 0, "", 'a', "bcdef")] [InlineData("abcdef", 2, "ab", 'c', "def")] [InlineData("abcdef", 6, "abcdef", char.MaxValue, "")] [InlineData("abcdef", 7, "INVALID_CURRENT_STATE", char.MaxValue, "INVALID_CURRENT_STATE")] /// <summary> /// https://github.com/NLog/NLog/issues/3194 /// </summary> public void DebugView_CurrentState(string input, int position, string expectedDone, char expectedCurrent, string expectedTodo) { var reader = new SimpleStringReader(input); reader.Position = position; Assert.Equal( SimpleStringReader.BuildCurrentState(expectedDone, expectedCurrent, expectedTodo), reader.CurrentState); } [Fact] public void DebugView_CurrentState_NegativePosition() { Assert.Throws<IndexOutOfRangeException>(() => new SimpleStringReader("abcdef") { Position = -1, }.CurrentState); } } #endif } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; internal static class FormatHelper { /// <summary> /// Convert object to string /// </summary> /// <param name="o">value</param> /// <param name="formatProvider">format for conversion.</param> /// <returns></returns> /// <remarks> /// If <paramref name="formatProvider"/> is <c>null</c> and <paramref name="o"/> isn't a <see cref="string"/> already, then the <see cref="LogFactory"/> will get a locked by <see cref="LogManager.Configuration"/> /// </remarks> internal static string ConvertToString(object o, IFormatProvider formatProvider) { // if no IFormatProvider is specified, use the Configuration.DefaultCultureInfo value. if (formatProvider is null) { if (SkipFormattableToString(o)) return o?.ToString() ?? string.Empty; if (o is IFormattable) { formatProvider = LogManager.LogFactory.DefaultCultureInfo; } } return Convert.ToString(o, formatProvider); } private static bool SkipFormattableToString(object value) { switch (Convert.GetTypeCode(value)) { case TypeCode.String: return true; case TypeCode.Empty: return true; default: return false; } } internal static string TryFormatToString(object value, string format, IFormatProvider formatProvider) { if (SkipFormattableToString(value)) return value?.ToString() ?? string.Empty; if (value is IFormattable formattable) { return formattable.ToString(format, formatProvider); } else if (value is System.Collections.IEnumerable) { return null; } else { return value?.ToString() ?? string.Empty; } } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests { using System; using System.IO; using System.Threading; using NLog.Config; using Xunit; public class LogFactoryTests : NLogTestBase { [Fact] public void Flush_DoNotThrowExceptionsAndTimeout_DoesNotThrow() { // Arrange var logFactory = new LogFactory().Setup().LoadConfigurationFromXml($@" <nlog throwExceptions='false'> <targets> <target type='BufferingWrapper' name='test'> <target type='MethodCall' name='test_wrapped' methodName='{nameof(TestClass.GenerateTimeout)}' className='{typeof(TestClass).AssemblyQualifiedName}' /> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeto='test'></logger> </rules> </nlog>").LogFactory; Logger logger = logFactory.GetCurrentClassLogger(); logger.Info("Prepare Timeout"); Exception timeoutException = null; ManualResetEvent manualResetEvent = new ManualResetEvent(false); // Act logger.Factory.Flush(TimeSpan.FromMilliseconds(1)); logger.Factory.Flush(ex => { timeoutException = ex; manualResetEvent.Set(); }, TimeSpan.FromMilliseconds(1)); // Assert Assert.True(manualResetEvent.WaitOne(5000)); Assert.NotNull(timeoutException); } [Fact] public void InvalidXMLConfiguration_DoesNotThrowErrorWhen_ThrowExceptionFlagIsNotSet() { using (new NoThrowNLogExceptions()) { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog internalLogIncludeTimestamp='IamNotBooleanValue'> <targets><target type='Debug' name='test' /></targets> <rules> <logger name='*' minlevel='Debug' writeto='test'></logger> </rules> </nlog>").LogFactory; Assert.NotNull(logFactory.Configuration); } } [Fact] public void InvalidXMLConfiguration_ThrowErrorWhen_ThrowExceptionFlagIsSet() { Boolean ExceptionThrown = false; try { new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog internalLogIncludeTimestamp='IamNotBooleanValue'> <targets><target type='Debug' name='test' /></targets> <rules> <logger name='*' minlevel='Debug' writeto='test'></logger> </rules> </nlog>"); } catch (Exception) { ExceptionThrown = true; } Assert.True(ExceptionThrown); } [Fact] [Obsolete("Replaced by LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] public void Configuration_InaccessibleNLog_doesNotThrowException() { string tempDirectory = null; try { // Arrange var logFactory = CreateEmptyNLogFile(out tempDirectory, out var configFile); using (OpenStream(configFile)) { // Act var loggingConfig = logFactory.Configuration; // Assert Assert.Null(loggingConfig); } // Assert Assert.NotNull(logFactory.Configuration); } finally { if (tempDirectory != null && Directory.Exists(tempDirectory)) Directory.Delete(tempDirectory, true); } } [Fact] [Obsolete("Replaced by LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] public void LoadConfiguration_InaccessibleNLog_throwException() { string tempDirectory = null; try { // Arrange var logFactory = CreateEmptyNLogFile(out tempDirectory, out var configFile); using (OpenStream(configFile)) { // Act var ex = Record.Exception(() => logFactory.LoadConfiguration(configFile)); // Assert Assert.IsType<FileNotFoundException>(ex); } // Assert Assert.NotNull(logFactory.LoadConfiguration(configFile).Configuration); } finally { if (tempDirectory != null && Directory.Exists(tempDirectory)) Directory.Delete(tempDirectory, true); } } private static FileStream OpenStream(string configFile) { return new FileStream(configFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None); } [Obsolete("Replaced by LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] private static LogFactory CreateEmptyNLogFile(out string tempDirectory, out string filePath) { tempDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); filePath = Path.Combine(tempDirectory, "NLog.config"); Directory.CreateDirectory(tempDirectory); File.WriteAllText(filePath, "<nlog />"); LogFactory logFactory = new LogFactory(); logFactory.SetCandidateConfigFilePaths(new[] { filePath }); return logFactory; } [Fact] public void SecondaryLogFactoryDoesNotTakePrimaryLogFactoryLock() { File.WriteAllText("NLog.config", "<nlog />"); try { bool threadTerminated; var primaryLogFactory = LogManager.factory; var primaryLogFactoryLock = primaryLogFactory._syncRoot; // Simulate a potential deadlock. // If the creation of the new LogFactory takes the lock of the global LogFactory, the thread will deadlock. lock (primaryLogFactoryLock) { var thread = new Thread(() => { (new LogFactory()).GetCurrentClassLogger(); }); thread.Start(); threadTerminated = thread.Join(TimeSpan.FromSeconds(1)); } Assert.True(threadTerminated); } finally { try { File.Delete("NLog.config"); } catch { } } } [Fact] public void ReloadConfigOnTimer_DoesNotThrowConfigException_IfConfigChangedInBetween() { EventHandler<LoggingConfigurationChangedEventArgs> testChanged = null; try { LogManager.Configuration = null; var loggingConfiguration = new LoggingConfiguration(); LogManager.Configuration = loggingConfiguration; var configLoader = new LoggingConfigurationWatchableFileLoader(LogFactory.DefaultAppEnvironment); var logFactory = new LogFactory(configLoader); logFactory.Configuration = loggingConfiguration; var differentConfiguration = new LoggingConfiguration(); // Verify that the random configuration change is ignored (Only the final reset is reacted upon) bool called = false; LoggingConfiguration oldConfiguration = null, newConfiguration = null; testChanged = (s, e) => { called = true; oldConfiguration = e.DeactivatedConfiguration; newConfiguration = e.ActivatedConfiguration; }; LogManager.LogFactory.ConfigurationChanged += testChanged; var exRecorded = Record.Exception(() => configLoader.ReloadConfigOnTimer(differentConfiguration)); Assert.Null(exRecorded); // Final reset clears the configuration, so it is changed to null LogManager.Configuration = null; Assert.True(called); Assert.Equal(loggingConfiguration, oldConfiguration); Assert.Null(newConfiguration); } finally { if (testChanged != null) LogManager.LogFactory.ConfigurationChanged -= testChanged; } } private class ReloadNullConfiguration : LoggingConfiguration { public override LoggingConfiguration Reload() { return null; } } [Fact] public void ReloadConfigOnTimer_DoesNotThrowConfigException_IfConfigReloadReturnsNull() { var loggingConfiguration = new ReloadNullConfiguration(); LogManager.Configuration = loggingConfiguration; var configLoader = new LoggingConfigurationWatchableFileLoader(LogFactory.DefaultAppEnvironment); var logFactory = new LogFactory(configLoader); logFactory.Configuration = loggingConfiguration; var exRecorded = Record.Exception(() => configLoader.ReloadConfigOnTimer(loggingConfiguration)); Assert.Null(exRecorded); } /// <summary> /// We should be forward compatible so that we can add easily attributes in the future. /// </summary> [Fact] public void NewAttrOnNLogLevelShouldNotThrowError() { using (new NoThrowNLogExceptions()) { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog imAnewAttribute='noError'> <targets><target type='file' name='f1' filename='test.log' /></targets> <rules> <logger name='*' minlevel='Debug' writeto='f1'></logger> </rules> </nlog>").LogFactory; Assert.NotNull(logFactory.Configuration); } } [Fact] public void SuspendAndResumeLogging_InOrder() { LogFactory factory = new LogFactory(); // In order Suspend => Resume [Case 1] Assert.True(factory.IsLoggingEnabled()); factory.SuspendLogging(); Assert.False(factory.IsLoggingEnabled()); factory.ResumeLogging(); Assert.True(factory.IsLoggingEnabled()); // In order Suspend => Resume [Case 2] using (var factory2 = new LogFactory()) { Assert.True(factory.IsLoggingEnabled()); factory.SuspendLogging(); Assert.False(factory.IsLoggingEnabled()); factory.ResumeLogging(); Assert.True(factory.IsLoggingEnabled()); } } [Fact] public void SuspendAndResumeLogging_OutOfOrder() { LogFactory factory = new LogFactory(); // Out of order Resume => Suspend => (Suspend => Resume) factory.ResumeLogging(); Assert.True(factory.IsLoggingEnabled()); factory.SuspendLogging(); Assert.True(factory.IsLoggingEnabled()); factory.SuspendLogging(); Assert.False(factory.IsLoggingEnabled()); factory.ResumeLogging(); Assert.True(factory.IsLoggingEnabled()); } [Fact] public void LogFactory_GetLoggerWithNull_ShouldThrow() { LogFactory factory = new LogFactory(); Assert.Throws<ArgumentNullException>(() => factory.GetLogger(null)); } private class TestClass { public static void GenerateTimeout() { Thread.Sleep(5000); } } [Fact] public void PurgeObsoleteLoggersTest() { var factory = new LogFactory(); var logger = GetWeakReferenceToTemporaryLogger(factory); Assert.NotNull(logger); GC.Collect(); GC.WaitForPendingFinalizers(); factory.ReconfigExistingLoggers(true); var loggerKeysCount = factory.ResetLoggerCache(); Assert.Equal(0, loggerKeysCount); logger = GetWeakReferenceToTemporaryLogger(factory); GC.Collect(); GC.WaitForPendingFinalizers(); factory.ReconfigExistingLoggers(); factory.ReconfigExistingLoggers(false); loggerKeysCount = factory.ResetLoggerCache(); Assert.Equal(1, loggerKeysCount); } static WeakReference GetWeakReferenceToTemporaryLogger(LogFactory factory) { string uniqueLoggerName = Guid.NewGuid().ToString(); return new WeakReference(factory.GetLogger(uniqueLoggerName)); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Config { using System; using System.IO; using NLog.Config; using Xunit; public class IncludeTests : NLogTestBase { [Fact] public void IncludeTest() { LogManager.ThrowExceptions = true; var includeAttrValue = @"included.nlog"; IncludeTest_inner(includeAttrValue, GetTempDir()); } [Fact] public void IncludeWildcardTest_relative() { var includeAttrValue = @"*.nlog"; IncludeTest_inner(includeAttrValue, GetTempDir()); } [Fact] public void IncludeWildcardTest_absolute() { var includeAttrValue = @"*.nlog"; var tempPath = GetTempDir(); includeAttrValue = Path.Combine(tempPath, includeAttrValue); IncludeTest_inner(includeAttrValue, tempPath); } private static void IncludeTest_inner(string includeAttrValue, string tempDir) { Directory.CreateDirectory(tempDir); CreateConfigFile(tempDir, "included.nlog", @"<nlog xmlns='http://www.nlog-project.org/schemas/NLog.xsd'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> </nlog>"); CreateConfigFile(tempDir, "main.nlog", $@"<nlog xmlns='http://www.nlog-project.org/schemas/NLog.xsd'> <include file='{includeAttrValue}' /> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); string fileToLoad = Path.Combine(tempDir, "main.nlog"); try { // load main.nlog from the XAP LogManager.Configuration = new XmlLoggingConfiguration(fileToLoad); LogManager.GetLogger("A").Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); } finally { if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); } } [Fact] public void IncludeNotExistingTest() { LogManager.ThrowConfigExceptions = true; string tempPath = GetTempDir(); Directory.CreateDirectory(tempPath); using (StreamWriter fs = File.CreateText(Path.Combine(tempPath, "main.nlog"))) { fs.Write(@"<nlog> <include file='included.nlog' /> </nlog>"); } string fileToLoad = Path.Combine(tempPath, "main.nlog"); try { Assert.Throws<NLogConfigurationException>(() => new XmlLoggingConfiguration(fileToLoad)); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void IncludeNotExistingIgnoredTest() { var tempPath = GetTempDir(); Directory.CreateDirectory(tempPath); var config = @"<nlog> <include file='included-notpresent.nlog' ignoreErrors='true' /> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"; CreateConfigFile(tempPath, "main.nlog", config); string fileToLoad = Path.Combine(tempPath, "main.nlog"); try { LogManager.Configuration = new XmlLoggingConfiguration(fileToLoad); LogManager.GetLogger("A").Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void IncludeNotExistingIgnoredTest_DoesNotThrow() { LogManager.ThrowExceptions = true; var tempPath = GetTempDir(); Directory.CreateDirectory(tempPath); var config = @"<nlog> <include file='included-notpresent.nlog' ignoreErrors='true' /> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"; CreateConfigFile(tempPath, "main.nlog", config); string fileToLoad = Path.Combine(tempPath, "main.nlog"); var ex = Record.Exception(() => new XmlLoggingConfiguration(fileToLoad)); Assert.Null(ex); } /// <summary> /// Create config file in dir /// </summary> /// <param name="tempPath"></param> /// <param name="filename"></param> /// <param name="config"></param> private static void CreateConfigFile(string tempPath, string filename, string config) { using (var fs = File.CreateText(Path.Combine(tempPath, filename))) { fs.Write(config); } } private static string GetTempDir() { return Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets { using NLog.Targets; using System; using Xunit; public class LineEndingModeTests : NLogTestBase { [Fact] public void LineEndingModeEqualityTest() { LineEndingMode modeDefault = LineEndingMode.Default; LineEndingMode modeNone = LineEndingMode.None; LineEndingMode modeLF = LineEndingMode.LF; LineEndingMode modeCRLF = LineEndingMode.CRLF; LineEndingMode modeNull = LineEndingMode.Null; Assert.True(LineEndingMode.Default == modeDefault); Assert.True(LineEndingMode.None == modeNone); Assert.True(LineEndingMode.LF == modeLF); Assert.True(LineEndingMode.Null == modeNull); Assert.False(LineEndingMode.Default == modeNone); Assert.False(LineEndingMode.None == modeLF); Assert.False(LineEndingMode.None == modeCRLF); Assert.False(LineEndingMode.None == modeNull); Assert.False(LineEndingMode.None == (object)new { }); Assert.False(LineEndingMode.None is null); Assert.True(LineEndingMode.Default.Equals(modeDefault)); Assert.True(LineEndingMode.None.Equals(modeNone)); Assert.True(LineEndingMode.LF.Equals(modeLF)); Assert.True(LineEndingMode.Null.Equals(modeNull)); Assert.False(LineEndingMode.Default.Equals(modeNone)); Assert.False(LineEndingMode.None.Equals(modeLF)); Assert.False(LineEndingMode.None.Equals(modeCRLF)); Assert.False(LineEndingMode.None.Equals(modeNull)); Assert.False(LineEndingMode.None.Equals(new { })); Assert.False(LineEndingMode.None.Equals(null)); // Handle running tests on different operating systems if (modeCRLF.NewLineCharacters == Environment.NewLine) { Assert.False(LineEndingMode.LF == modeDefault); Assert.True(LineEndingMode.CRLF == modeDefault); } else { Assert.True(LineEndingMode.LF == modeDefault); Assert.False(LineEndingMode.CRLF == modeDefault); } } [Fact] public void LineEndingModeInequalityTest() { LineEndingMode modeDefault = LineEndingMode.Default; LineEndingMode modeNone = LineEndingMode.None; LineEndingMode modeLF = LineEndingMode.LF; LineEndingMode modeCRLF = LineEndingMode.CRLF; LineEndingMode modeNull = LineEndingMode.Null; Assert.True(LineEndingMode.Default != modeNone); Assert.True(LineEndingMode.None != modeLF); Assert.True(LineEndingMode.None != modeCRLF); Assert.True(LineEndingMode.None != modeNull); Assert.False(LineEndingMode.Default != modeDefault); Assert.False(LineEndingMode.None != modeNone); Assert.False(LineEndingMode.LF != modeLF); Assert.False(LineEndingMode.CRLF != modeCRLF); Assert.False(LineEndingMode.Null != modeNull); Assert.True(null != LineEndingMode.LF); Assert.True(null != modeLF); Assert.True(LineEndingMode.LF != null); Assert.True(modeLF != null); Assert.True(null != LineEndingMode.CRLF); Assert.True(null != modeCRLF); Assert.True(LineEndingMode.CRLF != null); Assert.True(modeCRLF != null); Assert.True(null != LineEndingMode.Null); Assert.True(null != modeNull); Assert.True(LineEndingMode.Null != null); Assert.True(modeNull != null); // Handle running tests on different operating systems if (modeCRLF.NewLineCharacters == Environment.NewLine) { Assert.True(LineEndingMode.LF != modeDefault); } else { Assert.True(LineEndingMode.CRLF != modeDefault); } } [Fact] public void LineEndingModeNullComparison() { LineEndingMode mode1 = LineEndingMode.LF; Assert.False(mode1 is null); Assert.True(mode1 != null); Assert.False(null == mode1); Assert.True(null != mode1); LineEndingMode mode2 = null; Assert.True(mode2 is null); Assert.False(mode2 != null); Assert.True(null == mode2); Assert.False(null != mode2); } [Fact] public void LineEndingModeToStringTest() { Assert.Equal("None", LineEndingMode.None.ToString()); Assert.Equal("Default", LineEndingMode.Default.ToString()); Assert.Equal("CRLF", LineEndingMode.CRLF.ToString()); Assert.Equal("CR", LineEndingMode.CR.ToString()); Assert.Equal("LF", LineEndingMode.LF.ToString()); Assert.Equal("Null", LineEndingMode.Null.ToString()); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using NLog.Config; using NLog.Internal; /// <summary> /// A specialized layout that renders XML-formatted events. /// </summary> [ThreadAgnostic] public abstract class XmlElementBase : Layout { private Layout[] _precalculateLayouts = null; private const string DefaultPropertyName = "property"; private const string DefaultPropertyKeyAttribute = "key"; private const string DefaultCollectionItemName = "item"; /// <summary> /// Initializes a new instance of the <see cref="XmlElementBase"/> class. /// </summary> /// <param name="elementName">The name of the top XML node</param> /// <param name="elementValue">The value of the top XML node</param> protected XmlElementBase(string elementName, Layout elementValue) { ElementNameInternal = elementName; LayoutWrapper.Inner = elementValue; ExcludeProperties = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Name of the XML element /// </summary> /// <remarks>Upgrade to private protected when using C# 7.2 </remarks> internal string ElementNameInternal { get => _elementNameInternal; set => _elementNameInternal = XmlHelper.XmlConvertToElementName(value?.Trim()); } private string _elementNameInternal; /// <summary> /// Value inside the XML element /// </summary> /// <remarks>Upgrade to private protected when using C# 7.2 </remarks> internal readonly LayoutRenderers.Wrappers.XmlEncodeLayoutRendererWrapper LayoutWrapper = new LayoutRenderers.Wrappers.XmlEncodeLayoutRendererWrapper(); /// <summary> /// Auto indent and create new lines /// </summary> /// <docgen category='Layout Options' order='100' /> public bool IndentXml { get; set; } /// <summary> /// Gets the array of xml 'elements' configurations. /// </summary> /// <docgen category='Layout Options' order='10' /> [ArrayParameter(typeof(XmlElement), "element")] public IList<XmlElement> Elements { get; } = new List<XmlElement>(); /// <summary> /// Gets the array of 'attributes' configurations for the element /// </summary> /// <docgen category='Layout Options' order='10' /> [ArrayParameter(typeof(XmlAttribute), "attribute")] public IList<XmlAttribute> Attributes { get; } = new List<XmlAttribute>(); /// <summary> /// Gets or sets whether a ElementValue with empty value should be included in the output /// </summary> /// <docgen category='Layout Options' order='100' /> public bool IncludeEmptyValue { get; set; } /// <summary> /// Gets or sets the option to include all properties from the log event (as XML) /// </summary> /// <docgen category='Layout Output' order='10' /> public bool IncludeEventProperties { get; set; } /// <summary> /// Gets or sets whether to include the contents of the <see cref="ScopeContext"/> dictionary. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeScopeProperties { get => _includeScopeProperties ?? (_includeMdlc == true || _includeMdc == true); set => _includeScopeProperties = value; } private bool? _includeScopeProperties; /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary. /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeMdc { get => _includeMdc ?? false; set => _includeMdc = value; } private bool? _includeMdc; /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsLogicalContext"/> dictionary. /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeMdlc { get => _includeMdlc ?? false; set => _includeMdlc = value; } private bool? _includeMdlc; /// <summary> /// Gets or sets the option to include all properties from the log event (as XML) /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeEventProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeAllProperties { get => IncludeEventProperties; set => IncludeEventProperties = value; } /// <summary> /// List of property names to exclude when <see cref="IncludeAllProperties"/> is true /// </summary> /// <docgen category='Layout Options' order='100' /> #if !NET35 public ISet<string> ExcludeProperties { get; set; } #else public HashSet<string> ExcludeProperties { get; set; } #endif /// <summary> /// XML element name to use when rendering properties /// </summary> /// <remarks> /// Support string-format where {0} means property-key-name /// /// Skips closing element tag when having configured <see cref="PropertiesElementValueAttribute"/> /// </remarks> /// <docgen category='Layout Options' order='100' /> public string PropertiesElementName { get => _propertiesElementName; set { _propertiesElementName = value; _propertiesElementNameHasFormat = value?.IndexOf('{') >= 0; if (!_propertiesElementNameHasFormat) _propertiesElementName = XmlHelper.XmlConvertToElementName(value?.Trim()); } } private string _propertiesElementName = DefaultPropertyName; private bool _propertiesElementNameHasFormat; /// <summary> /// XML attribute name to use when rendering property-key /// /// When null (or empty) then key-attribute is not included /// </summary> /// <remarks> /// Will replace newlines in attribute-value with &#13;&#10; /// </remarks> /// <docgen category='Layout Options' order='100' /> public string PropertiesElementKeyAttribute { get; set; } = DefaultPropertyKeyAttribute; /// <summary> /// XML attribute name to use when rendering property-value /// /// When null (or empty) then value-attribute is not included and /// value is formatted as XML-element-value /// </summary> /// <remarks> /// Skips closing element tag when using attribute for value /// /// Will replace newlines in attribute-value with &#13;&#10; /// </remarks> /// <docgen category='Layout Options' order='100' /> public string PropertiesElementValueAttribute { get; set; } /// <summary> /// XML element name to use for rendering IList-collections items /// </summary> /// <docgen category='Layout Options' order='100' /> public string PropertiesCollectionItemName { get; set; } = DefaultCollectionItemName; /// <summary> /// How far should the XML serializer follow object references before backing off /// </summary> /// <docgen category='Layout Options' order='100' /> public int MaxRecursionLimit { get; set; } = 1; private ObjectReflectionCache ObjectReflectionCache => _objectReflectionCache ?? (_objectReflectionCache = new ObjectReflectionCache(LoggingConfiguration.GetServiceProvider())); private ObjectReflectionCache _objectReflectionCache; private static readonly IEqualityComparer<object> _referenceEqualsComparer = SingleItemOptimizedHashSet<object>.ReferenceEqualityComparer.Default; private const int MaxXmlLength = 512 * 1024; /// <inheritdoc/> protected override void InitializeLayout() { base.InitializeLayout(); if (IncludeScopeProperties) ThreadAgnostic = false; if (IncludeEventProperties) MutableUnsafe = true; if (Attributes.Count > 1) { HashSet<string> attributeValidator = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var attribute in Attributes) { if (string.IsNullOrEmpty(attribute.Name)) { Common.InternalLogger.Warn("XmlElement(ElementName={0}): Contains attribute with missing name (Ignored)"); } else if (attributeValidator.Contains(attribute.Name)) { Common.InternalLogger.Warn("XmlElement(ElementName={0}): Contains duplicate attribute name: {1} (Invalid xml)", ElementNameInternal, attribute.Name); } else { attributeValidator.Add(attribute.Name); } } } _precalculateLayouts = (IncludeEventProperties || IncludeScopeProperties) ? null : ResolveLayoutPrecalculation(Attributes.Select(atr => atr.Layout).Concat(Elements.Select(elm => elm.Layout))); } /// <inheritdoc/> protected override void CloseLayout() { _precalculateLayouts = null; base.CloseLayout(); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { PrecalculateBuilderInternal(logEvent, target, _precalculateLayouts); } /// <inheritdoc/> protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { int orgLength = target.Length; RenderXmlFormattedMessage(logEvent, target); if (target.Length == orgLength && IncludeEmptyValue && !string.IsNullOrEmpty(ElementNameInternal)) { RenderSelfClosingElement(target, ElementNameInternal); } } /// <inheritdoc/> protected override string GetFormattedMessage(LogEventInfo logEvent) { return RenderAllocateBuilder(logEvent); } private void RenderXmlFormattedMessage(LogEventInfo logEvent, StringBuilder sb) { int orgLength = sb.Length; // Attributes without element-names should be added to the top XML element if (!string.IsNullOrEmpty(ElementNameInternal)) { for (int i = 0; i < Attributes.Count; i++) { var attribute = Attributes[i]; int beforeAttributeLength = sb.Length; if (!RenderAppendXmlAttributeValue(attribute, logEvent, sb, sb.Length == orgLength)) { sb.Length = beforeAttributeLength; } } if (sb.Length != orgLength) { bool hasElements = HasNestedXmlElements(logEvent); if (!hasElements) { sb.Append("/>"); return; } else { sb.Append('>'); } } if (LayoutWrapper.Inner != null) { int beforeElementLength = sb.Length; if (sb.Length == orgLength) { RenderStartElement(sb, ElementNameInternal); } int beforeValueLength = sb.Length; LayoutWrapper.RenderAppendBuilder(logEvent, sb); if (beforeValueLength == sb.Length && !IncludeEmptyValue) { sb.Length = beforeElementLength; } } if (IndentXml && sb.Length != orgLength) sb.AppendLine(); } //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < Elements.Count; i++) { var element = Elements[i]; int beforeAttributeLength = sb.Length; if (!RenderAppendXmlElementValue(element, logEvent, sb, sb.Length == orgLength)) { sb.Length = beforeAttributeLength; } } AppendLogEventXmlProperties(logEvent, sb, orgLength); if (sb.Length > orgLength && !string.IsNullOrEmpty(ElementNameInternal)) { EndXmlDocument(sb, ElementNameInternal); } } private bool HasNestedXmlElements(LogEventInfo logEvent) { if (LayoutWrapper.Inner != null) return true; if (Elements.Count > 0) return true; if (IncludeScopeProperties) return true; if (IncludeEventProperties && logEvent.HasProperties) return true; return false; } private void AppendLogEventXmlProperties(LogEventInfo logEventInfo, StringBuilder sb, int orgLength) { if (IncludeScopeProperties) { bool checkExcludeProperties = ExcludeProperties.Count > 0; using (var scopeEnumerator = ScopeContext.GetAllPropertiesEnumerator()) { while (scopeEnumerator.MoveNext()) { var scopeProperty = scopeEnumerator.Current; if (string.IsNullOrEmpty(scopeProperty.Key)) continue; if (checkExcludeProperties && ExcludeProperties.Contains(scopeProperty.Key)) continue; AppendXmlPropertyValue(scopeProperty.Key, scopeProperty.Value, sb, orgLength); } } } if (IncludeEventProperties) { AppendLogEventProperties(logEventInfo, sb, orgLength); } } private void AppendLogEventProperties(LogEventInfo logEventInfo, StringBuilder sb, int orgLength) { if (!logEventInfo.HasProperties) return; bool checkExcludeProperties = ExcludeProperties.Count > 0; IEnumerable<MessageTemplates.MessageTemplateParameter> propertiesList = logEventInfo.CreateOrUpdatePropertiesInternal(true); foreach (var prop in propertiesList) { if (string.IsNullOrEmpty(prop.Name)) continue; if (checkExcludeProperties && ExcludeProperties.Contains(prop.Name)) continue; var propertyValue = prop.Value; if (!string.IsNullOrEmpty(prop.Format) && propertyValue is IFormattable formattedProperty) propertyValue = formattedProperty.ToString(prop.Format, logEventInfo.FormatProvider ?? LoggingConfiguration?.DefaultCultureInfo); else if (prop.CaptureType == MessageTemplates.CaptureType.Stringify) propertyValue = Convert.ToString(prop.Value ?? string.Empty, logEventInfo.FormatProvider ?? LoggingConfiguration?.DefaultCultureInfo); AppendXmlPropertyObjectValue(prop.Name, propertyValue, sb, orgLength, default(SingleItemOptimizedHashSet<object>), 0); } } private bool AppendXmlPropertyObjectValue(string propName, object propertyValue, StringBuilder sb, int orgLength, SingleItemOptimizedHashSet<object> objectsInPath, int depth, bool ignorePropertiesElementName = false) { var convertibleValue = propertyValue as IConvertible; var objTypeCode = convertibleValue?.GetTypeCode() ?? (propertyValue is null ? TypeCode.Empty : TypeCode.Object); if (objTypeCode != TypeCode.Object) { string xmlValueString = XmlHelper.XmlConvertToString(convertibleValue, objTypeCode, true); AppendXmlPropertyStringValue(propName, xmlValueString, sb, orgLength, false, ignorePropertiesElementName); } else { int beforeValueLength = sb.Length; if (beforeValueLength > MaxXmlLength) { return false; } int nextDepth = objectsInPath.Count == 0 ? depth : (depth + 1); // Allow serialization of list-items if (nextDepth > MaxRecursionLimit) { return false; } if (objectsInPath.Contains(propertyValue)) { return false; } if (propertyValue is System.Collections.IDictionary dict) { using (StartCollectionScope(ref objectsInPath, dict)) { AppendXmlDictionaryObject(propName, dict, sb, orgLength, objectsInPath, nextDepth, ignorePropertiesElementName); } } else if (propertyValue is System.Collections.IEnumerable collection) { if (ObjectReflectionCache.TryLookupExpandoObject(propertyValue, out var propertyValues)) { using (new SingleItemOptimizedHashSet<object>.SingleItemScopedInsert(propertyValue, ref objectsInPath, false, _referenceEqualsComparer)) { AppendXmlObjectPropertyValues(propName, ref propertyValues, sb, orgLength, ref objectsInPath, nextDepth, ignorePropertiesElementName); } } else { using (StartCollectionScope(ref objectsInPath, collection)) { AppendXmlCollectionObject(propName, collection, sb, orgLength, objectsInPath, nextDepth, ignorePropertiesElementName); } } } else { using (new SingleItemOptimizedHashSet<object>.SingleItemScopedInsert(propertyValue, ref objectsInPath, false, _referenceEqualsComparer)) { var propertyValues = ObjectReflectionCache.LookupObjectProperties(propertyValue); AppendXmlObjectPropertyValues(propName, ref propertyValues, sb, orgLength, ref objectsInPath, nextDepth, ignorePropertiesElementName); } } } return true; } private static SingleItemOptimizedHashSet<object>.SingleItemScopedInsert StartCollectionScope(ref SingleItemOptimizedHashSet<object> objectsInPath, object value) { return new SingleItemOptimizedHashSet<object>.SingleItemScopedInsert(value, ref objectsInPath, true, _referenceEqualsComparer); } private void AppendXmlCollectionObject(string propName, System.Collections.IEnumerable collection, StringBuilder sb, int orgLength, SingleItemOptimizedHashSet<object> objectsInPath, int depth, bool ignorePropertiesElementName) { string propNameElement = AppendXmlPropertyValue(propName, string.Empty, sb, orgLength, true); if (!string.IsNullOrEmpty(propNameElement)) { foreach (var item in collection) { int beforeValueLength = sb.Length; if (beforeValueLength > MaxXmlLength) break; if (!AppendXmlPropertyObjectValue(PropertiesCollectionItemName, item, sb, orgLength, objectsInPath, depth, true)) { sb.Length = beforeValueLength; } } AppendClosingPropertyTag(propNameElement, sb, ignorePropertiesElementName); } } private void AppendXmlDictionaryObject(string propName, System.Collections.IDictionary dictionary, StringBuilder sb, int orgLength, SingleItemOptimizedHashSet<object> objectsInPath, int depth, bool ignorePropertiesElementName) { string propNameElement = AppendXmlPropertyValue(propName, string.Empty, sb, orgLength, true, ignorePropertiesElementName); if (!string.IsNullOrEmpty(propNameElement)) { foreach (var item in new DictionaryEntryEnumerable(dictionary)) { int beforeValueLength = sb.Length; if (beforeValueLength > MaxXmlLength) break; if (!AppendXmlPropertyObjectValue(item.Key?.ToString(), item.Value, sb, orgLength, objectsInPath, depth)) { sb.Length = beforeValueLength; } } AppendClosingPropertyTag(propNameElement, sb, ignorePropertiesElementName); } } private void AppendXmlObjectPropertyValues(string propName, ref ObjectReflectionCache.ObjectPropertyList propertyValues, StringBuilder sb, int orgLength, ref SingleItemOptimizedHashSet<object> objectsInPath, int depth, bool ignorePropertiesElementName = false) { if (propertyValues.IsSimpleValue) { AppendXmlPropertyValue(propName, propertyValues.ObjectValue, sb, orgLength, false, ignorePropertiesElementName); } else { string propNameElement = AppendXmlPropertyValue(propName, string.Empty, sb, orgLength, true, ignorePropertiesElementName); if (!string.IsNullOrEmpty(propNameElement)) { foreach (var property in propertyValues) { int beforeValueLength = sb.Length; if (beforeValueLength > MaxXmlLength) break; if (!property.HasNameAndValue) continue; var propertyTypeCode = property.TypeCode; if (propertyTypeCode != TypeCode.Object) { string xmlValueString = XmlHelper.XmlConvertToString((IConvertible)property.Value, propertyTypeCode, true); AppendXmlPropertyStringValue(property.Name, xmlValueString, sb, orgLength, false, ignorePropertiesElementName); } else { if (!AppendXmlPropertyObjectValue(property.Name, property.Value, sb, orgLength, objectsInPath, depth)) { sb.Length = beforeValueLength; } } } AppendClosingPropertyTag(propNameElement, sb, ignorePropertiesElementName); } } } private string AppendXmlPropertyValue(string propName, object propertyValue, StringBuilder sb, int orgLength, bool ignoreValue = false, bool ignorePropertiesElementName = false) { string xmlValueString = ignoreValue ? string.Empty : XmlHelper.XmlConvertToStringSafe(propertyValue); return AppendXmlPropertyStringValue(propName, xmlValueString, sb, orgLength, ignoreValue, ignorePropertiesElementName); } private string AppendXmlPropertyStringValue(string propName, string xmlValueString, StringBuilder sb, int orgLength, bool ignoreValue = false, bool ignorePropertiesElementName = false) { if (string.IsNullOrEmpty(PropertiesElementName)) return string.Empty; // Not supported propName = propName?.Trim(); if (string.IsNullOrEmpty(propName)) return string.Empty; // Not supported if (sb.Length == orgLength && !string.IsNullOrEmpty(ElementNameInternal)) { BeginXmlDocument(sb, ElementNameInternal); } if (IndentXml && !string.IsNullOrEmpty(ElementNameInternal)) sb.Append(" "); sb.Append('<'); string propNameElement; if (ignorePropertiesElementName) { propNameElement = XmlHelper.XmlConvertToElementName(propName); sb.Append(propNameElement); } else { if (_propertiesElementNameHasFormat) { propNameElement = XmlHelper.XmlConvertToElementName(propName); sb.AppendFormat(PropertiesElementName, propNameElement); } else { propNameElement = PropertiesElementName; sb.Append(PropertiesElementName); } RenderAttribute(sb, PropertiesElementKeyAttribute, propName); } if (!ignoreValue) { if (RenderAttribute(sb, PropertiesElementValueAttribute, xmlValueString)) { sb.Append("/>"); if (IndentXml) sb.AppendLine(); } else { sb.Append('>'); XmlHelper.EscapeXmlString(xmlValueString, false, sb); AppendClosingPropertyTag(propNameElement, sb, ignorePropertiesElementName); } } else { sb.Append('>'); if (IndentXml) sb.AppendLine(); } return propNameElement; } private void AppendClosingPropertyTag(string propNameElement, StringBuilder sb, bool ignorePropertiesElementName = false) { sb.Append("</"); if (ignorePropertiesElementName) sb.Append(propNameElement); else sb.AppendFormat(PropertiesElementName, propNameElement); sb.Append('>'); if (IndentXml) sb.AppendLine(); } /// <summary> /// write attribute, only if <paramref name="attributeName"/> is not empty /// </summary> /// <param name="sb"></param> /// <param name="attributeName"></param> /// <param name="value"></param> /// <returns>rendered</returns> private static bool RenderAttribute(StringBuilder sb, string attributeName, string value) { if (!string.IsNullOrEmpty(attributeName)) { sb.Append(' '); sb.Append(attributeName); sb.Append("=\""); XmlHelper.EscapeXmlString(value, true, sb); sb.Append('\"'); return true; } return false; } private bool RenderAppendXmlElementValue(XmlElementBase xmlElement, LogEventInfo logEvent, StringBuilder sb, bool beginXmlDocument) { string xmlElementName = xmlElement.ElementNameInternal; if (string.IsNullOrEmpty(xmlElementName)) return false; if (beginXmlDocument && !string.IsNullOrEmpty(ElementNameInternal)) { BeginXmlDocument(sb, ElementNameInternal); } if (IndentXml && !string.IsNullOrEmpty(ElementNameInternal)) sb.Append(" "); int beforeValueLength = sb.Length; xmlElement.Render(logEvent, sb); if (sb.Length == beforeValueLength && !xmlElement.IncludeEmptyValue) return false; if (IndentXml) sb.AppendLine(); return true; } private bool RenderAppendXmlAttributeValue(XmlAttribute xmlAttribute, LogEventInfo logEvent, StringBuilder sb, bool beginXmlDocument) { string xmlKeyString = xmlAttribute.Name; if (string.IsNullOrEmpty(xmlKeyString)) return false; if (beginXmlDocument) { sb.Append('<'); sb.Append(ElementNameInternal); } sb.Append(' '); sb.Append(xmlKeyString); sb.Append("=\""); if (!xmlAttribute.RenderAppendXmlValue(logEvent, sb)) return false; sb.Append('\"'); return true; } private void BeginXmlDocument(StringBuilder sb, string elementName) { RenderStartElement(sb, elementName); if (IndentXml) sb.AppendLine(); } private void EndXmlDocument(StringBuilder sb, string elementName) { RenderEndElement(sb, elementName); } /// <inheritdoc/> public override string ToString() { if (Elements.Count > 0) return ToStringWithNestedItems(Elements, l => l.ToString()); else if (Attributes.Count > 0) return ToStringWithNestedItems(Attributes, a => "Attributes:" + a.Name); else if (ElementNameInternal != null) return ToStringWithNestedItems(new[] { this }, n => "Element:" + n.ElementNameInternal); else return GetType().Name; } private static void RenderSelfClosingElement(StringBuilder target, string elementName) { target.Append('<'); target.Append(elementName); target.Append("/>"); } private static void RenderStartElement(StringBuilder sb, string elementName) { sb.Append('<'); sb.Append(elementName); sb.Append('>'); } private static void RenderEndElement(StringBuilder sb, string elementName) { sb.Append("</"); sb.Append(elementName); sb.Append('>'); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.Reflection; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; /// <summary> /// Represents a parameter to a Database target. /// </summary> [NLogConfigurationItem] public class DatabaseParameterInfo { private static readonly Dictionary<string, Type> _typesByDbTypeName = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase) { { nameof(System.Data.DbType.AnsiString), typeof(string) }, // { nameof(System.Data.DbType.Binary), typeof(byte[]) }, // not supported { nameof(System.Data.DbType.Byte), typeof(byte) }, { nameof(System.Data.DbType.Boolean), typeof(bool) }, { nameof(System.Data.DbType.Currency), typeof(decimal) }, { nameof(System.Data.DbType.Date), typeof(DateTime) }, // DateOnly when .net framework will be deprecated { nameof(System.Data.DbType.DateTime), typeof(DateTime) }, { nameof(System.Data.DbType.Decimal), typeof(decimal) }, { nameof(System.Data.DbType.Double), typeof(double) }, { nameof(System.Data.DbType.Guid), typeof(Guid) }, { nameof(System.Data.DbType.Int16), typeof(short) }, { nameof(System.Data.DbType.Int32), typeof(int) }, { nameof(System.Data.DbType.Int64), typeof(long) }, { nameof(System.Data.DbType.Object), typeof(object) }, // not sure if we should support this { nameof(System.Data.DbType.SByte), typeof(sbyte) }, { nameof(System.Data.DbType.Single), typeof(float) }, { nameof(System.Data.DbType.String), typeof(string) }, { nameof(System.Data.DbType.Time), typeof(TimeSpan) }, // TimeOnly when .net framework will be deprecated { nameof(System.Data.DbType.UInt16), typeof(ushort) }, { nameof(System.Data.DbType.UInt32), typeof(uint) }, { nameof(System.Data.DbType.UInt64), typeof(ulong) }, { nameof(System.Data.DbType.VarNumeric), typeof(decimal) }, { nameof(System.Data.DbType.AnsiStringFixedLength), typeof(string) }, { nameof(System.Data.DbType.StringFixedLength), typeof(string) }, { nameof(System.Data.DbType.Xml), typeof(string) }, { nameof(System.Data.DbType.DateTime2), typeof(DateTime) }, { nameof(System.Data.DbType.DateTimeOffset), typeof(DateTimeOffset) } }; private readonly ValueTypeLayoutInfo _layoutInfo = new ValueTypeLayoutInfo(); /// <summary> /// Initializes a new instance of the <see cref="DatabaseParameterInfo" /> class. /// </summary> public DatabaseParameterInfo() : this(null, null) { } /// <summary> /// Initializes a new instance of the <see cref="DatabaseParameterInfo" /> class. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="parameterLayout">The parameter layout.</param> public DatabaseParameterInfo(string parameterName, Layout parameterLayout) { Name = parameterName; Layout = parameterLayout; } /// <summary> /// Gets or sets the database parameter name. /// </summary> /// <docgen category='Parameter Options' order='0' /> [RequiredParameter] public string Name { get; set; } /// <summary> /// Gets or sets the layout that should be use to calculate the value for the parameter. /// </summary> /// <docgen category='Parameter Options' order='1' /> [RequiredParameter] public Layout Layout { get => _layoutInfo.Layout; set => _layoutInfo.Layout = value; } /// <summary> /// Gets or sets the database parameter DbType. /// </summary> /// <docgen category='Parameter Options' order='2' /> public string DbType { get => _dbType; set { _dbType = value; if (!string.IsNullOrEmpty(_dbType)) { if (ParameterType is null || ParameterType == _dbParameterType) { var dbParameterType = TryParseDbType(DbType); if (dbParameterType != null) { ParameterType = dbParameterType; } _dbParameterType = dbParameterType; } } else if (_dbParameterType != null && ParameterType == _dbParameterType) { ParameterType = null; } } } private string _dbType; private Type _dbParameterType; /// <summary> /// Gets or sets the database parameter size. /// </summary> /// <docgen category='Parameter Options' order='3' /> public int Size { get; set; } /// <summary> /// Gets or sets the database parameter precision. /// </summary> /// <docgen category='Parameter Options' order='4' /> public byte Precision { get; set; } /// <summary> /// Gets or sets the database parameter scale. /// </summary> /// <docgen category='Parameter Options' order='5' /> public byte Scale { get; set; } /// <summary> /// Gets or sets the type of the parameter. /// </summary> /// <docgen category='Parameter Options' order='6' /> public Type ParameterType { get => _layoutInfo.ValueType; set { _dbParameterType = null; _layoutInfo.ValueType = value; } } /// <summary> /// Gets or sets the fallback value when result value is not available /// </summary> /// <docgen category='Parameter Options' order='7' /> public Layout DefaultValue { get => _layoutInfo.DefaultValue; set => _layoutInfo.DefaultValue = value; } /// <summary> /// Gets or sets convert format of the database parameter value. /// </summary> /// <docgen category='Parameter Options' order='8' /> public string Format { get => _layoutInfo.ValueParseFormat; set => _layoutInfo.ValueParseFormat = value; } /// <summary> /// Gets or sets the culture used for parsing parameter string-value for type-conversion /// </summary> /// <docgen category='Parameter Options' order='9' /> public CultureInfo Culture { get => _layoutInfo.ValueParseCulture; set => _layoutInfo.ValueParseCulture = value; } /// <summary> /// Gets or sets whether empty value should translate into DbNull. Requires database column to allow NULL values. /// </summary> /// <docgen category='Parameter Options' order='10' /> public bool AllowDbNull { get => _allowDbNull; set { _allowDbNull = value; if (value) DefaultValue = new Layout<DBNull>(DBNull.Value); else if (DefaultValue is Layout<DBNull>) DefaultValue = null; } } private bool _allowDbNull; /// <summary> /// Render Result Value /// </summary> /// <param name="logEvent">Log event for rendering</param> /// <returns>Result value when available, else fallback to defaultValue</returns> public object RenderValue(LogEventInfo logEvent) => _layoutInfo.RenderValue(logEvent); internal bool SetDbType(IDbDataParameter dbParameter) { if (!string.IsNullOrEmpty(DbType)) { if (_cachedDbTypeSetter is null || !_cachedDbTypeSetter.IsValid(dbParameter.GetType(), DbType)) { _cachedDbTypeSetter = new DbTypeSetter(dbParameter.GetType(), DbType); } return _cachedDbTypeSetter.SetDbType(dbParameter); } return true; // DbType not in use } private static Type TryParseDbType(string dbTypeName) { // retrieve the type name if a full name is given dbTypeName = dbTypeName?.Substring(dbTypeName.LastIndexOf('.') + 1).Trim(); if (string.IsNullOrEmpty(dbTypeName)) return null; return _typesByDbTypeName.TryGetValue(dbTypeName, out var type) ? type : null; } DbTypeSetter _cachedDbTypeSetter; class DbTypeSetter { private readonly Type _dbPropertyInfoType; private readonly string _dbTypeName; private readonly PropertyInfo _dbTypeSetter; private readonly Enum _dbTypeValue; private Action<IDbDataParameter> _dbTypeSetterFast; public DbTypeSetter(Type dbParameterType, string dbTypeName) { _dbPropertyInfoType = dbParameterType; _dbTypeName = dbTypeName?.Trim(); if (!string.IsNullOrEmpty(_dbTypeName)) { string[] dbTypeNames = _dbTypeName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); if (dbTypeNames.Length > 1 && !string.Equals(dbTypeNames[0], nameof(System.Data.DbType), StringComparison.OrdinalIgnoreCase)) { PropertyInfo propInfo = dbParameterType.GetProperty(dbTypeNames[0], BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (propInfo != null && TryParseEnum(dbTypeNames[1], propInfo.PropertyType, out Enum enumType)) { _dbTypeSetter = propInfo; _dbTypeValue = enumType; } } else { dbTypeName = dbTypeNames[dbTypeNames.Length - 1]; if (!string.IsNullOrEmpty(dbTypeName) && ConversionHelpers.TryParseEnum(dbTypeName, out DbType dbType)) { _dbTypeValue = dbType; _dbTypeSetterFast = (p) => p.DbType = dbType; } } } } public bool IsValid(Type dbParameterType, string dbTypeName) { if (ReferenceEquals(_dbPropertyInfoType, dbParameterType) && ReferenceEquals(_dbTypeName, dbTypeName)) { if (_dbTypeSetterFast == null && _dbTypeSetter != null && _dbTypeValue != null) { var propertySetter = _dbTypeSetter.CreatePropertySetter(); _dbTypeSetterFast = (p) => propertySetter.Invoke(p, _dbTypeValue); } return true; } return false; } public bool SetDbType(IDbDataParameter dbParameter) { if (_dbTypeSetterFast != null) { _dbTypeSetterFast.Invoke(dbParameter); return true; } else if (_dbTypeSetter != null && _dbTypeValue != null) { _dbTypeSetter.SetValue(dbParameter, _dbTypeValue, null); return true; } return false; } private static bool TryParseEnum(string value, Type enumType, out Enum enumValue) { if (!string.IsNullOrEmpty(value)) { // Note: .NET Standard 2.1 added a public Enum.TryParse(Type) try { enumValue = Enum.Parse(enumType, value, true) as Enum; return true; } catch (ArgumentException) { enumValue = null; return false; } } else { enumValue = null; return false; } } } } }<file_sep>Support & contributing guidelines === Do you have feature requests, questions or would you like to report a bug? Please follow these guidelines when posting on the [issue list](https://github.com/NLog/NLog/issues). The issues are labeled with the [following guideline](/issue-labeling.md). Feature requests ---- Please provide the following information: - The current NLog version - Any current work-arounds - Example of the config when implemented. Please use [fenced code blocks](https://help.github.com/articles/creating-and-highlighting-code-blocks/#fenced-code-blocks). - Pull requests and unit tests are welcome! Questions ---- Please provide the following information: - The current NLog version - The current config (xml or code). Please use [fenced code blocks](https://help.github.com/articles/creating-and-highlighting-code-blocks/#fenced-code-blocks). - If relevant: the current result (Including full exception details if any) - If relevant: the expected result Bug reports ---- Please provide the following information: - The current NLog version - The error message and stacktrace. Please use [fenced code blocks](https://help.github.com/articles/creating-and-highlighting-code-blocks/#fenced-code-blocks). - The internal log, `Debug` level. See [Internal Logging](https://github.com/NLog/NLog/wiki/Internal-Logging) - The current result - The expected result - Any current work-arounds - The current config (xml or code). Please use [fenced code blocks](https://help.github.com/articles/creating-and-highlighting-code-blocks/#fenced-code-blocks). - Pull requests and unit tests are welcome! Pull requests ---- Unit tests are really appreciated! Please document any public method and property. Document **why** and not how. At least required: * Method: Summary, param and return. * Property: Summary Multiple .NET versions === Keep in mind that multiple versions of .NET are supported. Some methods are not available in all .NET versions. The following conditional compilation symbols can be used: ``` #if NET35 #if NET45 #if NET46 #if NETSTANDARD #if NETSTANDARD1_3 #if NETSTANDARD1_5 ``` Update your fork === Is your fork not up-to-date with the NLog code? Most of the time that isn't a problem. But if you like to "sync back" the changes to your repository, execute the following command: The first time: ``` git remote add upstream https://github.com/NLog/NLog.git ``` After that you repository will have two remotes. You could update your remote (the fork) in the following way: ``` git fetch upstream git checkout <your feature branch> git rebase upstream/master ..fix if needed and git push -f ``` if `rebase` won't work well, use `git merge master` as alternative. It's also possible to send a PR in the opposite direction, but that's not preferred as it will pollute the commit log. <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using NLog.Config; /// <summary> /// Utilities for dealing with <see cref="StackTraceUsage"/> values. /// </summary> internal static class StackTraceUsageUtils { private static readonly Assembly nlogAssembly = typeof(StackTraceUsageUtils).GetAssembly(); private static readonly Assembly mscorlibAssembly = typeof(string).GetAssembly(); private static readonly Assembly systemAssembly = typeof(Debug).GetAssembly(); public static StackTraceUsage GetStackTraceUsage(bool includeFileName, int skipFrames, bool captureStackTrace) { if (!captureStackTrace) { return StackTraceUsage.None; } if (skipFrames != 0) { return includeFileName ? StackTraceUsage.Max : StackTraceUsage.WithStackTrace; } if (includeFileName) { return StackTraceUsage.WithCallSite | StackTraceUsage.WithFileNameAndLineNumber; } return StackTraceUsage.WithCallSite; } public static int GetFrameCount(this StackTrace strackTrace) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 return strackTrace.FrameCount; #else return strackTrace.GetFrames().Length; #endif } public static string GetStackFrameMethodName(MethodBase method, bool includeMethodInfo, bool cleanAsyncMoveNext, bool cleanAnonymousDelegates) { if (method is null) return null; string methodName = method.Name; var callerClassType = method.DeclaringType; if (cleanAsyncMoveNext && methodName == "MoveNext" && callerClassType?.DeclaringType != null && callerClassType.Name.IndexOf('<') == 0) { // NLog.UnitTests.LayoutRenderers.CallSiteTests+<CleanNamesOfAsyncContinuations>d_3'1.MoveNext int endIndex = callerClassType.Name.IndexOf('>', 1); if (endIndex > 1) { methodName = callerClassType.Name.Substring(1, endIndex - 1); if (methodName.IndexOf('<') == 0) methodName = methodName.Substring(1, methodName.Length - 1); // Local functions, and anonymous-methods in Task.Run() } } // Clean up the function name if it is an anonymous delegate // <.ctor>b__0 // <Main>b__2 if (cleanAnonymousDelegates && (methodName.IndexOf('<') == 0 && methodName.IndexOf("__", StringComparison.Ordinal) >= 0 && methodName.IndexOf('>') >= 0)) { int startIndex = methodName.IndexOf('<') + 1; int endIndex = methodName.IndexOf('>'); methodName = methodName.Substring(startIndex, endIndex - startIndex); } if (includeMethodInfo && methodName == method.Name) { methodName = method.ToString(); } return methodName; } public static string GetStackFrameMethodClassName(MethodBase method, bool includeNameSpace, bool cleanAsyncMoveNext, bool cleanAnonymousDelegates) { if (method is null) return null; var callerClassType = method.DeclaringType; if (cleanAsyncMoveNext && method.Name == "MoveNext" && callerClassType?.DeclaringType != null && callerClassType.Name.IndexOf('<') == 0) { // NLog.UnitTests.LayoutRenderers.CallSiteTests+<CleanNamesOfAsyncContinuations>d_3'1 int endIndex = callerClassType.Name.IndexOf('>', 1); if (endIndex > 1) { callerClassType = callerClassType.DeclaringType; } } if (!includeNameSpace && callerClassType?.DeclaringType != null && callerClassType.IsNested && callerClassType.GetFirstCustomAttribute<CompilerGeneratedAttribute>() != null) { return callerClassType.DeclaringType.Name; } string className = includeNameSpace ? callerClassType?.FullName : callerClassType?.Name; if (cleanAnonymousDelegates && className != null) { // NLog.UnitTests.LayoutRenderers.CallSiteTests+<>c__DisplayClassa int index = className.IndexOf("+<>", StringComparison.Ordinal); if (index >= 0) { className = className.Substring(0, index); } } return className; } [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming - Allow callsite logic", "IL2026")] public static MethodBase GetStackMethod(StackFrame stackFrame) { return stackFrame?.GetMethod(); } /// <summary> /// Gets the fully qualified name of the class invoking the calling method, including the /// namespace but not the assembly. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static string GetClassFullName() { int framesToSkip = 2; string className = string.Empty; #if !NETSTANDARD1_3 && !NETSTANDARD1_5 var stackFrame = new StackFrame(framesToSkip, false); className = GetClassFullName(stackFrame); #else var stackTrace = Environment.StackTrace; var stackTraceLines = stackTrace.Replace("\r", "").SplitAndTrimTokens('\n'); for (int i = 0; i < stackTraceLines.Length; ++i) { var callingClassAndMethod = stackTraceLines[i].Split(new[] { " ", "<>", "(", ")" }, StringSplitOptions.RemoveEmptyEntries)[1]; int methodStartIndex = callingClassAndMethod.LastIndexOf(".", StringComparison.Ordinal); if (methodStartIndex > 0) { // Trim method name. var callingClass = callingClassAndMethod.Substring(0, methodStartIndex); // Needed because of extra dot, for example if method was .ctor() className = callingClass.TrimEnd('.'); if (!className.StartsWith("System.Environment", StringComparison.Ordinal) && framesToSkip != 0) { i += framesToSkip - 1; framesToSkip = 0; continue; } if (!className.StartsWith("System.", StringComparison.Ordinal)) break; } } #endif return className; } #if !NETSTANDARD1_3 && !NETSTANDARD1_5 /// <summary> /// Gets the fully qualified name of the class invoking the calling method, including the /// namespace but not the assembly. /// </summary> /// <param name="stackFrame">StackFrame from the calling method</param> /// <returns>Fully qualified class name</returns> public static string GetClassFullName(StackFrame stackFrame) { string className = LookupClassNameFromStackFrame(stackFrame); if (string.IsNullOrEmpty(className)) { var stackTrace = new StackTrace(false); className = GetClassFullName(stackTrace); if (string.IsNullOrEmpty(className)) { var method = StackTraceUsageUtils.GetStackMethod(stackFrame); className = method?.Name ?? string.Empty; } } return className; } #endif private static string GetClassFullName(StackTrace stackTrace) { foreach (StackFrame frame in stackTrace.GetFrames()) { string className = LookupClassNameFromStackFrame(frame); if (!string.IsNullOrEmpty(className)) { return className; } } return string.Empty; } /// <summary> /// Returns the assembly from the provided StackFrame (If not internal assembly) /// </summary> /// <returns>Valid assembly, or null if assembly was internal</returns> public static Assembly LookupAssemblyFromStackFrame(StackFrame stackFrame) { var method = StackTraceUsageUtils.GetStackMethod(stackFrame); if (method is null) { return null; } var assembly = method.DeclaringType?.GetAssembly() ?? method.Module?.Assembly; // skip stack frame if the method declaring type assembly is from hidden assemblies list if (assembly == nlogAssembly) { return null; } if (assembly == mscorlibAssembly) { return null; } if (assembly == systemAssembly) { return null; } return assembly; } /// <summary> /// Returns the classname from the provided StackFrame (If not from internal assembly) /// </summary> /// <param name="stackFrame"></param> /// <returns>Valid class name, or empty string if assembly was internal</returns> public static string LookupClassNameFromStackFrame(StackFrame stackFrame) { var method = StackTraceUsageUtils.GetStackMethod(stackFrame); if (method != null && LookupAssemblyFromStackFrame(stackFrame) != null) { string className = GetStackFrameMethodClassName(method, true, true, true); if (!string.IsNullOrEmpty(className)) { if (!className.StartsWith("System.", StringComparison.Ordinal)) return className; } else { className = method.Name ?? string.Empty; if (className != "lambda_method" && className != "MoveNext") return className; } } return string.Empty; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; #if !NET35 && !NET40 using System.Threading.Tasks; #endif /// <summary> /// Provides an interface to execute System.Actions without surfacing any exceptions raised for that action. /// </summary> public interface ISuppress { /// <summary> /// Runs the provided action. If the action throws, the exception is logged at <c>Error</c> level. The exception is not propagated outside of this method. /// </summary> /// <param name="action">Action to execute.</param> void Swallow(Action action); /// <summary> /// Runs the provided function and returns its result. If an exception is thrown, it is logged at <c>Error</c> level. /// The exception is not propagated outside of this method; a default value is returned instead. /// </summary> /// <typeparam name="T">Return type of the provided function.</typeparam> /// <param name="func">Function to run.</param> /// <returns>Result returned by the provided function or the default value of type <typeparamref name="T"/> in case of exception.</returns> T Swallow<T>(Func<T> func); /// <summary> /// Runs the provided function and returns its result. If an exception is thrown, it is logged at <c>Error</c> level. /// The exception is not propagated outside of this method; a fallback value is returned instead. /// </summary> /// <typeparam name="T">Return type of the provided function.</typeparam> /// <param name="func">Function to run.</param> /// <param name="fallback">Fallback value to return in case of exception.</param> /// <returns>Result returned by the provided function or fallback value in case of exception.</returns> T Swallow<T>(Func<T> func, T fallback); #if !NET35 && !NET40 /// <summary> /// Logs an exception is logged at <c>Error</c> level if the provided task does not run to completion. /// </summary> /// <param name="task">The task for which to log an error if it does not run to completion.</param> /// <remarks>This method is useful in fire-and-forget situations, where application logic does not depend on completion of task. This method is avoids C# warning CS4014 in such situations.</remarks> void Swallow(Task task); /// <summary> /// Returns a task that completes when a specified task to completes. If the task does not run to completion, an exception is logged at <c>Error</c> level. The returned task always runs to completion. /// </summary> /// <param name="task">The task for which to log an error if it does not run to completion.</param> /// <returns>A task that completes in the <see cref="TaskStatus.RanToCompletion"/> state when <paramref name="task"/> completes.</returns> Task SwallowAsync(Task task); /// <summary> /// Runs async action. If the action throws, the exception is logged at <c>Error</c> level. The exception is not propagated outside of this method. /// </summary> /// <param name="asyncAction">Async action to execute.</param> /// <returns>A task that completes in the <see cref="TaskStatus.RanToCompletion"/> state when <paramref name="asyncAction"/> completes.</returns> Task SwallowAsync(Func<Task> asyncAction); /// <summary> /// Runs the provided async function and returns its result. If the task does not run to completion, an exception is logged at <c>Error</c> level. /// The exception is not propagated outside of this method; a default value is returned instead. /// </summary> /// <typeparam name="TResult">Return type of the provided function.</typeparam> /// <param name="asyncFunc">Async function to run.</param> /// <returns>A task that represents the completion of the supplied task. If the supplied task ends in the <see cref="TaskStatus.RanToCompletion"/> state, the result of the new task will be the result of the supplied task; otherwise, the result of the new task will be the default value of type <typeparamref name="TResult"/>.</returns> Task<TResult> SwallowAsync<TResult>(Func<Task<TResult>> asyncFunc); /// <summary> /// Runs the provided async function and returns its result. If the task does not run to completion, an exception is logged at <c>Error</c> level. /// The exception is not propagated outside of this method; a fallback value is returned instead. /// </summary> /// <typeparam name="TResult">Return type of the provided function.</typeparam> /// <param name="asyncFunc">Async function to run.</param> /// <param name="fallback">Fallback value to return if the task does not end in the <see cref="TaskStatus.RanToCompletion"/> state.</param> /// <returns>A task that represents the completion of the supplied task. If the supplied task ends in the <see cref="TaskStatus.RanToCompletion"/> state, the result of the new task will be the result of the supplied task; otherwise, the result of the new task will be the fallback value.</returns> Task<TResult> SwallowAsync<TResult>(Func<Task<TResult>> asyncFunc, TResult fallback); #endif } } <file_sep>![NLog](https://raw.githubusercontent.com/NLog/NLog.github.io/master/images/NLog-logo-only_small.png) <!--[![Pre-release version](https://img.shields.io/nuget/vpre/NLog.svg)](https://www.nuget.org/packages/NLog)--> [![NuGet](https://img.shields.io/nuget/v/nlog.svg)](https://www.nuget.org/packages/NLog) [![Semantic Versioning](https://img.shields.io/badge/semver-2.0.0-3D9FE0.svg)](https://semver.org/) [![NuGet downloads](https://img.shields.io/nuget/dt/NLog.svg)](https://www.nuget.org/packages/NLog) <!--[![StackOverflow](https://img.shields.io/stackexchange/stackoverflow/t/nlog.svg?maxAge=2592000&label=stackoverflow)](https://stackoverflow.com/questions/tagged/nlog) --> [![](https://sonarcloud.io/api/project_badges/measure?project=nlog2&metric=ncloc&branch=dev)](https://sonarcloud.io/dashboard/?id=nlog2&branch=dev) [![](https://sonarcloud.io/api/project_badges/measure?project=nlog2&metric=bugs&branch=dev)](https://sonarcloud.io/dashboard/?id=nlog2&branch=dev) [![](https://sonarcloud.io/api/project_badges/measure?project=nlog2&metric=vulnerabilities&branch=dev)](https://sonarcloud.io/dashboard/?id=nlog2&branch=dev) [![](https://sonarcloud.io/api/project_badges/measure?project=nlog2&metric=code_smells&branch=dev)](https://sonarcloud.io/project/issues?id=nlog2&resolved=false&types=CODE_SMELL&branch=dev) [![](https://sonarcloud.io/api/project_badges/measure?project=nlog2&metric=duplicated_lines_density&branch=dev)](https://sonarcloud.io/component_measures/domain/Duplications?id=nlog2&branch=dev) [![](https://sonarcloud.io/api/project_badges/measure?project=nlog2&metric=sqale_debt_ratio&branch=dev)](https://sonarcloud.io/dashboard/?id=nlog2&branch=dev) [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=nlog2&metric=coverage&branch=dev)](https://sonarcloud.io/dashboard?id=nlog2&branch=dev) [![](https://img.shields.io/badge/Docs-GitHub%20wiki-brightgreen)](https://github.com/NLog/NLog/wiki) [![](https://img.shields.io/badge/Troubleshoot-Guide-orange)](https://github.com/nlog/nlog/wiki/Logging-troubleshooting) NLog is a free logging platform for .NET with rich log routing and management capabilities. It makes it easy to produce and manage high-quality logs for your application regardless of its size or complexity. It can process diagnostic messages emitted from any .NET language, augment them with contextual information, format them according to your preference and send them to one or more targets such as file or database. Major and minor releases will be posted on [project news](https://nlog-project.org/archives/). Getting started --- * [.NET Framework](https://github.com/NLog/NLog/wiki/Tutorial) * [ASP.NET Core](https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-6) * [.NET Core Console](https://github.com/NLog/NLog/wiki/Getting-started-with-.NET-Core-2---Console-application) For the possible options in the config, check the [Options list](https://nlog-project.org/config/) and [API Reference](https://nlog-project.org/documentation/) Having troubles? Check the [troubleshooting guide](https://github.com/NLog/NLog/wiki/Logging-troubleshooting) ----- ℹ️ NLog 5.0 Released! NLog 5.0 is finally here. See [List of major changes in NLog 5.0](https://nlog-project.org/2021/08/25/nlog-5-0-preview1-ready.html) NLog Packages --- The NLog-nuget-package provides everything needed for doing file- and console-logging. But there are also multiple NLog extension packages, that provides additional target- and layout-output. See [targets](https://nlog-project.org/config/?tab=targets) and [layout renderers](https://nlog-project.org/config/?tab=layout-renderers) overview! See Nuget/build status of all official packages [here](https://github.com/NLog/NLog/blob/dev/packages-and-status.md) Questions, bug reports or feature requests? --- Issues with getting it working? Please check the [troubleshooting guide](https://github.com/NLog/NLog/wiki/Logging-troubleshooting) before asking! With a clear error message, it's really easier to solve the issue! Unclear how to configure NLog correctly of other questions? Please post questions on [StackOverflow](https://stackoverflow.com/). Do you have feature request or would you like to report a bug? Please post them on the [issue list](https://github.com/NLog/NLog/issues) and follow [these guidelines](.github/CONTRIBUTING.md). Frequently Asked Questions (FAQ) --- See [FAQ on the Wiki](https://github.com/NLog/NLog/wiki/faq) Contributing --- As the current NLog team is a small team, we cannot fix every bug or implement every feature on our own. So contributions are really appreciated! If you like to start with a small task, then [up-for-grabs](https://github.com/NLog/NLog/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+label%3Aup-for-grabs+-label%3A%22almost+ready%22+) are nice to start with. Please note, we have a `dev` and `master` branch - `master` is for pure bug fixes and targets NLog 4.x - `dev` targets NLog 5 A good way to get started (flow) 1. Fork the NLog repos. 1. Create a new branch in you current repos from the 'dev' branch. (critical bugfixes from 'master') 1. 'Check out' the code with Git or [GitHub Desktop](https://desktop.github.com/) 1. Check [contributing.md](.github/CONTRIBUTING.md#sync-projects) 1. Push commits and create a Pull Request (PR) to NLog Please note: bugfixes should target the **master** branch, others the **dev** branch (NLog 5) License --- NLog is open source software, licensed under the terms of BSD license. See [LICENSE.txt](LICENSE.txt) for details. How to build --- Use Visual Studio 2019 and open the solution 'NLog.sln'. For building in the cloud we use: - AppVeyor for Windows- and Linux-builds - SonarQube for code coverage Trying to build your fork in the cloud? Check [this how-to](howto-build-your-fork.md) Note: master points to NLog 4.x and dev to NLog 5.x <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using NLog.Common; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class RetryingTargetWrapperTests : NLogTestBase { [Fact] public void RetryingTargetWrapperTest1() { var target = new MyTarget(); var wrapper = new RetryingTargetWrapper() { WrappedTarget = target, RetryCount = 10, RetryDelayMilliseconds = 1, }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new [] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), }; wrapper.WriteAsyncLogEvents(events); // make sure all events went through Assert.Equal(3, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Equal(events.Length, exceptions.Count); // make sure there were no exception foreach (var ex in exceptions) { Assert.Null(ex); } } [Fact] public void RetryingTargetWrapperTest2() { var target = new MyTarget() { ThrowExceptions = 6, }; var wrapper = new RetryingTargetWrapper() { WrappedTarget = target, RetryCount = 4, RetryDelayMilliseconds = 1, }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new [] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), }; var result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace); Assert.True(result.IndexOf("Error while writing to 'MyTarget([unnamed])'. Try 1/4") != -1); Assert.True(result.IndexOf("Error while writing to 'MyTarget([unnamed])'. Try 2/4") != -1); Assert.True(result.IndexOf("Error while writing to 'MyTarget([unnamed])'. Try 3/4") != -1); Assert.True(result.IndexOf("Error while writing to 'MyTarget([unnamed])'. Try 4/4") != -1); Assert.True(result.IndexOf("Too many retries. Aborting.") != -1); Assert.True(result.IndexOf("Error while writing to 'MyTarget([unnamed])'. Try 1/4") != -1); Assert.True(result.IndexOf("Error while writing to 'MyTarget([unnamed])'. Try 2/4") != -1); // first event does not get to wrapped target because of too many attempts. // second event gets there in 3rd retry // and third event gets there immediately Assert.Equal(2, target.Events.Count); Assert.Same(events[1].LogEvent, target.Events[0]); Assert.Same(events[2].LogEvent, target.Events[1]); Assert.Equal(events.Length, exceptions.Count); Assert.NotNull(exceptions[0]); Assert.Equal("Some exception has occurred.", exceptions[0].Message); Assert.Null(exceptions[1]); Assert.Null(exceptions[2]); } #if MONO [Fact(Skip="Not working under MONO - Premature abort seems to fail, and instead it just waits until finished")] #else [Fact] #endif public void RetryingTargetWrapperBlockingCloseTest() { RetryingIntegrationTest(3, () => { var target = new MyTarget() { ThrowExceptions = 5, }; var wrapper = new RetryingTargetWrapper() { WrappedTarget = target, RetryCount = 10, RetryDelayMilliseconds = 5000, }; var asyncWrapper = new AsyncTargetWrapper(wrapper) {TimeToSleepBetweenBatches = 1}; asyncWrapper.Initialize(null); wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), }; // Attempt to write LogEvents that will take forever to retry asyncWrapper.WriteAsyncLogEvents(events); // Wait a little for the AsyncWrapper to start writing System.Threading.Thread.Sleep(50); // Close down the AsyncWrapper while busy writing asyncWrapper.Close(); // Close down the RetryingWrapper while busy retrying wrapper.Close(); // Close down the actual target while busy writing target.Close(); // Wait a little for the RetryingWrapper to detect that it has been closed down System.Threading.Thread.Sleep(200); // The premature abort, causes the exception to be logged Assert.NotNull(exceptions[0]); }); } [Fact] public void RetryingTargetWrapperBatchingTest() { var target = new MyTarget() { ThrowExceptions = 3, }; var retryWrapper = new RetryingTargetWrapper() { WrappedTarget = target, RetryCount = 2, RetryDelayMilliseconds = 10, EnableBatchWrite = true, }; var asyncWrapper = new AsyncTargetWrapper(retryWrapper) { TimeToSleepBetweenBatches = 5000 }; var logFactory = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(asyncWrapper); }).LogFactory; // Verify that RetryingTargetWrapper is not sleeping for every LogEvent in single batch var stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); var logger = logFactory.GetCurrentClassLogger(); for (int i = 1; i <= 500; ++i) logger.Info("Test {0}", i); logFactory.Flush(); Assert.Equal(1, target.WriteBatchCount); for (int i = 0; i < 5000; ++i) { if (target.Events.Count >= 495) break; System.Threading.Thread.Sleep(1); } Assert.Equal(1, target.WriteBatchCount); Assert.InRange(target.Events.Count, 495, 500); Assert.InRange(stopWatch.ElapsedMilliseconds, 0, 3000); } public class MyTarget : Target { public MyTarget() { Events = new List<LogEventInfo>(); } public MyTarget(string name) : this() { Name = name; } public List<LogEventInfo> Events { get; private set; } public int ThrowExceptions { get; set; } public int WriteBatchCount { get; private set; } protected override void Write(IList<AsyncLogEventInfo> logEvents) { if (logEvents.Count > 1) { ++WriteBatchCount; if (ThrowExceptions-- > 0) { for (int i = 0; i < logEvents.Count; ++i) logEvents[i].Continuation(new ApplicationException("Some exception has occurred.")); return; } } base.Write(logEvents); } protected override void Write(AsyncLogEventInfo logEvent) { if (ThrowExceptions-- > 0) { logEvent.Continuation(new ApplicationException("Some exception has occurred.")); return; } Events.Add(logEvent.LogEvent); logEvent.Continuation(null); } protected override void Write(LogEventInfo logEvent) { } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Text; using NLog.Config; using NLog.Internal; /// <summary> /// Renders the assembly version information for the entry assembly or a named assembly. /// </summary> /// <remarks> /// As this layout renderer uses reflection and version information is unlikely to change during application execution, /// it is recommended to use it in conjunction with the <see cref="NLog.LayoutRenderers.Wrappers.CachedLayoutRendererWrapper"/>. /// </remarks> /// <remarks> /// The entry assembly can't be found in some cases e.g. ASP.NET, unit tests, etc. /// </remarks> [LayoutRenderer("assembly-version")] [ThreadAgnostic] public class AssemblyVersionLayoutRenderer : LayoutRenderer { /// <summary> /// The (full) name of the assembly. If <c>null</c>, using the entry assembly. /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultParameter] public string Name { get; set; } /// <summary> /// Gets or sets the type of assembly version to retrieve. /// </summary> /// <remarks> /// Some version type and platform combinations are not fully supported. /// - UWP earlier than .NET Standard 1.5: Value for <see cref="AssemblyVersionType.Assembly"/> is always returned unless the <see cref="Name"/> parameter is specified. /// </remarks> /// <docgen category='Layout Options' order='10' /> public AssemblyVersionType Type { get; set; } = AssemblyVersionType.Assembly; ///<summary> /// The default value to render if the Version is not available ///</summary> /// <docgen category='Layout Options' order='10' /> public string Default { get => _default ?? GenerateDefaultValue(); set => _default = value; } private string _default; /// <summary> /// Gets or sets the custom format of the assembly version output. /// </summary> /// <remarks> /// Supported placeholders are 'major', 'minor', 'build' and 'revision'. /// The default .NET template for version numbers is 'major.minor.build.revision'. See /// https://docs.microsoft.com/en-gb/dotnet/api/system.version?view=netframework-4.7.2#remarks /// for details. /// </remarks> /// <docgen category='Layout Options' order='10' /> public string Format { get => _format; set => _format = value?.ToLowerInvariant() ?? string.Empty; } private string _format = DefaultFormat; private const string DefaultFormat = "major.minor.build.revision"; /// <inheritdoc/> protected override void InitializeLayoutRenderer() { _assemblyVersion = null; base.InitializeLayoutRenderer(); } /// <inheritdoc/> protected override void CloseLayoutRenderer() { _assemblyVersion = null; base.CloseLayoutRenderer(); } private string _assemblyVersion; /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { var version = _assemblyVersion ?? (_assemblyVersion = ApplyFormatToVersion(GetVersion())); if (version is null) version = GenerateDefaultValue(); builder.Append(version); } private string ApplyFormatToVersion(string version) { if (version is null) { return _default; } else if (StringHelpers.IsNullOrWhiteSpace(version)) { return _default ?? GenerateDefaultValue(); } else if (version == "0.0.0.0" && _default != null) { return _default; } if (Format.Equals(DefaultFormat, StringComparison.OrdinalIgnoreCase) || string.IsNullOrEmpty(version)) { return version; } var versionParts = version.SplitAndTrimTokens('.'); version = Format.Replace("major", versionParts[0]) .Replace("minor", versionParts.Length > 1 ? versionParts[1] : "0") .Replace("build", versionParts.Length > 2 ? versionParts[2] : "0") .Replace("revision", versionParts.Length > 3 ? versionParts[3] : "0"); return version; } private string GenerateDefaultValue() { return $"Could not find value for {(string.IsNullOrEmpty(Name) ? "entry" : Name)} assembly and version type {Type}"; } private string GetVersion() { try { var assembly = GetAssembly(); switch (Type) { case AssemblyVersionType.File: return assembly?.GetFirstCustomAttribute<System.Reflection.AssemblyFileVersionAttribute>()?.Version; case AssemblyVersionType.Informational: return assembly?.GetFirstCustomAttribute<System.Reflection.AssemblyInformationalVersionAttribute>()?.InformationalVersion; default: return assembly?.GetName().Version?.ToString(); } } catch (Exception ex) { NLog.Common.InternalLogger.Warn(ex, "${assembly-version} - Failed to load assembly {0}", Name); if (ex.MustBeRethrown()) throw; return null; } } /// <summary> /// Gets the assembly specified by <see cref="Name"/>, or entry assembly otherwise /// </summary> protected virtual System.Reflection.Assembly GetAssembly() { if (string.IsNullOrEmpty(Name)) { #if !NETSTANDARD1_3 return System.Reflection.Assembly.GetEntryAssembly(); #else return null; #endif } else { return System.Reflection.Assembly.Load(new System.Reflection.AssemblyName(Name)); } } } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.SessionState; using NLog.Targets.Wrappers; using NLog.Targets; using NLog.Config; using NLog; namespace ASPNetBufferingWrapper { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { FileTarget fileTarget = new FileTarget(); fileTarget.FileName = "${basedir}/logfile.txt"; PostFilteringTargetWrapper postfilteringTarget = new PostFilteringTargetWrapper(); ASPNetBufferingTargetWrapper aspnetBufferingTarget = new ASPNetBufferingTargetWrapper(); aspnetBufferingTarget.WrappedTarget = postfilteringTarget; postfilteringTarget.WrappedTarget = fileTarget; postfilteringTarget.DefaultFilter = "level >= LogLevel.Info"; FilteringRule rule = new FilteringRule(); rule.Exists = "level >= LogLevel.Warn"; rule.Filter = "level >= LogLevel.Debug"; postfilteringTarget.Rules.Add(rule); SimpleConfigurator.ConfigureForTargetLogging(aspnetBufferingTarget, LogLevel.Debug); } protected void Application_End(object sender, EventArgs e) { } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.Collections.Generic; using System.ComponentModel; #if !NET35 && !NET40 using System.Threading.Tasks; #endif using JetBrains.Annotations; using NLog.Internal; /// <summary> /// Provides logging interface and utility functions. /// </summary> [CLSCompliant(true)] public partial class Logger : ILogger { internal static readonly Type DefaultLoggerType = typeof(Logger); private TargetWithFilterChain[] _targetsByLevel = TargetWithFilterChain.NoTargetsByLevel; private Logger _contextLogger; private ThreadSafeDictionary<string, object> _contextProperties; private volatile bool _isTraceEnabled; private volatile bool _isDebugEnabled; private volatile bool _isInfoEnabled; private volatile bool _isWarnEnabled; private volatile bool _isErrorEnabled; private volatile bool _isFatalEnabled; /// <summary> /// Initializes a new instance of the <see cref="Logger"/> class. /// </summary> protected internal Logger() { _contextLogger = this; } /// <summary> /// Occurs when logger configuration changes. /// </summary> public event EventHandler<EventArgs> LoggerReconfigured; /// <summary> /// Gets the name of the logger. /// </summary> public string Name { get; private set; } /// <summary> /// Gets the factory that created this logger. /// </summary> public LogFactory Factory { get; private set; } /// <summary> /// Collection of context properties for the Logger. The logger will append it for all log events /// </summary> /// <remarks> /// It is recommended to use <see cref="WithProperty(string, object)"/> for modifying context properties /// when same named logger is used at multiple locations or shared by different thread contexts. /// </remarks> public IDictionary<string, object> Properties => _contextProperties ?? System.Threading.Interlocked.CompareExchange(ref _contextProperties, CreateContextPropertiesDictionary(null), null) ?? _contextProperties; /// <summary> /// Gets a value indicating whether logging is enabled for the specified level. /// </summary> /// <param name="level">Log level to be checked.</param> /// <returns>A value of <see langword="true" /> if logging is enabled for the specified level, otherwise it returns <see langword="false" />.</returns> public bool IsEnabled(LogLevel level) { return GetTargetsForLevelSafe(level) != null; } /// <summary> /// Creates new logger that automatically appends the specified property to all log events (without changing current logger) /// /// With <see cref="Properties"/> property, all properties can be enumerated. /// </summary> /// <param name="propertyKey">Property Name</param> /// <param name="propertyValue">Property Value</param> /// <returns>New Logger object that automatically appends specified property</returns> public Logger WithProperty(string propertyKey, object propertyValue) { if (string.IsNullOrEmpty(propertyKey)) throw new ArgumentException(nameof(propertyKey)); Logger newLogger = CreateChildLogger(); newLogger._contextProperties[propertyKey] = propertyValue; return newLogger; } /// <summary> /// Creates new logger that automatically appends the specified properties to all log events (without changing current logger) /// /// With <see cref="Properties"/> property, all properties can be enumerated. /// </summary> /// <param name="properties">Collection of key-value pair properties</param> /// <returns>New Logger object that automatically appends specified properties</returns> public Logger WithProperties(IEnumerable<KeyValuePair<string, object>> properties) { Guard.ThrowIfNull(properties); Logger newLogger = CreateChildLogger(); foreach (KeyValuePair<string, object> property in properties) { newLogger._contextProperties[property.Key] = property.Value; } return newLogger; } /// <summary> /// Updates the specified context property for the current logger. The logger will append it for all log events. /// /// With <see cref="Properties"/> property, all properties can be enumerated (or updated). /// </summary> /// <remarks> /// It is highly recommended to ONLY use <see cref="WithProperty(string, object)"/> for modifying context properties. /// This method will affect all locations/contexts that makes use of the same named logger object. And can cause /// unexpected surprises at multiple locations and other thread contexts. /// </remarks> /// <param name="propertyKey">Property Name</param> /// <param name="propertyValue">Property Value</param> [Obsolete("Instead use WithProperty which is safe. If really necessary then one can use Properties-property. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public void SetProperty(string propertyKey, object propertyValue) { if (string.IsNullOrEmpty(propertyKey)) throw new ArgumentException(nameof(propertyKey)); Properties[propertyKey] = propertyValue; } private static ThreadSafeDictionary<string, object> CreateContextPropertiesDictionary(ThreadSafeDictionary<string, object> contextProperties) { contextProperties = contextProperties != null ? new ThreadSafeDictionary<string, object>(contextProperties) : new ThreadSafeDictionary<string, object>(); return contextProperties; } /// <summary> /// Updates the <see cref="ScopeContext"/> with provided property /// </summary> /// <param name="propertyName">Name of property</param> /// <param name="propertyValue">Value of property</param> /// <returns>A disposable object that removes the properties from logical context scope on dispose.</returns> /// <remarks><see cref="ScopeContext"/> property-dictionary-keys are case-insensitive</remarks> public IDisposable PushScopeProperty(string propertyName, object propertyValue) { return ScopeContext.PushProperty(propertyName, propertyValue); } /// <summary> /// Updates the <see cref="ScopeContext"/> with provided property /// </summary> /// <param name="propertyName">Name of property</param> /// <param name="propertyValue">Value of property</param> /// <returns>A disposable object that removes the properties from logical context scope on dispose.</returns> /// <remarks><see cref="ScopeContext"/> property-dictionary-keys are case-insensitive</remarks> public IDisposable PushScopeProperty<TValue>(string propertyName, TValue propertyValue) { return ScopeContext.PushProperty(propertyName, propertyValue); } #if !NET35 && !NET40 /// <summary> /// Updates the <see cref="ScopeContext"/> with provided properties /// </summary> /// <param name="scopeProperties">Properties being added to the scope dictionary</param> /// <returns>A disposable object that removes the properties from logical context scope on dispose.</returns> /// <remarks><see cref="ScopeContext"/> property-dictionary-keys are case-insensitive</remarks> public IDisposable PushScopeProperties(IReadOnlyCollection<KeyValuePair<string, object>> scopeProperties) { return ScopeContext.PushProperties(scopeProperties); } /// <summary> /// Updates the <see cref="ScopeContext"/> with provided properties /// </summary> /// <param name="scopeProperties">Properties being added to the scope dictionary</param> /// <returns>A disposable object that removes the properties from logical context scope on dispose.</returns> /// <remarks><see cref="ScopeContext"/> property-dictionary-keys are case-insensitive</remarks> public IDisposable PushScopeProperties<TValue>(IReadOnlyCollection<KeyValuePair<string, TValue>> scopeProperties) { return ScopeContext.PushProperties(scopeProperties); } #endif /// <summary> /// Pushes new state on the logical context scope stack /// </summary> /// <param name="nestedState">Value to added to the scope stack</param> /// <returns>A disposable object that pops the nested scope state on dispose.</returns> public IDisposable PushScopeNested<T>(T nestedState) { return ScopeContext.PushNestedState(nestedState); } /// <summary> /// Pushes new state on the logical context scope stack /// </summary> /// <param name="nestedState">Value to added to the scope stack</param> /// <returns>A disposable object that pops the nested scope state on dispose.</returns> public IDisposable PushScopeNested(object nestedState) { return ScopeContext.PushNestedState(nestedState); } /// <summary> /// Writes the specified diagnostic message. /// </summary> /// <param name="logEvent">Log event.</param> public void Log(LogEventInfo logEvent) { var targetsForLevel = GetTargetsForLevelSafe(logEvent.Level); if (targetsForLevel != null) { if (logEvent.LoggerName is null) logEvent.LoggerName = Name; if (logEvent.FormatProvider is null) logEvent.FormatProvider = Factory.DefaultCultureInfo; WriteToTargets(logEvent, targetsForLevel); } } /// <summary> /// Writes the specified diagnostic message. /// </summary> /// <param name="wrapperType">Type of custom Logger wrapper.</param> /// <param name="logEvent">Log event.</param> public void Log(Type wrapperType, LogEventInfo logEvent) { var targetsForLevel = GetTargetsForLevelSafe(logEvent.Level); if (targetsForLevel != null) { if (logEvent.LoggerName is null) logEvent.LoggerName = Name; if (logEvent.FormatProvider is null) logEvent.FormatProvider = Factory.DefaultCultureInfo; WriteToTargets(wrapperType, logEvent, targetsForLevel); } } #region Log() overloads /// <overloads> /// Writes the diagnostic message at the specified level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="level">The log level.</param> /// <param name="value">The value to be written.</param> public void Log<T>(LogLevel level, T value) { if (IsEnabled(level)) { WriteToTargets(level, Factory.DefaultCultureInfo, value); } } /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> public void Log<T>(LogLevel level, IFormatProvider formatProvider, T value) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, value); } } /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> public void Log(LogLevel level, LogMessageGenerator messageFunc) { if (IsEnabled(level)) { Guard.ThrowIfNull(messageFunc); WriteToTargets(level, messageFunc()); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters and formatting them with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, args); } } /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">Log message.</param> public void Log(LogLevel level, [Localizable(false)] string message) { if (IsEnabled(level)) { WriteToTargets(level, message); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { if (IsEnabled(level)) { WriteToTargets(level, message, args); } } /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, Exception exception, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { if (IsEnabled(level)) { WriteToTargets(level, exception, message, args); } } /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, Exception exception, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { if (IsEnabled(level)) { WriteToTargets(level, exception, formatProvider, message, args); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified parameter and formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] public void Log<TArgument>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified parameter. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] public void Log<TArgument>(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, TArgument argument) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] public void Log<TArgument1, TArgument2>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument1, argument2 }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] public void Log<TArgument1, TArgument2>(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument1, argument2 }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] public void Log<TArgument1, TArgument2, TArgument3>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[] { argument1, argument2, argument3 }); } } /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] public void Log<TArgument1, TArgument2, TArgument3>(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3) { if (IsEnabled(level)) { WriteToTargets(level, message, new object[] { argument1, argument2, argument3 }); } } private LogEventInfo PrepareLogEventInfo(LogEventInfo logEvent) { if (_contextProperties != null) { foreach (var property in _contextProperties) { if (!logEvent.Properties.ContainsKey(property.Key)) { logEvent.Properties[property.Key] = property.Value; } } } return logEvent; } #endregion /// <summary> /// Runs the provided action. If the action throws, the exception is logged at <c>Error</c> level. The exception is not propagated outside of this method. /// </summary> /// <param name="action">Action to execute.</param> public void Swallow(Action action) { try { action(); } catch (Exception e) { Error(e); } } /// <summary> /// Runs the provided function and returns its result. If an exception is thrown, it is logged at <c>Error</c> level. /// The exception is not propagated outside of this method; a default value is returned instead. /// </summary> /// <typeparam name="T">Return type of the provided function.</typeparam> /// <param name="func">Function to run.</param> /// <returns>Result returned by the provided function or the default value of type <typeparamref name="T"/> in case of exception.</returns> public T Swallow<T>(Func<T> func) { return Swallow(func, default(T)); } /// <summary> /// Runs the provided function and returns its result. If an exception is thrown, it is logged at <c>Error</c> level. /// The exception is not propagated outside of this method; a fallback value is returned instead. /// </summary> /// <typeparam name="T">Return type of the provided function.</typeparam> /// <param name="func">Function to run.</param> /// <param name="fallback">Fallback value to return in case of exception.</param> /// <returns>Result returned by the provided function or fallback value in case of exception.</returns> public T Swallow<T>(Func<T> func, T fallback) { try { return func(); } catch (Exception e) { Error(e); return fallback; } } #if !NET35 && !NET40 /// <summary> /// Logs an exception is logged at <c>Error</c> level if the provided task does not run to completion. /// </summary> /// <param name="task">The task for which to log an error if it does not run to completion.</param> /// <remarks>This method is useful in fire-and-forget situations, where application logic does not depend on completion of task. This method is avoids C# warning CS4014 in such situations.</remarks> public async void Swallow(Task task) { try { await task.ConfigureAwait(false); } catch (Exception e) { Error(e); } } /// <summary> /// Returns a task that completes when a specified task to completes. If the task does not run to completion, an exception is logged at <c>Error</c> level. The returned task always runs to completion. /// </summary> /// <param name="task">The task for which to log an error if it does not run to completion.</param> /// <returns>A task that completes in the <see cref="TaskStatus.RanToCompletion"/> state when <paramref name="task"/> completes.</returns> public async Task SwallowAsync(Task task) { try { await task.ConfigureAwait(false); } catch (Exception e) { Error(e); } } /// <summary> /// Runs async action. If the action throws, the exception is logged at <c>Error</c> level. The exception is not propagated outside of this method. /// </summary> /// <param name="asyncAction">Async action to execute.</param> public async Task SwallowAsync(Func<Task> asyncAction) { try { await asyncAction().ConfigureAwait(false); } catch (Exception e) { Error(e); } } /// <summary> /// Runs the provided async function and returns its result. If the task does not run to completion, an exception is logged at <c>Error</c> level. /// The exception is not propagated outside of this method; a default value is returned instead. /// </summary> /// <typeparam name="TResult">Return type of the provided function.</typeparam> /// <param name="asyncFunc">Async function to run.</param> /// <returns>A task that represents the completion of the supplied task. If the supplied task ends in the <see cref="TaskStatus.RanToCompletion"/> state, the result of the new task will be the result of the supplied task; otherwise, the result of the new task will be the default value of type <typeparamref name="TResult"/>.</returns> public async Task<TResult> SwallowAsync<TResult>(Func<Task<TResult>> asyncFunc) { return await SwallowAsync(asyncFunc, default(TResult)).ConfigureAwait(false); } /// <summary> /// Runs the provided async function and returns its result. If the task does not run to completion, an exception is logged at <c>Error</c> level. /// The exception is not propagated outside of this method; a fallback value is returned instead. /// </summary> /// <typeparam name="TResult">Return type of the provided function.</typeparam> /// <param name="asyncFunc">Async function to run.</param> /// <param name="fallback">Fallback value to return if the task does not end in the <see cref="TaskStatus.RanToCompletion"/> state.</param> /// <returns>A task that represents the completion of the supplied task. If the supplied task ends in the <see cref="TaskStatus.RanToCompletion"/> state, the result of the new task will be the result of the supplied task; otherwise, the result of the new task will be the fallback value.</returns> public async Task<TResult> SwallowAsync<TResult>(Func<Task<TResult>> asyncFunc, TResult fallback) { try { return await asyncFunc().ConfigureAwait(false); } catch (Exception e) { Error(e); return fallback; } } #endif internal void Initialize(string name, TargetWithFilterChain[] targetsByLevel, LogFactory factory) { Name = name; Factory = factory; SetConfiguration(targetsByLevel); } private void WriteToTargets(LogLevel level, string message, object[] args) { WriteToTargets(level, Factory.DefaultCultureInfo, message, args); } private void WriteToTargets(LogLevel level, IFormatProvider formatProvider, string message, object[] args) { var targetsForLevel = GetTargetsForLevel(level); if (targetsForLevel != null) { var logEvent = LogEventInfo.Create(level, Name, formatProvider, message, args); WriteToTargets(logEvent, targetsForLevel); } } private void WriteToTargets(LogLevel level, string message) { var targetsForLevel = GetTargetsForLevel(level); if (targetsForLevel != null) { // please note that this overload calls the overload of LogEventInfo.Create with object[] parameter on purpose - // to avoid unnecessary string.Format (in case of calling Create(LogLevel, string, IFormatProvider, object)) var logEvent = LogEventInfo.Create(level, Name, Factory.DefaultCultureInfo, message, (object[])null); WriteToTargets(logEvent, targetsForLevel); } } private void WriteToTargets<T>(LogLevel level, IFormatProvider formatProvider, T value) { var targetsForLevel = GetTargetsForLevel(level); if (targetsForLevel != null) { var logEvent = LogEventInfo.Create(level, Name, formatProvider, value); WriteToTargets(logEvent, targetsForLevel); } } private void WriteToTargets(LogLevel level, Exception ex, string message, object[] args) { var targetsForLevel = GetTargetsForLevel(level); if (targetsForLevel != null) { // Translate Exception with missing LogEvent message as log single value var logEvent = message is null && ex != null && !(args?.Length > 0) ? LogEventInfo.Create(level, Name, ExceptionMessageFormatProvider.Instance, ex) : LogEventInfo.Create(level, Name, ex, Factory.DefaultCultureInfo, message, args); WriteToTargets(logEvent, targetsForLevel); } } private void WriteToTargets(LogLevel level, Exception ex, IFormatProvider formatProvider, string message, object[] args) { var targetsForLevel = GetTargetsForLevel(level); if (targetsForLevel != null) { var logEvent = LogEventInfo.Create(level, Name, ex, formatProvider, message, args); WriteToTargets(logEvent, targetsForLevel); } } private void WriteToTargets([NotNull] LogEventInfo logEvent, [NotNull] TargetWithFilterChain targetsForLevel) { try { LoggerImpl.Write(DefaultLoggerType, targetsForLevel, PrepareLogEventInfo(logEvent), Factory); } catch (Exception ex) { #if DEBUG if (ex.MustBeRethrownImmediately()) throw; // Throwing exceptions here might crash the entire application (.NET 2.0 behavior) #endif if (Factory.ThrowExceptions || LogManager.ThrowExceptions) throw; Common.InternalLogger.Error(ex, "Failed to write LogEvent"); } } private void WriteToTargets(Type wrapperType, [NotNull] LogEventInfo logEvent, [NotNull] TargetWithFilterChain targetsForLevel) { try { LoggerImpl.Write(wrapperType ?? DefaultLoggerType, targetsForLevel, PrepareLogEventInfo(logEvent), Factory); } catch (Exception ex) { #if DEBUG if (ex.MustBeRethrownImmediately()) throw; // Throwing exceptions here might crash the entire application (.NET 2.0 behavior) #endif if (Factory.ThrowExceptions || LogManager.ThrowExceptions) throw; Common.InternalLogger.Error(ex, "Failed to write LogEvent"); } } internal void SetConfiguration(TargetWithFilterChain[] targetsByLevel) { _targetsByLevel = targetsByLevel; // pre-calculate 'enabled' flags _isTraceEnabled = IsEnabled(LogLevel.Trace); _isDebugEnabled = IsEnabled(LogLevel.Debug); _isInfoEnabled = IsEnabled(LogLevel.Info); _isWarnEnabled = IsEnabled(LogLevel.Warn); _isErrorEnabled = IsEnabled(LogLevel.Error); _isFatalEnabled = IsEnabled(LogLevel.Fatal); OnLoggerReconfigured(EventArgs.Empty); } private TargetWithFilterChain GetTargetsForLevelSafe(LogLevel level) { if (level is null) { throw new InvalidOperationException("Log level must be defined"); } return GetTargetsForLevel(level); } private TargetWithFilterChain GetTargetsForLevel(LogLevel level) { if (ReferenceEquals(_contextLogger, this)) return _targetsByLevel[level.Ordinal]; else return _contextLogger.GetTargetsForLevel(level); // Use the GetTargetsForLevel() of the parent Logger } /// <summary> /// Raises the event when the logger is reconfigured. /// </summary> /// <param name="e">Event arguments</param> protected virtual void OnLoggerReconfigured(EventArgs e) { LoggerReconfigured?.Invoke(this, e); } private Logger CreateChildLogger() { Logger newLogger = (Logger)MemberwiseClone(); newLogger.Initialize(Name, _targetsByLevel, Factory); newLogger._contextProperties = CreateContextPropertiesDictionary(_contextProperties); newLogger._contextLogger = _contextLogger; // Use the GetTargetsForLevel() of the parent Logger return newLogger; } } } <file_sep>using NLog; var consoleWriter = new StringWriter(); var orgConsole = System.Console.Out; try { System.Console.SetOut(consoleWriter); NLog.LogManager.ThrowExceptions = true; // unit-test-mode var logger = NLog.LogManager.Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target type='console' name='console' layout='${threadid}|${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='console' /> </rules> </nlog> ").GetCurrentClassLogger(); logger.Debug("Almost ready"); logger.Info("Success"); NLog.LogManager.Shutdown(); logger.Debug("Almost done"); } catch (Exception ex) { System.Console.SetOut(orgConsole); Console.WriteLine(ex.ToString()); throw; } finally { System.Console.SetOut(orgConsole); } var result = consoleWriter.ToString(); Console.WriteLine(result); if (result == $"{Environment.CurrentManagedThreadId}|Success{System.Environment.NewLine}") return 0; else return -1;<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.ComponentModel; using System.Globalization; using JetBrains.Annotations; using NLog.Internal; namespace NLog.Targets { /// <summary> /// Line ending mode. /// </summary> [TypeConverter(typeof(LineEndingModeConverter))] public sealed class LineEndingMode : IEquatable<LineEndingMode> { /// <summary> /// Insert platform-dependent end-of-line sequence after each line. /// </summary> public static readonly LineEndingMode Default = new LineEndingMode("Default", EnvironmentHelper.NewLine); /// <summary> /// Insert CR LF sequence (ASCII 13, ASCII 10) after each line. /// </summary> public static readonly LineEndingMode CRLF = new LineEndingMode("CRLF", "\r\n"); /// <summary> /// Insert CR character (ASCII 13) after each line. /// </summary> public static readonly LineEndingMode CR = new LineEndingMode("CR", "\r"); /// <summary> /// Insert LF character (ASCII 10) after each line. /// </summary> public static readonly LineEndingMode LF = new LineEndingMode("LF", "\n"); /// <summary> /// Insert null terminator (ASCII 0) after each line. /// </summary> public static readonly LineEndingMode Null = new LineEndingMode("Null", "\0"); /// <summary> /// Do not insert any line ending. /// </summary> public static readonly LineEndingMode None = new LineEndingMode("None", string.Empty); private readonly string _name; private readonly string _newLineCharacters; /// <summary> /// Gets the name of the LineEndingMode instance. /// </summary> public string Name => _name; /// <summary> /// Gets the new line characters (value) of the LineEndingMode instance. /// </summary> public string NewLineCharacters => _newLineCharacters; private LineEndingMode() { } /// <summary> /// Initializes a new instance of <see cref="LogLevel"/>. /// </summary> /// <param name="name">The mode name.</param> /// <param name="newLineCharacters">The new line characters to be used.</param> private LineEndingMode(string name, string newLineCharacters) { _name = name; _newLineCharacters = newLineCharacters; } /// <summary> /// Returns the <see cref="LineEndingMode"/> that corresponds to the supplied <paramref name="name"/>. /// </summary> /// <param name="name"> /// The textual representation of the line ending mode, such as CRLF, LF, Default etc. /// Name is not case sensitive. /// </param> /// <returns>The <see cref="LineEndingMode"/> value, that corresponds to the <paramref name="name"/>.</returns> /// <exception cref="ArgumentOutOfRangeException">There is no line ending mode with the specified name.</exception> public static LineEndingMode FromString([NotNull] string name) { Guard.ThrowIfNull(name); if (name.Equals(CRLF.Name, StringComparison.OrdinalIgnoreCase)) return CRLF; if (name.Equals(LF.Name, StringComparison.OrdinalIgnoreCase)) return LF; if (name.Equals(CR.Name, StringComparison.OrdinalIgnoreCase)) return CR; if (name.Equals(Default.Name, StringComparison.OrdinalIgnoreCase)) return Default; if (name.Equals(Null.Name, StringComparison.OrdinalIgnoreCase)) return Null; if (name.Equals(None.Name, StringComparison.OrdinalIgnoreCase)) return None; throw new ArgumentOutOfRangeException(nameof(name), name, "LineEndingMode is out of range"); } /// <summary> /// Compares two <see cref="LineEndingMode"/> objects and returns a /// value indicating whether the first one is equal to the second one. /// </summary> /// <param name="mode1">The first level.</param> /// <param name="mode2">The second level.</param> /// <returns>The value of <c>mode1.NewLineCharacters == mode2.NewLineCharacters</c>.</returns> public static bool operator ==(LineEndingMode mode1, LineEndingMode mode2) { if (mode1 is null) { return mode2 is null; } if (mode2 is null) { return false; } return mode1.NewLineCharacters == mode2.NewLineCharacters; } /// <summary> /// Compares two <see cref="LineEndingMode"/> objects and returns a /// value indicating whether the first one is not equal to the second one. /// </summary> /// <param name="mode1">The first mode</param> /// <param name="mode2">The second mode</param> /// <returns>The value of <c>mode1.NewLineCharacters != mode2.NewLineCharacters</c>.</returns> public static bool operator !=(LineEndingMode mode1, LineEndingMode mode2) { if (mode1 is null) { return !(mode2 is null); } if (mode2 is null) { return true; } return mode1.NewLineCharacters != mode2.NewLineCharacters; } /// <inheritdoc/> public override string ToString() { return Name; } /// <inheritdoc/> public override int GetHashCode() { return _newLineCharacters?.GetHashCode() ?? 0; } /// <inheritdoc/> public override bool Equals(object obj) { return obj is LineEndingMode mode && Equals(mode); } /// <summary>Indicates whether the current object is equal to another object of the same type.</summary> /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns> /// <param name="other">An object to compare with this object.</param> public bool Equals(LineEndingMode other) { return ReferenceEquals(this, other) || string.Equals(_newLineCharacters, other?._newLineCharacters, StringComparison.Ordinal); } /// <summary> /// Provides a type converter to convert <see cref="LineEndingMode"/> objects to and from other representations. /// </summary> public class LineEndingModeConverter : TypeConverter { /// <inheritdoc/> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } /// <inheritdoc/> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { var name = value as string; return name != null ? FromString(name) : base.ConvertFrom(context, culture, value); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using NLog.Internal; using NLog.Targets; /// <summary> /// Provides simple programmatic configuration API used for trivial logging cases. /// /// Warning, these methods will overwrite the current config. /// </summary> [Obsolete("Use LogManager.Setup().LoadConfiguration() instead. Marked obsolete on NLog 5.2")] public static class SimpleConfigurator { #if !NETSTANDARD1_3 /// <summary> /// Configures NLog for console logging so that all messages above and including /// the <see cref="NLog.LogLevel.Info"/> level are output to the console. /// </summary> [Obsolete("Use LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteToConsole()) instead. Marked obsolete on NLog 5.2")] public static void ConfigureForConsoleLogging() { ConfigureForConsoleLogging(LogLevel.Info); } /// <summary> /// Configures NLog for console logging so that all messages above and including /// the specified level are output to the console. /// </summary> /// <param name="minLevel">The minimal logging level.</param> [Obsolete("Use LogManager.Setup().LoadConfiguration(c => c.ForLogger(minLevel).WriteToConsole()) instead. Marked obsolete on NLog 5.2")] public static void ConfigureForConsoleLogging(LogLevel minLevel) { ConsoleTarget consoleTarget = new ConsoleTarget(); LoggingConfiguration config = new LoggingConfiguration(); config.AddRule(minLevel, LogLevel.MaxLevel, consoleTarget, "*"); LogManager.Configuration = config; } #endif /// <summary> /// Configures NLog for to log to the specified target so that all messages /// above and including the <see cref="NLog.LogLevel.Info"/> level are output. /// </summary> /// <param name="target">The target to log all messages to.</param> [Obsolete("Use LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(target)) instead. Marked obsolete on NLog 5.2")] public static void ConfigureForTargetLogging(Target target) { Guard.ThrowIfNull(target); ConfigureForTargetLogging(target, LogLevel.Info); } /// <summary> /// Configures NLog for to log to the specified target so that all messages /// above and including the specified level are output. /// </summary> /// <param name="target">The target to log all messages to.</param> /// <param name="minLevel">The minimal logging level.</param> [Obsolete("Use LogManager.Setup().LoadConfiguration(c => c.ForLogger(minLevel).WriteTo(target)) instead. Marked obsolete on NLog 5.2")] public static void ConfigureForTargetLogging(Target target, LogLevel minLevel) { Guard.ThrowIfNull(target); LoggingConfiguration config = new LoggingConfiguration(); config.AddRule(minLevel, LogLevel.MaxLevel, target, "*"); LogManager.Configuration = config; } /// <summary> /// Configures NLog for file logging so that all messages above and including /// the <see cref="NLog.LogLevel.Info"/> level are written to the specified file. /// </summary> /// <param name="fileName">Log file name.</param> [Obsolete("Use LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteToFile(fileName)) instead. Marked obsolete on NLog 5.2")] public static void ConfigureForFileLogging(string fileName) { ConfigureForFileLogging(fileName, LogLevel.Info); } /// <summary> /// Configures NLog for file logging so that all messages above and including /// the specified level are written to the specified file. /// </summary> /// <param name="fileName">Log file name.</param> /// <param name="minLevel">The minimal logging level.</param> [Obsolete("Use LogManager.Setup().LoadConfiguration(c => c.ForLogger(minLevel).WriteToFile(fileName)) instead. Marked obsolete on NLog 5.2")] public static void ConfigureForFileLogging(string fileName, LogLevel minLevel) { FileTarget target = new FileTarget(); target.FileName = fileName; ConfigureForTargetLogging(target, minLevel); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using JetBrains.Annotations; namespace NLog.UnitTests { using System; using System.IO; using System.Linq; using Xunit; using NLog.Common; using NLog.Config; using NLog.Targets; using System.Threading.Tasks; public class LogManagerTests : NLogTestBase { [Fact] public void GetLoggerTest() { var loggerA = LogManager.GetLogger("A"); var loggerA2 = LogManager.GetLogger("A"); var loggerB = LogManager.GetLogger("B"); Assert.Same(loggerA, loggerA2); Assert.NotSame(loggerA, loggerB); Assert.Equal("A", loggerA.Name); Assert.Equal("B", loggerB.Name); } [Fact] public void GarbageCollectionTest() { string uniqueLoggerName = Guid.NewGuid().ToString(); var loggerA1 = LogManager.GetLogger(uniqueLoggerName); GC.Collect(); var loggerA2 = LogManager.GetLogger(uniqueLoggerName); Assert.Same(loggerA1, loggerA2); } static WeakReference GetWeakReferenceToTemporaryLogger() { string uniqueLoggerName = Guid.NewGuid().ToString(); return new WeakReference(LogManager.GetLogger(uniqueLoggerName)); } [Fact] public void GarbageCollection2Test() { WeakReference wr = GetWeakReferenceToTemporaryLogger(); // nobody's holding a reference to this Logger anymore, so GC.Collect(2) should free it GC.Collect(2, GCCollectionMode.Forced, true); Assert.False(wr.IsAlive); } [Fact] public void NullLoggerTest() { var logger = LogManager.CreateNullLogger(); Assert.Equal(String.Empty, logger.Name); } [Fact] public void GlobalThresholdTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog globalThreshold='Info'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; Assert.Equal(LogLevel.Info, logFactory.GlobalThreshold); // nothing gets logged because of globalThreshold logFactory.GetLogger("A").Debug("xxx"); logFactory.AssertDebugLastMessage("debug", ""); // lower the threshold logFactory.GlobalThreshold = LogLevel.Trace; logFactory.GetLogger("A").Debug("yyy"); logFactory.AssertDebugLastMessage("debug", "yyy"); // raise the threshold logFactory.GlobalThreshold = LogLevel.Info; // this should be yyy, meaning that the target is in place // only rules have been modified. logFactory.GetLogger("A").Debug("zzz"); logFactory.AssertDebugLastMessage("debug", "yyy"); } [Fact] public void DisableLoggingTest_UsingStatement() { const string LoggerConfig = @" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='DisableLoggingTest_UsingStatement_A' levels='Trace' writeTo='debug' /> <logger name='DisableLoggingTest_UsingStatement_B' levels='Error' writeTo='debug' /> </rules> </nlog>"; // Disable/Enable logging should affect ALL the loggers. var loggerA = LogManager.GetLogger("DisableLoggingTest_UsingStatement_A"); var loggerB = LogManager.GetLogger("DisableLoggingTest_UsingStatement_B"); LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(LoggerConfig); // The starting state for logging is enable. Assert.True(LogManager.IsLoggingEnabled()); loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "TTT"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "EEE"); loggerA.Trace("---"); AssertDebugLastMessage("debug", "---"); using (LogManager.SuspendLogging()) { Assert.False(LogManager.IsLoggingEnabled()); // The last of LastMessage outside using statement should be returned. loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "---"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "---"); } Assert.True(LogManager.IsLoggingEnabled()); loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "TTT"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "EEE"); LogManager.Shutdown(); LogManager.Configuration = null; } [Fact] public void DisableLoggingTest_WithoutUsingStatement() { const string LoggerConfig = @" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='DisableLoggingTest_WithoutUsingStatement_A' levels='Trace' writeTo='debug' /> <logger name='DisableLoggingTest_WithoutUsingStatement_B' levels='Error' writeTo='debug' /> </rules> </nlog>"; // Disable/Enable logging should affect ALL the loggers. var loggerA = LogManager.GetLogger("DisableLoggingTest_WithoutUsingStatement_A"); var loggerB = LogManager.GetLogger("DisableLoggingTest_WithoutUsingStatement_B"); LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(LoggerConfig); // The starting state for logging is enable. Assert.True(LogManager.IsLoggingEnabled()); loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "TTT"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "EEE"); loggerA.Trace("---"); AssertDebugLastMessage("debug", "---"); LogManager.SuspendLogging(); Assert.False(LogManager.IsLoggingEnabled()); // The last value of LastMessage before DisableLogging() should be returned. loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "---"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "---"); LogManager.ResumeLogging(); Assert.True(LogManager.IsLoggingEnabled()); loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "TTT"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "EEE"); LogManager.Shutdown(); LogManager.Configuration = null; } private int _reloadCounter; private void WaitForConfigReload(int counter) { while (_reloadCounter < counter) { System.Threading.Thread.Sleep(100); } } private void OnConfigReloaded(object sender, LoggingConfigurationChangedEventArgs e) { ++_reloadCounter; Console.WriteLine("OnConfigReloaded triggered: {0}", _reloadCounter); } [Fact] public void AutoReloadTest() { #if NETSTANDARD || MONO if (IsLinux()) { Console.WriteLine("[SKIP] LogManagerTests.AutoReloadTest because we are running in Travis"); return; } #endif using (new InternalLoggerScope()) { string fileName = Path.GetTempFileName(); try { _reloadCounter = 0; LogManager.ConfigurationChanged += OnConfigReloaded; using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } LogManager.Configuration = new XmlLoggingConfiguration(fileName); AssertDebugCounter("debug", 0); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); InternalLogger.Info("Rewriting test file..."); // now write the file again using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='xxx ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } InternalLogger.Info("Rewritten."); WaitForConfigReload(2); logger.Debug("aaa"); AssertDebugLastMessage("debug", "xxx aaa"); // write the file again, this time make an error using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='xxx ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } WaitForConfigReload(3); logger.Debug("bbb"); AssertDebugLastMessage("debug", "xxx bbb"); // write the corrected file again using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='zzz ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } WaitForConfigReload(4); logger.Debug("ccc"); AssertDebugLastMessage("debug", "zzz ccc"); } finally { LogManager.ConfigurationChanged -= OnConfigReloaded; if (File.Exists(fileName)) File.Delete(fileName); } } } [Fact] public void GivenCurrentClass_WhenGetCurrentClassLogger_ThenLoggerShouldBeCurrentClass() { var logger = LogManager.GetCurrentClassLogger(); Assert.Equal(GetType().FullName, logger.Name); } private static class ImAStaticClass { [UsedImplicitly] public static readonly Logger Logger = LogManager.GetCurrentClassLogger(); static ImAStaticClass() { } public static void DummyToInvokeInitializers() { } } [Fact] public void GetCurrentClassLogger_static_class() { ImAStaticClass.DummyToInvokeInitializers(); Assert.Equal(typeof(ImAStaticClass).FullName, ImAStaticClass.Logger.Name); } private abstract class ImAAbstractClass { public virtual Logger Logger { get; private set; } public virtual Logger LoggerType { get; private set; } public string BaseName => typeof(ImAAbstractClass).FullName; /// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> protected ImAAbstractClass() { Logger = LogManager.GetCurrentClassLogger(); LoggerType = LogManager.LogFactory.GetCurrentClassLogger<MyLogger>(); } protected ImAAbstractClass(string param1, Func<string> param2) { if (string.IsNullOrEmpty(param1)) throw new ArgumentException(param2?.Invoke() ?? nameof(param1)); Logger = LogManager.GetCurrentClassLogger(); LoggerType = LogManager.LogFactory.GetCurrentClassLogger<MyLogger>(); } class MyLogger : Logger { } } private class InheritedFromAbstractClass : ImAAbstractClass { public readonly Logger LoggerInherited = LogManager.GetCurrentClassLogger(); public readonly Logger LoggerTypeInherited = LogManager.LogFactory.GetCurrentClassLogger<MyLogger>(); public string InheritedName => GetType().FullName; public InheritedFromAbstractClass() : base() { } public InheritedFromAbstractClass(string param1, Func<string> param2) : base(param1, param2) { if (string.IsNullOrEmpty(param1)) throw new ArgumentException(param2?.Invoke() ?? nameof(param1)); } class MyLogger : Logger { } } /// <summary> /// Creating instance in a abstract ctor should not be a problem /// </summary> [Fact] public void GetCurrentClassLogger_abstract_class() { var instance = new InheritedFromAbstractClass(); Assert.Equal(instance.BaseName, instance.Logger.Name); Assert.Equal(instance.BaseName, instance.LoggerType.Name); Assert.Equal(instance.InheritedName, instance.LoggerInherited.Name); Assert.Equal(instance.InheritedName, instance.LoggerTypeInherited.Name); } /// <summary> /// Creating instance in a abstract ctor should not be a problem /// </summary> [Fact] public void GetCurrentClassLogger_abstract_class_with_parameter() { var instance = new InheritedFromAbstractClass("Hello", null); Assert.Equal(instance.BaseName, instance.Logger.Name); Assert.Equal(instance.BaseName, instance.LoggerType.Name); Assert.Equal(instance.InheritedName, instance.LoggerInherited.Name); Assert.Equal(instance.InheritedName, instance.LoggerTypeInherited.Name); } /// <summary> /// I'm a class which isn't inhereting from Logger /// </summary> private class ImNotALogger { } /// <summary> /// ImNotALogger inherits not from Logger , but should not throw an exception /// </summary> [Fact] [Obsolete("Replaced by LogFactory.GetLogger<T>(). Marked obsolete on NLog 5.2")] public void GetLogger_wrong_loggertype_should_continue() { using (new NoThrowNLogExceptions()) { var instance = LogManager.GetLogger("a", typeof(ImNotALogger)); Assert.NotNull(instance); } } /// <summary> /// ImNotALogger inherits not from Logger , but should not throw an exception /// </summary> [Fact] [Obsolete("Replaced by LogFactory.GetLogger<T>(). Marked obsolete on NLog 5.2")] public void GetLogger_wrong_loggertype_should_continue_even_if_class_is_static() { using (new NoThrowNLogExceptions()) { var instance = LogManager.GetLogger("a", typeof(ImAStaticClass)); Assert.NotNull(instance); } } [Fact] public void GivenLazyClass_WhenGetCurrentClassLogger_ThenLoggerNameShouldBeCurrentClass() { var logger = new Lazy<Logger>(LogManager.GetCurrentClassLogger); Assert.Equal(GetType().FullName, logger.Value.Name); } [Fact] public void ThreadSafe_Shutdown() { LogManager.Configuration = new LoggingConfiguration(); LogManager.ThrowExceptions = true; LogManager.Configuration.AddTarget("memory", new NLog.Targets.Wrappers.BufferingTargetWrapper(new MemoryTarget() { MaxLogsCount = 500 }, 5, 1)); LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, LogManager.Configuration.FindTargetByName("memory"))); LogManager.Configuration.AddTarget("memory2", new NLog.Targets.Wrappers.BufferingTargetWrapper(new MemoryTarget() { MaxLogsCount = 500 }, 5, 1)); LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, LogManager.Configuration.FindTargetByName("memory2"))); var stopFlag = false; var exceptionThrown = false; Task.Run(() => { try { var logger = LogManager.GetLogger("Hello"); while (!stopFlag) { logger.Debug("Hello World"); System.Threading.Thread.Sleep(1); } } catch { exceptionThrown = true; } }); Task.Run(() => { try { var logger = LogManager.GetLogger("Hello"); while (!stopFlag) { logger.Debug("Hello World"); System.Threading.Thread.Sleep(1); } } catch { exceptionThrown = true; } }); System.Threading.Thread.Sleep(20); LogManager.Shutdown(); // Shutdown active LoggingConfiguration System.Threading.Thread.Sleep(20); stopFlag = true; System.Threading.Thread.Sleep(20); Assert.False(exceptionThrown); } /// <summary> /// Note: THe problem can be reproduced when: debugging the unittest + "break when exception is thrown" checked in visual studio. /// /// https://github.com/NLog/NLog/issues/500 /// </summary> [Fact] public void ThreadSafe_getCurrentClassLogger_test() { MemoryTarget mTarget = new MemoryTarget() { Name = "memory", MaxLogsCount = 1000 }; MemoryTarget mTarget2 = new MemoryTarget() { Name = "memory2", MaxLogsCount = 1000 }; var task1 = Task.Run(() => { //need for init LogManager.Configuration = new LoggingConfiguration(); LogManager.Configuration.AddTarget(mTarget.Name, mTarget); LogManager.Configuration.AddRuleForAllLevels(mTarget.Name); System.Threading.Thread.Sleep(1); LogManager.ReconfigExistingLoggers(); System.Threading.Thread.Sleep(1); mTarget.Layout = @"${date:format=HH\:mm\:ss}|${level:uppercase=true}|${message} ${exception:format=tostring}"; }); var task2 = task1.ContinueWith((t) => { LogManager.Configuration.AddTarget(mTarget2.Name, mTarget2); LogManager.Configuration.AddRuleForAllLevels(mTarget2.Name); System.Threading.Thread.Sleep(1); LogManager.ReconfigExistingLoggers(); System.Threading.Thread.Sleep(1); mTarget2.Layout = @"${date:format=HH\:mm\:ss}|${level:uppercase=true}|${message} ${exception:format=tostring}"; }); System.Threading.Thread.Sleep(1); Parallel.For(0, 8, new ParallelOptions() { MaxDegreeOfParallelism = 8 }, (e) => { bool task1Complete = false, task2Complete = false; for (int i = 0; i < 100; ++i) { if (i > 25 && !task1Complete) { task1.Wait(5000); task1Complete = true; } if (i > 75 && !task2Complete) { task2.Wait(5000); task2Complete = true; } // Multiple threads initializing new loggers while configuration is changing var loggerA = LogManager.GetLogger(e + "A" + i); loggerA.Info("Hi there {0}", e); var loggerB = LogManager.GetLogger(e + "B" + i); loggerB.Info("Hi there {0}", e); var loggerC = LogManager.GetLogger(e + "C" + i); loggerC.Info("Hi there {0}", e); var loggerD = LogManager.GetLogger(e + "D" + i); loggerD.Info("Hi there {0}", e); }; }); Assert.NotEqual(0, mTarget.Logs.Count + mTarget2.Logs.Count); } [Fact] public void RemovedTargetShouldNotLog() { var config = new LoggingConfiguration(); var targetA = new MemoryTarget("TargetA") { Layout = "A | ${message}", MaxLogsCount = 1 }; var targetB = new MemoryTarget("TargetB") { Layout = "B | ${message}", MaxLogsCount = 1 }; config.AddRule(LogLevel.Debug, LogLevel.Fatal, targetA); config.AddRule(LogLevel.Debug, LogLevel.Fatal, targetB); LogManager.Configuration = config; Assert.Equal(new[] { "TargetA", "TargetB" }, LogManager.Configuration.ConfiguredNamedTargets.Select(target => target.Name)); Assert.NotNull(LogManager.Configuration.FindTargetByName("TargetA")); Assert.NotNull(LogManager.Configuration.FindTargetByName("TargetB")); var logger = LogManager.GetCurrentClassLogger(); logger.Info("Hello World"); Assert.Equal("A | Hello World", targetA.Logs.LastOrDefault()); Assert.Equal("B | Hello World", targetB.Logs.LastOrDefault()); // Remove the first target from the configuration LogManager.Configuration.RemoveTarget("TargetA"); Assert.Equal(new[] { "TargetB" }, LogManager.Configuration.ConfiguredNamedTargets.Select(target => target.Name)); Assert.Null(LogManager.Configuration.FindTargetByName("TargetA")); Assert.NotNull(LogManager.Configuration.FindTargetByName("TargetB")); logger.Info("Goodbye World"); Assert.Equal("A | Hello World", targetA.Logs.LastOrDefault()); // Flushed and closed Assert.Equal("B | Goodbye World", targetB.Logs.LastOrDefault()); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Layouts { using System; using System.Collections.Generic; using NLog.LayoutRenderers; using NLog.Targets; using Xunit; public class AllEventPropertiesTests : NLogTestBase { [Fact] public void AllParametersAreSetToDefault() { var renderer = new AllEventPropertiesLayoutRenderer(); var ev = BuildLogEventWithProperties(); var result = renderer.Render(ev); Assert.Equal("a=1, hello=world, 17=100", result); } [Fact] public void CustomSeparator() { var renderer = new AllEventPropertiesLayoutRenderer(); renderer.Separator = " | "; var ev = BuildLogEventWithProperties(); var result = renderer.Render(ev); Assert.Equal("a=1 | hello=world | 17=100", result); } [Fact] public void CustomFormat() { var renderer = new AllEventPropertiesLayoutRenderer(); renderer.Format = "[key] is [value]"; var ev = BuildLogEventWithProperties(); var result = renderer.Render(ev); Assert.Equal("a is 1, hello is world, 17 is 100", result); } [Fact] public void NoProperties() { var renderer = new AllEventPropertiesLayoutRenderer(); var ev = new LogEventInfo(); var result = renderer.Render(ev); Assert.Equal("", result); } [Fact] public void EventPropertyFormat() { var renderer = new AllEventPropertiesLayoutRenderer(); var ev = new LogEventInfo(LogLevel.Info, null, null, "{pi:0}", new object[] { 3.14159265359 }); var result = renderer.Render(ev); Assert.Equal("pi=3", result); } [Fact] public void StructuredLoggingProperties() { var renderer = new AllEventPropertiesLayoutRenderer(); var planetProperties = new System.Collections.Generic.Dictionary<string, object>() { { "Name", "Earth" }, { "PlanetType", "Water-world" }, }; var ev = new LogEventInfo(LogLevel.Info, null, null, "Hello Planet {@planet}", new object[] { planetProperties }); var result = renderer.Render(ev); Assert.Equal(@"planet=""Name""=""Earth"", ""PlanetType""=""Water-world""", result); } [Fact] public void IncludeScopeProperties() { var renderer = new AllEventPropertiesLayoutRenderer() { IncludeScopeProperties = true }; var ev = new LogEventInfo(LogLevel.Info, null, null, "{pi:0}", new object[] { 3.14159265359 }); using (ScopeContext.PushProperty("Figure", "Circle")) { var result = renderer.Render(ev); Assert.Equal("pi=3, Figure=Circle", result); } } [Fact] public void TestInvalidCustomFormatWithoutKeyPlaceholder() { var renderer = new AllEventPropertiesLayoutRenderer(); var ex = Assert.Throws<ArgumentException>(() => renderer.Format = "[key is [value]"); Assert.Equal("Invalid format: [key] placeholder is missing.", ex.Message); } [Fact] public void TestInvalidCustomFormatWithoutValuePlaceholder() { var renderer = new AllEventPropertiesLayoutRenderer(); var ex = Assert.Throws<ArgumentException>(() => renderer.Format = "[key] is [vlue]"); Assert.Equal("Invalid format: [value] placeholder is missing.", ex.Message); } [Fact] public void AllEventWithFluent_without_callerInformation() { //Arrange LogFactory logFactory = new LogFactory() .Setup() .LoadConfiguration(builder => { builder.ForLogger().WriteTo(new DebugTarget("debug") { Layout = "${all-event-properties}" }); }) .LogFactory; //Act logFactory.GetCurrentClassLogger() .WithProperty("Test", "InfoWrite") .WithProperty("coolness", "200%") .WithProperty("a", "not b") .Debug("This is a test message '{0}'.", DateTime.Now.Ticks); //Assert logFactory.AssertDebugLastMessage("Test=InfoWrite, coolness=200%, a=not b"); } [Fact] public void WithPropertiesTest() { //Arrange LogFactory logFactory = new LogFactory() .Setup() .LoadConfiguration(builder => { builder.ForLogger().WriteTo(new DebugTarget("debug") { Layout = "${all-event-properties}" }); }) .LogFactory; Dictionary<string, object> properties = new Dictionary<string, object>() { {"TestString", "myString" }, {"TestInt", 999 } }; //Act logFactory.GetCurrentClassLogger() .WithProperties(properties) .Debug("This is a test message '{0}'.", DateTime.Now.Ticks); //Assert logFactory.AssertDebugLastMessage("TestString=myString, TestInt=999"); } #if NET35 || NET40 [Fact(Skip = "NET35 not supporting Caller-Attributes")] #else [Fact] #endif public void AllEventWithFluent_with_callerInformation() { //Arrange LogFactory logFactory = new LogFactory() .Setup() .LoadConfiguration(builder => { builder.ForLogger().WriteTo(new DebugTarget("debug") { Layout = "${all-event-properties}${callsite}" }); }) .LogFactory; //Act logFactory.GetCurrentClassLogger() .WithProperty("Test", "InfoWrite") .WithProperty("coolness", "200%") .WithProperty("a", "not b") .Debug("This is a test message '{0}'.", DateTime.Now.Ticks); //Assert logFactory.AssertDebugLastMessageContains(nameof(AllEventWithFluent_with_callerInformation)); logFactory.AssertDebugLastMessageContains(nameof(AllEventPropertiesTests)); } [Theory] [InlineData(null, "a=1, hello=world, 17=100, notempty=0")] [InlineData(false, "a=1, hello=world, 17=100, notempty=0")] [InlineData(true, "a=1, hello=world, 17=100, empty1=, empty2=, notempty=0")] public void IncludeEmptyValuesTest(bool? includeEmptyValues, string expected) { // Arrange var renderer = new AllEventPropertiesLayoutRenderer(); if (includeEmptyValues != null) { renderer.IncludeEmptyValues = includeEmptyValues.Value; } var ev = BuildLogEventWithProperties(); ev.Properties["empty1"] = null; ev.Properties["empty2"] = ""; ev.Properties["notempty"] = 0; // Act var result = renderer.Render(ev); // Assert Assert.Equal(expected, result); } [Theory] [InlineData("", "a=1, hello=world, 17=100")] [InlineData("Wrong", "a=1, hello=world, 17=100")] [InlineData("hello", "a=1, 17=100")] [InlineData("Hello", "a=1, 17=100")] [InlineData("Hello, 17", "a=1")] public void ExcludeSingleProperty(string exclude, string result) { // Arrange var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target type='Debug' name='debug' layout='${all-event-properties:Exclude=" + exclude + @"}' /> </targets> <rules> <logger name='*' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetCurrentClassLogger(); // Act var ev = BuildLogEventWithProperties(); logger.Log(ev); // Assert logFactory.AssertDebugLastMessageContains(result); } private static LogEventInfo BuildLogEventWithProperties() { var ev = new LogEventInfo() { Level = LogLevel.Info }; ev.Properties["a"] = 1; ev.Properties["hello"] = "world"; ev.Properties[17] = 100; return ev; } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using NLog.Common; using NLog.Layouts; /// <summary> /// Dynamic filtering with a minlevel and maxlevel range /// </summary> internal class DynamicRangeLevelFilter : ILoggingRuleLevelFilter { private readonly LoggingRule _loggingRule; private readonly SimpleLayout _minLevel; private readonly SimpleLayout _maxLevel; private readonly SimpleLayout _finalMinLevelFilter; private KeyValuePair<MinMaxLevels, bool[]> _activeFilter; public bool[] LogLevels => GenerateLogLevels(); public LogLevel FinalMinLevel => GenerateFinalMinLevel(); public DynamicRangeLevelFilter(LoggingRule loggingRule, SimpleLayout minLevel, SimpleLayout maxLevel, SimpleLayout finalMinLevelFilter) { _loggingRule = loggingRule; _minLevel = minLevel; _maxLevel = maxLevel; _finalMinLevelFilter = finalMinLevelFilter; _activeFilter = new KeyValuePair<MinMaxLevels, bool[]>(new MinMaxLevels(string.Empty, string.Empty), LoggingRuleLevelFilter.Off.LogLevels); } public LoggingRuleLevelFilter GetSimpleFilterForUpdate() { return new LoggingRuleLevelFilter(LogLevels, FinalMinLevel); } private bool[] GenerateLogLevels() { var minLevelFilter = _minLevel?.Render(LogEventInfo.CreateNullEvent()) ?? string.Empty; var maxLevelFilter = _maxLevel?.Render(LogEventInfo.CreateNullEvent()) ?? string.Empty; if (string.IsNullOrEmpty(minLevelFilter) && string.IsNullOrEmpty(maxLevelFilter)) return LoggingRuleLevelFilter.Off.LogLevels; var activeFilter = _activeFilter; if (!activeFilter.Key.Equals(new MinMaxLevels(minLevelFilter, maxLevelFilter))) { bool[] logLevels = ParseLevelRange(minLevelFilter, maxLevelFilter); _activeFilter = activeFilter = new KeyValuePair<MinMaxLevels, bool[]>(new MinMaxLevels(minLevelFilter, maxLevelFilter), logLevels); } return activeFilter.Value; } private LogLevel GenerateFinalMinLevel() { var levelFilter = _finalMinLevelFilter?.Render(LogEventInfo.CreateNullEvent()); return ParseLogLevel(levelFilter, null); } private bool[] ParseLevelRange(string minLevelFilter, string maxLevelFilter) { LogLevel minLevel = ParseLogLevel(minLevelFilter, LogLevel.MinLevel); LogLevel maxLevel = ParseLogLevel(maxLevelFilter, LogLevel.MaxLevel); bool[] logLevels = new bool[LogLevel.MaxLevel.Ordinal + 1]; if (minLevel != null && maxLevel != null) { for (int i = minLevel.Ordinal; i <= logLevels.Length - 1 && i <= maxLevel.Ordinal; ++i) { logLevels[i] = true; } } return logLevels; } private LogLevel ParseLogLevel(string logLevel, LogLevel levelIfEmpty) { try { if (string.IsNullOrEmpty(logLevel)) return levelIfEmpty; return LogLevel.FromString(logLevel.Trim()); } catch (ArgumentException ex) { InternalLogger.Warn(ex, "Logging rule {0} with pattern '{1}' has invalid loglevel: {2}", _loggingRule.RuleName, _loggingRule.LoggerNamePattern, logLevel); return null; } } private struct MinMaxLevels : IEquatable<MinMaxLevels> { private readonly string _minLevel; private readonly string _maxLevel; public MinMaxLevels(string minLevel, string maxLevel) { _minLevel = minLevel; _maxLevel = maxLevel; } public bool Equals(MinMaxLevels other) { return _minLevel == other._minLevel && _maxLevel == other._maxLevel; } } } } <file_sep>namespace DumpApiXml { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Xml; public class DocFileBuilder { private static Dictionary<string, string> simpleTypeNames = new Dictionary<string, string>() { { typeof(string).FullName, "String" }, { typeof(int).FullName, "Integer" }, { typeof(long).FullName, "Long" }, { typeof(bool).FullName, "Boolean" }, { typeof(char).FullName, "Char" }, { typeof(byte).FullName, "Byte" }, { typeof(CultureInfo).FullName, "Culture" }, { typeof(Encoding).FullName, "Encoding" }, { "NLog.Layouts.Layout", "Layout" }, { "NLog.Targets.Target", "Target" }, { "NLog.Targets.LineEndingMode", "LineEndingMode" }, { "NLog.Conditions.ConditionExpression", "Condition" }, { "NLog.Filters.FilterResult", "FilterResult" }, { "NLog.Layout", "Layout" }, { "NLog.Target", "Target" }, { "NLog.ConditionExpression", "Condition" }, { "NLog.FilterResult", "FilterResult" }, }; private List<Assembly> assemblies = new List<Assembly>(); private List<XmlDocument> comments = new List<XmlDocument>(); public void Build(string outputFile) { using (XmlWriter writer = XmlWriter.Create(outputFile, new XmlWriterSettings { Indent = true })) { Build(writer); } } public void Build(XmlWriter writer) { writer.WriteProcessingInstruction("xml-stylesheet", "type='text/xsl' href='style.xsl'"); writer.WriteStartElement("types"); this.DumpApiDocs(writer, "target", "NLog.Targets.TargetAttribute", "", " target"); this.DumpApiDocs(writer, "layout", "NLog.Layouts.LayoutAttribute", "", ""); this.DumpApiDocs(writer, "layout-renderer", "NLog.LayoutRenderers.LayoutRendererAttribute", "${", "}"); this.DumpApiDocs(writer, "filter", "NLog.Filters.FilterAttribute", "", " filter"); this.DumpApiDocs(writer, "target", "NLog.TargetAttribute", "", " target"); this.DumpApiDocs(writer, "layout", "NLog.LayoutAttribute", "", ""); this.DumpApiDocs(writer, "layout-renderer", "NLog.LayoutRendererAttribute", "${", "}"); this.DumpApiDocs(writer, "filter", "NLog.FilterAttribute", "", " filter"); this.DumpApiDocs(writer, "time-source", "NLog.Time.TimeSourceAttribute", "", " time source"); writer.WriteEndElement(); } public void DisableComments() { this.comments.Clear(); } public void LoadAssembly(string fileName) { this.assemblies.Add(Assembly.LoadFrom(fileName)); } public void LoadComments(string commentsFile) { var commentsDoc = new XmlDocument(); commentsDoc.Load(commentsFile); FixWhitespace(commentsDoc.DocumentElement); this.comments.Add(commentsDoc); } private void FixWhitespace(XmlElement xmlElement) { foreach (var node in xmlElement.ChildNodes) { XmlElement el = node as XmlElement; if (el != null) { FixWhitespace(el); continue; } XmlText txt = node as XmlText; if (txt != null) { txt.Value = FixWhitespace(txt.Value); } } } private string FixWhitespace(string p) { p = p.Replace("\n", " "); p = p.Replace("\r", " "); string oldP = ""; while (oldP != p) { oldP = p; p = p.Replace(" ", " "); } return p; } private static string GetTypeName(Type type) { string simpleName; type = GetUnderlyingType(type); if (simpleTypeNames.TryGetValue(type.FullName, out simpleName)) { return simpleName; } return type.FullName; } private static Type GetUnderlyingType(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { type = type.GetGenericArguments()[0]; } return type; } private static bool IsCollection(PropertyInfo prop, out Type elementType, out string elementName) { object v1, v2; if (TryGetFirstTwoArgumentForAttribute(prop, "NLog.Config.ArrayParameterAttribute", out v1, out v2)) { elementType = (Type)v1; elementName = (string)v2; return true; } else { elementName = null; elementType = null; return false; } } private static bool TryGetFirstArgumentForAttribute(Type type, string attributeTypeName, out object value) { foreach (CustomAttributeData cad in CustomAttributeData.GetCustomAttributes(type)) { if (cad.Constructor.DeclaringType.FullName == attributeTypeName) { value = cad.ConstructorArguments[0].Value; return true; } } value = null; return false; } private static bool TryGetFirstTwoArgumentForAttribute(PropertyInfo propInfo, string attributeTypeName, out object value1, out object value2) { foreach (CustomAttributeData cad in CustomAttributeData.GetCustomAttributes(propInfo)) { if (cad.Constructor.DeclaringType.FullName == attributeTypeName) { value1 = cad.ConstructorArguments[0].Value; value2 = cad.ConstructorArguments[1].Value; return true; } } value1 = value2 = null; return false; } private static bool TryGetTypeNameFromNameAttribute(Type type, string attributeTypeName, out string name) { object val; if (TryGetFirstArgumentForAttribute(type, attributeTypeName, out val)) { name = (string)val; return true; } name = null; return false; } private string Capitalize(string p) { return p.Substring(0, 1).ToUpper() + p.Substring(1); } private void DumpApiDocs(XmlWriter writer, string kind, string attributeTypeName, string titlePrefix, string titleSuffix) { foreach (Type type in this.GetTypesWithAttribute(attributeTypeName).OrderBy(t => t.Name)) { if (type.IsAbstract) { continue; } writer.WriteStartElement("type"); writer.WriteAttributeString("kind", kind); writer.WriteAttributeString("assembly", type.Assembly.GetName().Name); writer.WriteAttributeString("clrType", type.FullName); string name; if (TryGetTypeNameFromNameAttribute(type, attributeTypeName, out name)) { writer.WriteAttributeString("name", name); } writer.WriteAttributeString("slug", this.GetSlug(name, kind)); writer.WriteAttributeString("title", titlePrefix + name + titleSuffix); if (InheritsFrom(type, "CompoundTargetBase")) { writer.WriteAttributeString("iscompound", "1"); } if (InheritsFrom(type, "WrapperTargetBase")) { writer.WriteAttributeString("iswrapper", "1"); } if (InheritsFrom(type, "WrapperLayoutRendererBase")) { writer.WriteAttributeString("iswrapper", "1"); } string ambientPropName; if (TryGetTypeNameFromNameAttribute(type, "NLog.LayoutRenderers.AmbientPropertyAttribute", out ambientPropName)) { writer.WriteAttributeString("ambientProperty", ambientPropName); } this.DumpTypeMembers(writer, type); writer.WriteEndElement(); } } private bool InheritsFrom(Type type, string typeName) { for (var t = type; t != null; t = t.BaseType) { if (t.Name == typeName) { return true; } } return false; } private void DumpTypeMembers(XmlWriter writer, Type type) { XmlElement memberDoc; var categories = new Dictionary<string, int>(); categories["General Options"] = 10; categories["Layout Options"] = 20; if (this.TryGetMemberDoc("T:" + type.FullName, out memberDoc)) { writer.WriteStartElement("doc"); memberDoc.WriteContentTo(writer); writer.WriteEndElement(); foreach (XmlElement element in memberDoc.SelectNodes("docgen/categories/category")) { string categoryName = element.GetAttribute("name"); int order = Convert.ToInt32(element.GetAttribute("order")); categories[categoryName] = order; } } var property2Category = new Dictionary<PropertyInfo, string>(); var propertyOrderWithinCategory = new Dictionary<PropertyInfo, int>(); var propertyDoc = new Dictionary<PropertyInfo, XmlElement>(); var propertyInfos = this.GetProperties(type).ToList(); foreach (PropertyInfo propInfo in propertyInfos) { string category = null; int order = 100; if (HasAttribute(propInfo, "NLog.Config.NLogConfigurationIgnorePropertyAttribute")) { Console.WriteLine("SKIP {0}.{1}, it has [NLogConfigurationIgnoreProperty]", type.Name, propInfo.Name); continue; } if (HasAttribute(propInfo, "System.ObsoleteAttribute")) { Console.WriteLine("SKIP [Obsolete] {0}.{1}", type.Name, propInfo.Name); continue; } if (this.TryGetMemberDoc("P:" + propInfo.DeclaringType.FullName + "." + propInfo.Name, out memberDoc)) { propertyDoc.Add(propInfo, memberDoc); var docgen = (XmlElement)memberDoc.SelectSingleNode("docgen"); if (docgen != null) { category = docgen.GetAttribute("category"); order = Convert.ToInt32(docgen.GetAttribute("order")); } } if (string.IsNullOrEmpty(category)) { Console.WriteLine("WARNING: Property {0}.{1} does not have <docgen /> element defined.", propInfo.DeclaringType.Name, propInfo.Name); category = "Other"; } if (!categories.TryGetValue(category, out _)) { categories.Add(category, 100 + categories.Count); } //Console.WriteLine("p: {0} cat: {1} order: {2}", propInfo.Name, category, order); property2Category[propInfo] = category; propertyOrderWithinCategory[propInfo] = order; } if (categories.Count == 0) return; object configInstance = null; try { if (!type.IsAbstract) { configInstance = Activator.CreateInstance(type); } } catch (Exception ex) { Console.WriteLine("FAILED to create default instance of {0} - {1}", type.Name, ex.ToString()); } foreach (string category in categories.OrderBy(c => c.Value).Select(c => c.Key)) { string categoryName = category; foreach (PropertyInfo propInfo in propertyInfos .Where(p => property2Category.ContainsKey(p) && propertyOrderWithinCategory.ContainsKey(p)) .Where(p => property2Category[p] == categoryName).OrderBy( p => propertyOrderWithinCategory[p]).ThenBy(pi => pi.Name)) { string elementTag; Type elementType; writer.WriteStartElement("property"); writer.WriteAttributeString("name", propInfo.Name); writer.WriteAttributeString("camelName", this.MakeCamelCase(propInfo.Name)); string defaultValue; if (TryGetPropertyDefaultValue(configInstance, propInfo, out defaultValue)) { writer.WriteAttributeString("defaultValue", defaultValue); } writer.WriteAttributeString("category", categoryName); if (HasAttribute(propInfo, "NLog.Config.RequiredParameterAttribute")) { writer.WriteAttributeString("required", "1"); } else { writer.WriteAttributeString("required", "0"); } if (propInfo.Name == "Encoding") { writer.WriteAttributeString("type", "Encoding"); } else if (HasAttribute(propInfo, "NLog.Config.AcceptsLayoutAttribute") || propInfo.Name == "Layout") { writer.WriteAttributeString("type", "Layout"); } else if (HasAttribute(propInfo, "NLog.Config.AcceptsConditionAttribute") || propInfo.Name == "Condition") { writer.WriteAttributeString("type", "Condition"); } else if (IsCollection(propInfo, out elementType, out elementTag)) { writer.WriteAttributeString("type", "Collection"); writer.WriteStartElement("elementType"); writer.WriteAttributeString("name", GetTypeName(elementType)); writer.WriteAttributeString("elementTag", elementTag); if (elementType != type) { this.DumpTypeMembers(writer, elementType); } writer.WriteEndElement(); } else { var underlyingType = GetUnderlyingType(propInfo.PropertyType); var typeName = GetTypeName(underlyingType); if (underlyingType.IsEnum) { writer.WriteAttributeString("type", "Enum"); writer.WriteAttributeString("enumType", typeName); foreach (FieldInfo fi in underlyingType.GetFields(BindingFlags.Static | BindingFlags.Public)) { writer.WriteStartElement("enum"); writer.WriteAttributeString("name", fi.Name); if ( this.TryGetMemberDoc( "F:" + underlyingType.FullName.Replace("+", ".") + "." + fi.Name, out memberDoc)) { writer.WriteStartElement("doc"); memberDoc.WriteContentTo(writer); writer.WriteEndElement(); } writer.WriteEndElement(); } } else { writer.WriteAttributeString("type", typeName); } } if (this.TryGetMemberDoc("P:" + propInfo.DeclaringType.FullName + "." + propInfo.Name, out memberDoc)) { writer.WriteStartElement("doc"); memberDoc.WriteContentTo(writer); writer.WriteEndElement(); } writer.WriteEndElement(); } } } private static bool TryGetPropertyDefaultValue(object configInstance, PropertyInfo propInfo, out string defaultValue) { try { object propertyValue = configInstance != null ? propInfo.GetValue(configInstance) : null; if (propertyValue is Enum) { defaultValue = propertyValue.ToString(); return true; } if (propertyValue is Encoding encoding) { defaultValue = encoding.WebName; return true; } IConvertible convertibleValue = propertyValue as IConvertible; if (convertibleValue == null && propertyValue != null) { if (propertyValue is System.Collections.IEnumerable) { defaultValue = string.Empty; return true; } convertibleValue = Convert.ToString(propertyValue, CultureInfo.InvariantCulture); } switch (convertibleValue?.GetTypeCode() ?? TypeCode.Empty) { case TypeCode.Boolean: defaultValue = XmlConvert.ToString((bool)convertibleValue); return true; case TypeCode.DateTime: defaultValue = XmlConvert.ToString((DateTime)convertibleValue, XmlDateTimeSerializationMode.RoundtripKind); return true; case TypeCode.Int16: defaultValue = XmlConvert.ToString((Int16)convertibleValue); return true; case TypeCode.Int32: defaultValue = XmlConvert.ToString((Int32)convertibleValue); return true; case TypeCode.Int64: defaultValue = XmlConvert.ToString((Int64)convertibleValue); return true; case TypeCode.UInt16: defaultValue = XmlConvert.ToString((UInt16)convertibleValue); return true; case TypeCode.UInt32: defaultValue = XmlConvert.ToString((UInt32)convertibleValue); return true; case TypeCode.UInt64: defaultValue = XmlConvert.ToString((UInt64)convertibleValue); return true; case TypeCode.Double: defaultValue = XmlConvert.ToString((Double)convertibleValue); return true; case TypeCode.Single: defaultValue = XmlConvert.ToString((Single)convertibleValue); return true; case TypeCode.Decimal: defaultValue = XmlConvert.ToString((Decimal)convertibleValue); return true; case TypeCode.Char: defaultValue = XmlConvert.ToString((Char)convertibleValue); return true; case TypeCode.Empty: defaultValue = null; return false; } defaultValue = convertibleValue?.ToString(); return defaultValue != null; } catch (Exception ex) { Console.WriteLine("FAILED to lookup default value for property {0}-{1} - {2}", configInstance?.GetType(), propInfo?.Name, ex.ToString()); defaultValue = null; return false; } } private void FixupElement(XmlElement element) { var summary = (XmlElement)element.SelectSingleNode("summary"); if (summary != null) { summary.InnerXml = this.FixupSummaryXml(summary.InnerXml); } foreach (XmlElement code in element.SelectNodes("//code[@src]")) { code.SetAttribute("source", code.GetAttribute("src")); code.RemoveAttribute("src"); } } private string FixupSummaryXml(string xml) { xml = xml.Trim(); xml = this.ReplaceAndCapitalize(xml, "Gets or sets a value indicating ", "Indicates "); xml = this.ReplaceAndCapitalize(xml, "Gets or sets the ", ""); xml = this.ReplaceAndCapitalize(xml, "Gets or sets a ", ""); xml = this.ReplaceAndCapitalize(xml, "Gets or sets ", ""); xml = this.ReplaceAndCapitalize(xml, "Gets the ", "The "); return xml; } private IEnumerable<PropertyInfo> GetProperties(Type type) { return type.GetProperties() .Where(c => this.IncludeProperty(c)).OrderBy(p => p.Name); } private string GetSlug(string name, string kind) { switch (kind) { case "target": return name + "_target"; case "layout-renderer": return name + "_layout_renderer"; case "layout": return name; case "filter": return name + "_filter"; case "time-source": return name + "_time_source"; } string slugBase; if (name == name.ToUpperInvariant()) { slugBase = name.ToLowerInvariant(); } else { name = name.Replace("NLog", "Nlog"); name = name.Replace("Log4J", "Log4j"); var sb = new StringBuilder(); for (int i = 0; i < name.Length; ++i) { if (Char.IsUpper(name[i]) && i > 0) { sb.Append("_"); } sb.Append(name[i]); } slugBase = sb.ToString(); } if (kind == "layout") { return slugBase; } else { return slugBase + "-" + kind; } } private IEnumerable<Type> GetTypesWithAttribute(string attributeTypeName) { foreach (Assembly assembly in this.assemblies) { foreach (Type t in assembly.SafeGetTypes()) { if (HasAttribute(t, attributeTypeName)) { yield return t; } } } } private bool HasAttribute(Type type, string attributeTypeName) { try { foreach (CustomAttributeData cad in CustomAttributeData.GetCustomAttributes(type)) { if (cad.Constructor.DeclaringType.FullName == attributeTypeName) { return true; } } } catch { } return false; } private bool HasAttribute(PropertyInfo propertyInfo, string attributeTypeName) { try { foreach (CustomAttributeData cad in CustomAttributeData.GetCustomAttributes(propertyInfo)) { if (cad.Constructor.DeclaringType.FullName == attributeTypeName) { return true; } } } catch { } return false; } private bool IncludeProperty(PropertyInfo pi) { if (pi.CanRead && pi.CanWrite && pi.GetSetMethod() != null && pi.GetSetMethod().IsPublic) { if (pi.Name == "CultureInfo") { return false; } if (pi.Name == "WrappedTarget") { return false; } if ((pi.PropertyType.FullName.StartsWith("NLog.ILayout") || pi.PropertyType.FullName.StartsWith("NLog.Layout")) && pi.Name != "Layout" && pi.Name.EndsWith("Layout")) { return false; } if (pi.PropertyType.FullName.StartsWith("NLog.Conditions.ConditionExpression") && pi.Name != "Condition" && pi.Name.EndsWith("Condition")) { return false; } if (pi.Name.StartsWith("Compiled")) { return false; } return true; } if (HasAttribute(pi, "NLog.Config.ArrayParameterAttribute")) { return true; } return false; } private string MakeCamelCase(string s) { if (s.Length <= 2) { return s.ToLowerInvariant(); } if (s.ToUpperInvariant() == s) { return s.ToLowerInvariant(); } if (s.StartsWith("DB")) { return "db" + s.Substring(2); } return s.Substring(0, 1).ToLowerInvariant() + s.Substring(1); } private string ReplaceAndCapitalize(string xml, string pattern, string replacement) { if (xml.StartsWith(pattern)) { return this.Capitalize(xml.Replace(pattern, replacement)); } return xml; } private bool TryGetMemberDoc(string id, out XmlElement element) { foreach (XmlDocument doc in this.comments) { element = (XmlElement)doc.SelectSingleNode("/doc/members/member[@name='" + id + "']"); if (element != null) { this.FixupElement(element); return true; } } element = null; return false; } } public static class AssemblyExt { /// <summary> /// Gets all usable exported types from the given assembly. /// </summary> /// <param name="assembly">Assembly to scan.</param> /// <returns>Usable types from the given assembly.</returns> /// <remarks>Types which cannot be loaded are skipped.</remarks> public static Type[] SafeGetTypes(this Assembly assembly) { try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException typeLoadException) { foreach (var ex in typeLoadException.LoaderExceptions) { //InternalLogger.Warn(ex, "Type load exception."); } var loadedTypes = new List<Type>(); foreach (var t in typeLoadException.Types) { if (t != null) { loadedTypes.Add(t); } } return loadedTypes.ToArray(); } } } } <file_sep>using System; using NLog; using NLog.Targets; using NLog.Targets.Wrappers; using System.Diagnostics; class Example { static void Main(string[] args) { FileTarget wrappedTarget = new FileTarget(); wrappedTarget.FileName = "${basedir}/file.txt"; PostFilteringTargetWrapper postFilteringTarget = new PostFilteringTargetWrapper(); postFilteringTarget.WrappedTarget = wrappedTarget; // set up default filter postFilteringTarget.DefaultFilter = "level >= LogLevel.Info"; FilteringRule rule; // if there are any warnings in the buffer // dump the messages whose level is Debug or higher rule = new FilteringRule(); rule.Exists = "level >= LogLevel.Warn"; rule.Filter = "level >= LogLevel.Debug"; postFilteringTarget.Rules.Add(rule); BufferingTargetWrapper target = new BufferingTargetWrapper(); target.BufferSize = 100; target.WrappedTarget = postFilteringTarget; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 && !NETSTANDARD1_5 namespace NLog.LayoutRenderers { using System; using System.Text; using NLog.Common; using NLog.Internal; /// <summary> /// Thread identity information (username). /// </summary> [LayoutRenderer("environment-user")] public class EnvironmentUserLayoutRenderer : LayoutRenderer, IStringValueRenderer { /// <summary> /// Gets or sets a value indicating whether username should be included. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool UserName { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether domain name should be included. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool Domain { get; set; } /// <summary> /// Gets or sets the default value to be used when the User is not set. /// </summary> /// <docgen category='Layout Options' order='10' /> public string DefaultUser { get; set; } = "UserUnknown"; /// <summary> /// Gets or sets the default value to be used when the Domain is not set. /// </summary> /// <docgen category='Layout Options' order='10' /> public string DefaultDomain { get; set; } = "DomainUnknown"; /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(GetStringValue()); } string IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) => GetStringValue(); private string GetStringValue() { if (UserName) { return Domain ? string.Concat(GetDomainName(), "\\", GetUserName()) : GetUserName(); } else { return Domain ? GetDomainName() : string.Empty; } } string GetUserName() { return GetValueSafe(() => Environment.UserName, DefaultUser); } string GetDomainName() { return GetValueSafe(() => Environment.UserDomainName, DefaultDomain); } private string GetValueSafe(Func<string> getValue, string defaultValue) { try { var value = getValue(); return string.IsNullOrEmpty(value) ? (defaultValue ?? string.Empty) : value; } catch (Exception ex) { InternalLogger.Warn(ex, "Failed to lookup Environment-User. Fallback value={0}", defaultValue); return defaultValue ?? string.Empty; } } } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using JetBrains.Annotations; using NLog.Common; using NLog.Filters; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using NLog.Targets.Wrappers; using NLog.Time; namespace NLog.Config { /// <summary> /// Loads NLog configuration from <see cref="ILoggingConfigurationElement"/> /// </summary> public abstract class LoggingConfigurationParser : LoggingConfiguration { private readonly ServiceRepository _serviceRepository; /// <summary> /// Constructor /// </summary> /// <param name="logFactory"></param> protected LoggingConfigurationParser(LogFactory logFactory) : base(logFactory) { _serviceRepository = logFactory.ServiceRepository; } /// <summary> /// Loads NLog configuration from provided config section /// </summary> /// <param name="nlogConfig"></param> /// <param name="basePath">Directory where the NLog-config-file was loaded from</param> protected void LoadConfig(ILoggingConfigurationElement nlogConfig, string basePath) { InternalLogger.Trace("ParseNLogConfig"); nlogConfig.AssertName("nlog"); SetNLogElementSettings(nlogConfig); var validatedConfig = ValidatedConfigurationElement.Create(nlogConfig, LogFactory); // Validate after having loaded initial settings //first load the extensions, as the can be used in other elements (targets etc) foreach (var extensionsChild in validatedConfig.ValidChildren) { if (extensionsChild.MatchesName("extensions")) { ParseExtensionsElement(extensionsChild, basePath); } } var rulesList = new List<ValidatedConfigurationElement>(); //parse all other direct elements foreach (var child in validatedConfig.ValidChildren) { if (child.MatchesName("rules")) { //postpone parsing <rules> to the end rulesList.Add(child); } else if (child.MatchesName("extensions")) { //already parsed } else if (!ParseNLogSection(child)) { var configException = new NLogConfigurationException($"Unrecognized element '{child.Name}' from section 'NLog'"); if (MustThrowConfigException(configException)) throw configException; } } foreach (var ruleChild in rulesList) { ParseRulesElement(ruleChild, LoggingRules); } } private void SetNLogElementSettings(ILoggingConfigurationElement nlogConfig) { var sortedList = CreateUniqueSortedListFromConfig(nlogConfig); CultureInfo defaultCultureInfo = DefaultCultureInfo ?? LogFactory._defaultCultureInfo; bool? parseMessageTemplates = null; bool internalLoggerEnabled = false; bool autoLoadExtensions = false; foreach (var configItem in sortedList) { switch (configItem.Key.ToUpperInvariant()) { case "THROWEXCEPTIONS": LogFactory.ThrowExceptions = ParseBooleanValue(configItem.Key, configItem.Value, LogFactory.ThrowExceptions); break; case "THROWCONFIGEXCEPTIONS": LogFactory.ThrowConfigExceptions = ParseNullableBooleanValue(configItem.Key, configItem.Value, false); break; case "INTERNALLOGLEVEL": InternalLogger.LogLevel = ParseLogLevelSafe(configItem.Key, configItem.Value, InternalLogger.LogLevel); internalLoggerEnabled = InternalLogger.LogLevel != LogLevel.Off; break; case "USEINVARIANTCULTURE": if (ParseBooleanValue(configItem.Key, configItem.Value, false)) defaultCultureInfo = DefaultCultureInfo = CultureInfo.InvariantCulture; break; case "KEEPVARIABLESONRELOAD": LogFactory.KeepVariablesOnReload = ParseBooleanValue(configItem.Key, configItem.Value, LogFactory.KeepVariablesOnReload); break; case "INTERNALLOGTOCONSOLE": InternalLogger.LogToConsole = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.LogToConsole); break; case "INTERNALLOGTOCONSOLEERROR": InternalLogger.LogToConsoleError = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.LogToConsoleError); break; case "INTERNALLOGFILE": InternalLogger.LogFile = configItem.Value?.Trim(); break; case "INTERNALLOGTOTRACE": InternalLogger.LogToTrace = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.LogToTrace); break; case "INTERNALLOGINCLUDETIMESTAMP": InternalLogger.IncludeTimestamp = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.IncludeTimestamp); break; case "GLOBALTHRESHOLD": LogFactory.GlobalThreshold = ParseLogLevelSafe(configItem.Key, configItem.Value, LogFactory.GlobalThreshold); break; // expanding variables not possible here, they are created later case "PARSEMESSAGETEMPLATES": parseMessageTemplates = ParseNullableBooleanValue(configItem.Key, configItem.Value, true); break; case "AUTOSHUTDOWN": LogFactory.AutoShutdown = ParseBooleanValue(configItem.Key, configItem.Value, true); break; case "AUTORELOAD": break; // Ignore here, used by other logic case "AUTOLOADEXTENSIONS": autoLoadExtensions = ParseBooleanValue(configItem.Key, configItem.Value, false); break; default: var configException = new NLogConfigurationException($"Unrecognized value '{configItem.Key}'='{configItem.Value}' for element '{nlogConfig.Name}'"); if (MustThrowConfigException(configException)) throw configException; break; } } if (defaultCultureInfo != null && !ReferenceEquals(DefaultCultureInfo, defaultCultureInfo)) { DefaultCultureInfo = defaultCultureInfo; } if (!internalLoggerEnabled && !InternalLogger.HasActiveLoggers()) { InternalLogger.LogLevel = LogLevel.Off; // Reduce overhead of the InternalLogger when not configured } if (autoLoadExtensions) { ConfigurationItemFactory.Default.AssemblyLoader.ScanForAutoLoadExtensions(ConfigurationItemFactory.Default); } _serviceRepository.RegisterMessageTemplateParser(parseMessageTemplates); } /// <summary> /// Builds list with unique keys, using last value of duplicates. High priority keys placed first. /// </summary> /// <param name="nlogConfig"></param> /// <returns></returns> private ICollection<KeyValuePair<string, string>> CreateUniqueSortedListFromConfig(ILoggingConfigurationElement nlogConfig) { var dict = ValidatedConfigurationElement.Create(nlogConfig, LogFactory).ValueLookup; if (dict.Count <= 1) return dict; var sortedList = new List<KeyValuePair<string, string>>(dict.Count); var highPriorityList = new[] { "ThrowExceptions", "ThrowConfigExceptions", "InternalLogLevel", "InternalLogFile", "InternalLogToConsole", }; foreach (var highPrioritySetting in highPriorityList) { if (dict.TryGetValue(highPrioritySetting, out var settingValue)) { sortedList.Add(new KeyValuePair<string, string>(highPrioritySetting, settingValue)); dict.Remove(highPrioritySetting); } } foreach (var configItem in dict) { sortedList.Add(configItem); } return sortedList; } /// <summary> /// Parse loglevel, but don't throw if exception throwing is disabled /// </summary> /// <param name="propertyName">Name of attribute for logging.</param> /// <param name="propertyValue">Value of parse.</param> /// <param name="fallbackValue">Used if there is an exception</param> /// <returns></returns> private LogLevel ParseLogLevelSafe(string propertyName, string propertyValue, LogLevel fallbackValue) { try { var internalLogLevel = LogLevel.FromString(propertyValue?.Trim()); return internalLogLevel; } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException($"Property '{propertyName}' assigned invalid LogLevel value '{propertyValue}'. Fallback to '{fallbackValue}'", exception); if (MustThrowConfigException(configException)) throw configException; return fallbackValue; } } /// <summary> /// Parses a single config section within the NLog-config /// </summary> /// <param name="configSection"></param> /// <returns>Section was recognized</returns> protected virtual bool ParseNLogSection(ILoggingConfigurationElement configSection) { switch (configSection.Name?.Trim().ToUpperInvariant()) { case "TIME": ParseTimeElement(ValidatedConfigurationElement.Create(configSection, LogFactory)); return true; case "VARIABLE": ParseVariableElement(ValidatedConfigurationElement.Create(configSection, LogFactory)); return true; case "VARIABLES": ParseVariablesElement(ValidatedConfigurationElement.Create(configSection, LogFactory)); return true; case "APPENDERS": case "TARGETS": ParseTargetsElement(ValidatedConfigurationElement.Create(configSection, LogFactory)); return true; } return false; } private void ParseExtensionsElement(ValidatedConfigurationElement extensionsElement, string baseDirectory) { extensionsElement.AssertName("extensions"); foreach (var childItem in extensionsElement.ValidChildren) { string prefix = null; string type = null; string assemblyFile = null; string assemblyName = null; foreach (var childProperty in childItem.Values) { if (MatchesName(childProperty.Key, "prefix")) { prefix = childProperty.Value + "."; } else if (MatchesName(childProperty.Key, "type")) { type = childProperty.Value; } else if (MatchesName(childProperty.Key, "assemblyFile")) { assemblyFile = childProperty.Value; } else if (MatchesName(childProperty.Key, "assembly")) { assemblyName = childProperty.Value; } else { var configException = new NLogConfigurationException($"Unrecognized value '{childProperty.Key}'='{childProperty.Value}' for element '{childItem.Name}' in section '{extensionsElement.Name}'"); if (MustThrowConfigException(configException)) throw configException; } } if (!StringHelpers.IsNullOrWhiteSpace(type)) { RegisterExtension(type, prefix); } #if !NETSTANDARD1_3 if (!StringHelpers.IsNullOrWhiteSpace(assemblyFile)) { ParseExtensionWithAssemblyFile(baseDirectory, assemblyFile, prefix); continue; } #endif if (!StringHelpers.IsNullOrWhiteSpace(assemblyName)) { ParseExtensionWithAssemblyName(assemblyName?.Trim(), prefix); } } } private void RegisterExtension(string typeName, string itemNamePrefix) { try { ConfigurationItemFactory.Default.AssemblyLoader.LoadTypeFromName(ConfigurationItemFactory.Default, typeName, itemNamePrefix); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException("Error loading extensions: " + typeName, exception); if (MustThrowConfigException(configException)) throw configException; } } #if !NETSTANDARD1_3 private void ParseExtensionWithAssemblyFile(string baseDirectory, string assemblyFile, string prefix) { try { ConfigurationItemFactory.Default.AssemblyLoader.LoadAssemblyFromPath(ConfigurationItemFactory.Default, assemblyFile, baseDirectory, prefix); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception); if (MustThrowConfigException(configException)) throw configException; } } #endif private bool RegisterExtensionFromAssemblyName(string assemblyName, string originalTypeName) { InternalLogger.Debug("Loading Assembly-Name '{0}' for type: {1}", assemblyName, originalTypeName); return ParseExtensionWithAssemblyName(assemblyName, string.Empty); } private bool ParseExtensionWithAssemblyName(string assemblyName, string prefix) { try { ConfigurationItemFactory.Default.AssemblyLoader.LoadAssemblyFromName(ConfigurationItemFactory.Default, assemblyName, prefix); return true; } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException("Error loading extensions: " + assemblyName, exception); if (MustThrowConfigException(configException)) throw configException; } return false; } private void ParseVariableElement(ValidatedConfigurationElement variableElement) { string variableName = null; string variableValue = null; foreach (var childProperty in variableElement.Values) { if (MatchesName(childProperty.Key, "name")) variableName = childProperty.Value; else if (MatchesName(childProperty.Key, "value") || MatchesName(childProperty.Key, "layout")) variableValue = childProperty.Value; else { var configException = new NLogConfigurationException($"Unrecognized value '{childProperty.Key}'='{childProperty.Value}' for element '{variableElement.Name}' in section 'variables'"); if (MustThrowConfigException(configException)) throw configException; } } if (!AssertNonEmptyValue(variableName, "name", variableElement.Name, "variables")) return; Layout variableLayout = variableValue is null ? ParseVariableLayoutValue(variableElement) : CreateSimpleLayout(ExpandSimpleVariables(variableValue)); if (!AssertNotNullValue(variableLayout, "value", variableElement.Name, "variables")) return; InsertParsedConfigVariable(variableName, variableLayout); } private Layout ParseVariableLayoutValue(ValidatedConfigurationElement variableElement) { var childElement = variableElement.ValidChildren.FirstOrDefault(); if (childElement != null) { return TryCreateLayoutInstance(childElement, typeof(Layout)); } return null; } private void ParseVariablesElement(ValidatedConfigurationElement variableElement) { variableElement.AssertName("variables"); foreach (var childItem in variableElement.ValidChildren) { ParseVariableElement(childItem); } } private void ParseTimeElement(ValidatedConfigurationElement timeElement) { timeElement.AssertName("time"); string timeSourceType = null; foreach (var childProperty in timeElement.Values) { if (MatchesName(childProperty.Key, "type")) { timeSourceType = childProperty.Value; } else { var configException = new NLogConfigurationException($"Unrecognized value '{childProperty.Key}'='{childProperty.Value}' for element '{timeElement.Name}'"); if (MustThrowConfigException(configException)) throw configException; } } if (!AssertNonEmptyValue(timeSourceType, "type", timeElement.Name, string.Empty)) return; TimeSource newTimeSource = FactoryCreateInstance(timeSourceType, ConfigurationItemFactory.Default.TimeSourceFactory); if (newTimeSource != null) { ConfigureFromAttributesAndElements(newTimeSource, timeElement); InternalLogger.Info("Selecting time source {0}", newTimeSource); TimeSource.Current = newTimeSource; } } [ContractAnnotation("value:notnull => true")] private bool AssertNotNullValue(object value, string propertyName, string elementName, string sectionName) { if (value is null) return AssertNonEmptyValue(string.Empty, propertyName, elementName, sectionName); return true; } [ContractAnnotation("value:null => false")] private bool AssertNonEmptyValue(string value, string propertyName, string elementName, string sectionName) { if (!StringHelpers.IsNullOrWhiteSpace(value)) return true; var configException = new NLogConfigurationException($"Property '{propertyName}' has blank value, for element '{elementName}' in section '{sectionName}'"); if (MustThrowConfigException(configException)) throw configException; return false; } /// <summary> /// Parse {Rules} xml element /// </summary> /// <param name="rulesElement"></param> /// <param name="rulesCollection">Rules are added to this parameter.</param> private void ParseRulesElement(ValidatedConfigurationElement rulesElement, IList<LoggingRule> rulesCollection) { InternalLogger.Trace("ParseRulesElement"); rulesElement.AssertName("rules"); foreach (var childItem in rulesElement.ValidChildren) { LoggingRule loggingRule = ParseRuleElement(childItem); if (loggingRule != null) { lock (rulesCollection) { rulesCollection.Add(loggingRule); } } } } private LogLevel LogLevelFromString(string text) { return LogLevel.FromString(ExpandSimpleVariables(text).Trim()); } /// <summary> /// Parse {Logger} xml element /// </summary> /// <param name="loggerElement"></param> private LoggingRule ParseRuleElement(ValidatedConfigurationElement loggerElement) { string minLevel = null; string maxLevel = null; string finalMinLevel = null; string enableLevels = null; string ruleName = null; string namePattern = null; bool enabled = true; bool final = false; string writeTargets = null; string filterDefaultAction = null; foreach (var childProperty in loggerElement.Values) { switch (childProperty.Key?.Trim().ToUpperInvariant()) { case "NAME": if (loggerElement.MatchesName("logger")) namePattern = childProperty.Value; // Legacy Style else ruleName = childProperty.Value; break; case "RULENAME": ruleName = childProperty.Value; break; case "LOGGER": namePattern = childProperty.Value; break; case "ENABLED": enabled = ParseBooleanValue(childProperty.Key, childProperty.Value, true); break; case "APPENDTO": writeTargets = childProperty.Value; break; case "WRITETO": writeTargets = childProperty.Value; break; case "FINAL": final = ParseBooleanValue(childProperty.Key, childProperty.Value, false); break; case "LEVEL": case "LEVELS": enableLevels = childProperty.Value; break; case "MINLEVEL": minLevel = childProperty.Value; break; case "MAXLEVEL": maxLevel = childProperty.Value; break; case "FINALMINLEVEL": finalMinLevel = childProperty.Value; break; case "FILTERDEFAULTACTION": filterDefaultAction = childProperty.Value; break; default: var configException = new NLogConfigurationException($"Unrecognized value '{childProperty.Key}'='{childProperty.Value}' for element '{loggerElement.Name}' in section 'rules'"); if (MustThrowConfigException(configException)) throw configException; break; } } if (string.IsNullOrEmpty(ruleName) && string.IsNullOrEmpty(namePattern) && string.IsNullOrEmpty(writeTargets) && !final) { InternalLogger.Debug("Logging rule without name or filter or targets is ignored"); return null; } namePattern = namePattern ?? "*"; if (!enabled) { InternalLogger.Debug("Logging rule {0} with name pattern `{1}` is disabled", ruleName, namePattern); return null; } var rule = new LoggingRule(ruleName) { LoggerNamePattern = namePattern, Final = final, }; EnableLevelsForRule(rule, enableLevels, minLevel, maxLevel, finalMinLevel); ParseLoggingRuleTargets(writeTargets, rule); ParseLoggingRuleChildren(loggerElement, rule, filterDefaultAction); ValidateLoggingRuleFilters(rule); return rule; } private void EnableLevelsForRule( LoggingRule rule, string enableLevels, string minLevel, string maxLevel, string finalMinLevel) { if (enableLevels != null) { enableLevels = ExpandSimpleVariables(enableLevels); finalMinLevel = finalMinLevel != null ? ExpandSimpleVariables(finalMinLevel) : finalMinLevel; if (IsLevelLayout(enableLevels) || IsLevelLayout(finalMinLevel)) { SimpleLayout simpleLayout = ParseLevelLayout(enableLevels); SimpleLayout finalMinLevelLayout = ParseLevelLayout(finalMinLevel); rule.EnableLoggingForLevelLayout(simpleLayout, finalMinLevelLayout); } else { foreach (var logLevel in enableLevels.SplitAndTrimTokens(',')) { rule.EnableLoggingForLevel(LogLevelFromString(logLevel)); } if (finalMinLevel != null) rule.FinalMinLevel = LogLevelFromString(finalMinLevel); } } else { minLevel = minLevel != null ? ExpandSimpleVariables(minLevel) : minLevel; maxLevel = maxLevel != null ? ExpandSimpleVariables(maxLevel) : maxLevel; finalMinLevel = finalMinLevel != null ? ExpandSimpleVariables(finalMinLevel) : finalMinLevel; if (IsLevelLayout(minLevel) || IsLevelLayout(maxLevel) || IsLevelLayout(finalMinLevel)) { SimpleLayout finalMinLevelLayout = ParseLevelLayout(finalMinLevel); SimpleLayout minLevelLayout = ParseLevelLayout(minLevel) ?? finalMinLevelLayout; SimpleLayout maxLevelLayout = ParseLevelLayout(maxLevel); rule.EnableLoggingForLevelsLayout(minLevelLayout, maxLevelLayout, finalMinLevelLayout); } else { LogLevel finalMinLogLevel = finalMinLevel != null ? LogLevelFromString(finalMinLevel) : null; LogLevel minLogLevel = minLevel != null ? LogLevelFromString(minLevel) : (finalMinLogLevel ?? LogLevel.MinLevel); LogLevel maxLogLevel = maxLevel != null ? LogLevelFromString(maxLevel) : LogLevel.MaxLevel; rule.SetLoggingLevels(minLogLevel, maxLogLevel); if (finalMinLogLevel != null) rule.FinalMinLevel = finalMinLogLevel; } } } private static bool IsLevelLayout(string level) { return level?.IndexOf('{') >= 0; } private SimpleLayout ParseLevelLayout(string levelLayout) { SimpleLayout simpleLayout = !StringHelpers.IsNullOrWhiteSpace(levelLayout) ? CreateSimpleLayout(levelLayout) : null; simpleLayout?.Initialize(this); return simpleLayout; } private void ParseLoggingRuleTargets(string writeTargets, LoggingRule rule) { writeTargets = ExpandSimpleVariables(writeTargets); if (string.IsNullOrEmpty(writeTargets)) return; foreach (string targetName in writeTargets.SplitAndTrimTokens(',')) { Target target = FindTargetByName(targetName); if (target != null) { rule.Targets.Add(target); } else { var configException = new NLogConfigurationException($"Target '{targetName}' not found for logging rule: {(string.IsNullOrEmpty(rule.RuleName) ? rule.LoggerNamePattern : rule.RuleName)}."); if (MustThrowConfigException(configException)) throw configException; } } } private void ParseLoggingRuleChildren(ValidatedConfigurationElement loggerElement, LoggingRule rule, string filterDefaultAction = null) { foreach (var child in loggerElement.ValidChildren) { LoggingRule childRule = null; if (child.MatchesName("filters")) { ParseLoggingRuleFilters(rule, child, filterDefaultAction); } else if (child.MatchesName("logger") && loggerElement.MatchesName("logger")) { childRule = ParseRuleElement(child); } else if (child.MatchesName("rule") && loggerElement.MatchesName("rule")) { childRule = ParseRuleElement(child); } else { var configException = new NLogConfigurationException($"Unrecognized child element '{child.Name}' for element '{loggerElement.Name}' in section 'rules'"); if (MustThrowConfigException(configException)) throw configException; } if (childRule != null) { ValidateLoggingRuleFilters(rule); lock (rule.ChildRules) { rule.ChildRules.Add(childRule); } } } } private void ParseLoggingRuleFilters(LoggingRule rule, ValidatedConfigurationElement filtersElement, string filterDefaultAction = null) { filtersElement.AssertName("filters"); filterDefaultAction = filtersElement.GetOptionalValue("defaultAction", null) ?? filtersElement.GetOptionalValue(nameof(rule.FilterDefaultAction), null) ?? filterDefaultAction; if (filterDefaultAction != null) { SetPropertyValueFromString(rule, nameof(rule.FilterDefaultAction), filterDefaultAction, filtersElement); } foreach (var filterElement in filtersElement.ValidChildren) { var filterType = filterElement.GetOptionalValue("type", null) ?? filterElement.Name; Filter filter = FactoryCreateInstance(filterType, ConfigurationItemFactory.Default.FilterFactory); ConfigureFromAttributesAndElements(filter, filterElement); rule.Filters.Add(filter); } } private void ValidateLoggingRuleFilters(LoggingRule rule) { bool overridesDefaultAction = rule.Filters.Count == 0 || rule.FilterDefaultAction != FilterResult.Ignore; for (int i = 0; i < rule.Filters.Count; ++i) { if (rule.Filters[i].Action != FilterResult.Ignore && rule.Filters[i].Action != FilterResult.IgnoreFinal && rule.Filters[i].Action != FilterResult.Neutral) overridesDefaultAction = true; } if (!overridesDefaultAction) { var configException = new NLogConfigurationException($"LoggingRule where all filters and FilterDefaultAction=Ignore : {rule}"); if (MustThrowConfigException(configException)) throw configException; } } private void ParseTargetsElement(ValidatedConfigurationElement targetsElement) { targetsElement.AssertName("targets", "appenders"); bool asyncWrap = ParseBooleanValue("async", targetsElement.GetOptionalValue("async", "false"), false); ValidatedConfigurationElement defaultWrapperElement = null; Dictionary<string, ValidatedConfigurationElement> typeNameToDefaultTargetParameters = null; foreach (var targetElement in targetsElement.ValidChildren) { string targetTypeName = targetElement.GetConfigItemTypeAttribute(); string targetValueName = targetElement.GetOptionalValue("name", null); if (!string.IsNullOrEmpty(targetValueName)) targetValueName = $"{targetElement.Name}(Name={targetValueName})"; else targetValueName = targetElement.Name; switch (targetElement.Name?.Trim().ToUpperInvariant()) { case "DEFAULT-WRAPPER": case "TARGETDEFAULTWRAPPER": if (AssertNonEmptyValue(targetTypeName, "type", targetValueName, targetsElement.Name)) { defaultWrapperElement = targetElement; } break; case "DEFAULT-TARGET-PARAMETERS": case "TARGETDEFAULTPARAMETERS": if (AssertNonEmptyValue(targetTypeName, "type", targetValueName, targetsElement.Name)) { if (typeNameToDefaultTargetParameters is null) typeNameToDefaultTargetParameters = new Dictionary<string, ValidatedConfigurationElement>(StringComparer.OrdinalIgnoreCase); typeNameToDefaultTargetParameters[targetTypeName.Trim()] = targetElement; } break; case "TARGET": case "APPENDER": case "WRAPPER": case "WRAPPER-TARGET": case "COMPOUND-TARGET": if (AssertNonEmptyValue(targetTypeName, "type", targetValueName, targetsElement.Name)) { AddNewTargetFromConfig(targetTypeName, targetElement, asyncWrap, typeNameToDefaultTargetParameters, defaultWrapperElement); } break; default: var configException = new NLogConfigurationException($"Unrecognized element '{targetValueName}' in section '{targetsElement.Name}'"); if (MustThrowConfigException(configException)) throw configException; break; } } } private void AddNewTargetFromConfig(string targetTypeName, ValidatedConfigurationElement targetElement, bool asyncWrap, Dictionary<string, ValidatedConfigurationElement> typeNameToDefaultTargetParameters = null, ValidatedConfigurationElement defaultWrapperElement = null) { Target newTarget = null; try { newTarget = CreateTargetType(targetTypeName); if (newTarget != null) { ParseTargetElement(newTarget, targetElement, typeNameToDefaultTargetParameters); if (asyncWrap) { newTarget = WrapWithAsyncTargetWrapper(newTarget); } if (defaultWrapperElement != null) { newTarget = WrapWithDefaultWrapper(newTarget, defaultWrapperElement); } AddTarget(newTarget); } } catch (NLogConfigurationException ex) { if (MustThrowConfigException(ex)) throw; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException($"Target '{newTarget?.ToString() ?? targetTypeName}' has invalid config. Error: {ex.Message}", ex); if (MustThrowConfigException(configException)) throw; } } private Target CreateTargetType(string targetTypeName) { return FactoryCreateInstance(targetTypeName, ConfigurationItemFactory.Default.TargetFactory); } private void ParseTargetElement(Target target, ValidatedConfigurationElement targetElement, Dictionary<string, ValidatedConfigurationElement> typeNameToDefaultTargetParameters = null) { string targetTypeName = targetElement.GetConfigItemTypeAttribute("targets"); if (typeNameToDefaultTargetParameters != null && typeNameToDefaultTargetParameters.TryGetValue(targetTypeName, out var defaults)) { ParseTargetElement(target, defaults, null); } var compound = target as CompoundTargetBase; var wrapper = target as WrapperTargetBase; ConfigureObjectFromAttributes(target, targetElement); foreach (var childElement in targetElement.ValidChildren) { if (compound != null && ParseCompoundTarget(compound, childElement, typeNameToDefaultTargetParameters, null)) { continue; } if (wrapper != null && ParseTargetWrapper(wrapper, childElement, typeNameToDefaultTargetParameters)) { continue; } SetPropertyValuesFromElement(target, childElement, targetElement); } } private bool ParseTargetWrapper( WrapperTargetBase wrapper, ValidatedConfigurationElement childElement, Dictionary<string, ValidatedConfigurationElement> typeNameToDefaultTargetParameters) { if (IsTargetRefElement(childElement.Name)) { var targetName = childElement.GetRequiredValue("name", GetName(wrapper)); Target newTarget = FindTargetByName(targetName); if (newTarget is null) { var configException = new NLogConfigurationException($"Referenced target '{targetName}' not found."); if (MustThrowConfigException(configException)) throw configException; } wrapper.WrappedTarget = newTarget; return true; } if (IsTargetElement(childElement.Name)) { string targetTypeName = childElement.GetConfigItemTypeAttribute(GetName(wrapper)); Target newTarget = CreateTargetType(targetTypeName); if (newTarget != null) { ParseTargetElement(newTarget, childElement, typeNameToDefaultTargetParameters); if (!string.IsNullOrEmpty(newTarget.Name)) { // if the new target has name, register it AddTarget(newTarget.Name, newTarget); } else if (!string.IsNullOrEmpty(wrapper.Name)) { newTarget.Name = wrapper.Name + "_wrapped"; } if (wrapper.WrappedTarget != null) { var configException = new NLogConfigurationException($"Failed to assign wrapped target {targetTypeName}, because target {wrapper.Name} already has one."); if (MustThrowConfigException(configException)) throw configException; } } wrapper.WrappedTarget = newTarget; return true; } return false; } private bool ParseCompoundTarget( CompoundTargetBase compound, ValidatedConfigurationElement childElement, Dictionary<string, ValidatedConfigurationElement> typeNameToDefaultTargetParameters, string targetName) { if (MatchesName(childElement.Name, "targets") || MatchesName(childElement.Name, "appenders")) { foreach (var child in childElement.ValidChildren) { ParseCompoundTarget(compound, child, typeNameToDefaultTargetParameters, null); } return true; } if (IsTargetRefElement(childElement.Name)) { targetName = childElement.GetRequiredValue("name", GetName(compound)); Target newTarget = FindTargetByName(targetName); if (newTarget is null) { throw new NLogConfigurationException("Referenced target '" + targetName + "' not found."); } compound.Targets.Add(newTarget); return true; } if (IsTargetElement(childElement.Name)) { string targetTypeName = childElement.GetConfigItemTypeAttribute(GetName(compound)); Target newTarget = CreateTargetType(targetTypeName); if (newTarget != null) { if (targetName != null) newTarget.Name = targetName; ParseTargetElement(newTarget, childElement, typeNameToDefaultTargetParameters); if (newTarget.Name != null) { // if the new target has name, register it AddTarget(newTarget.Name, newTarget); } compound.Targets.Add(newTarget); } return true; } return false; } private void ConfigureObjectFromAttributes<T>(T targetObject, ValidatedConfigurationElement element, bool ignoreType = true) where T : class { foreach (var kvp in element.ValueLookup) { string childName = kvp.Key; string childValue = kvp.Value; if (ignoreType && MatchesName(childName, "type")) { continue; } SetPropertyValueFromString(targetObject, childName, childValue, element); } } private void SetPropertyValueFromString<T>(T targetObject, string propertyName, string propertyValue, ValidatedConfigurationElement element) where T : class { try { if (targetObject is null) { throw new NLogConfigurationException($"'{typeof(T).Name}' is null, and cannot assign property '{propertyName}'='{propertyValue}'"); } if (!PropertyHelper.TryGetPropertyInfo(ConfigurationItemFactory.Default, targetObject, propertyName, out var propertyInfo)) { throw new NLogConfigurationException($"'{targetObject.GetType()?.Name}' cannot assign unknown property '{propertyName}'='{propertyValue}'"); } var propertyValueExpanded = ExpandSimpleVariables(propertyValue, out var matchingVariableName); if (matchingVariableName != null && TryLookupDynamicVariable(matchingVariableName, out var matchingLayout)) { if (propertyInfo.PropertyType.IsAssignableFrom(matchingLayout.GetType())) { PropertyHelper.SetPropertyValueForObject(targetObject, matchingLayout, propertyInfo); return; } } PropertyHelper.SetPropertyFromString(targetObject, propertyInfo, propertyValueExpanded, ConfigurationItemFactory.Default); } catch (NLogConfigurationException ex) { if (MustThrowConfigException(ex)) throw; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException($"'{targetObject?.GetType()?.Name}' cannot assign property '{propertyName}'='{propertyValue}' in section '{element.Name}'. Error: {ex.Message}", ex); if (MustThrowConfigException(configException)) throw; } } private void SetPropertyValuesFromElement<T>(T targetObject, ValidatedConfigurationElement childElement, ILoggingConfigurationElement parentElement) where T : class { if (targetObject is null) { var configException = new NLogConfigurationException($"'{typeof(T).Name}' is null, and cannot assign property '{childElement.Name}' in section '{parentElement.Name}'"); if (MustThrowConfigException(configException)) throw configException; return; } if (!PropertyHelper.TryGetPropertyInfo(ConfigurationItemFactory.Default, targetObject, childElement.Name, out var propInfo)) { var configException = new NLogConfigurationException($"'{targetObject.GetType()?.Name}' cannot assign unknown property '{childElement.Name}' in section '{parentElement.Name}'"); if (MustThrowConfigException(configException)) throw configException; return; } if (AddArrayItemFromElement(targetObject, propInfo, childElement)) { return; } if (SetLayoutFromElement(targetObject, propInfo, childElement)) { return; } if (SetFilterFromElement(targetObject, propInfo, childElement)) { return; } object propertyValue = propInfo.GetValue(targetObject, null); ConfigureFromAttributesAndElements(propertyValue, childElement); } private bool AddArrayItemFromElement(object o, PropertyInfo propInfo, ValidatedConfigurationElement element) { Type elementType = PropertyHelper.GetArrayItemType(propInfo); if (elementType != null) { IList propertyValue = (IList)propInfo.GetValue(o, null); if (string.Equals(propInfo.Name, element.Name, StringComparison.OrdinalIgnoreCase)) { bool foundChild = false; foreach (var child in element.ValidChildren) { foundChild = true; propertyValue.Add(ParseArrayItemFromElement(elementType, child)); } if (foundChild) return true; } object arrayItem = ParseArrayItemFromElement(elementType, element); propertyValue.Add(arrayItem); return true; } return false; } private object ParseArrayItemFromElement(Type elementType, ValidatedConfigurationElement element) { object arrayItem = TryCreateLayoutInstance(element, elementType); // arrayItem is not a layout if (arrayItem is null) { if (!ConfigurationItemFactory.Default.TryCreateInstance(elementType, out arrayItem)) { throw new NLogConfigurationException($"Factory returned null for {elementType}"); } ConfigureFromAttributesAndElements(arrayItem, element); } return arrayItem; } private bool SetLayoutFromElement(object o, PropertyInfo propInfo, ValidatedConfigurationElement element) { var layout = TryCreateLayoutInstance(element, propInfo.PropertyType); // and is a Layout and 'type' attribute has been specified if (layout != null) { PropertyHelper.SetPropertyValueForObject(o, layout, propInfo); return true; } return false; } private bool SetFilterFromElement(object o, PropertyInfo propInfo, ValidatedConfigurationElement element) { Filter filter = TryCreateFilterInstance(element, propInfo.PropertyType); // and is a Filter and 'type' attribute has been specified if (filter != null) { PropertyHelper.SetPropertyValueForObject(o, filter, propInfo); return true; } return false; } private SimpleLayout CreateSimpleLayout(string layoutText) { return new SimpleLayout(layoutText, ConfigurationItemFactory.Default, LogFactory.ThrowConfigExceptions); } private Layout TryCreateLayoutInstance(ValidatedConfigurationElement element, Type type) { // Check if Layout type if (!typeof(Layout).IsAssignableFrom(type)) return null; // Check if the 'type' attribute has been specified string classType = element.GetConfigItemTypeAttribute(); if (classType is null) return null; var expandedClassType = ExpandSimpleVariables(classType, out var matchingVariableName); if (matchingVariableName != null && TryLookupDynamicVariable(matchingVariableName, out var matchingLayout)) { if (type.IsAssignableFrom(matchingLayout.GetType())) { return matchingLayout; } } var layoutInstance = FactoryCreateInstance(expandedClassType, ConfigurationItemFactory.Default.LayoutFactory); if (layoutInstance != null) { ConfigureFromAttributesAndElements(layoutInstance, element); return layoutInstance; } return null; } private Filter TryCreateFilterInstance(ValidatedConfigurationElement element, Type type) { var filter = TryCreateInstance(element, type, ConfigurationItemFactory.Default.FilterFactory); if (filter != null) { ConfigureFromAttributesAndElements(filter, element); return filter; } return null; } private T TryCreateInstance<T>(ValidatedConfigurationElement element, Type type, IFactory<T> factory) where T : class { // Check if correct type if (!typeof(T).IsAssignableFrom(type)) return null; // Check if the 'type' attribute has been specified string classType = element.GetConfigItemTypeAttribute(); if (classType is null) return null; return FactoryCreateInstance(classType, factory); } private T FactoryCreateInstance<T>(string typeName, IFactory<T> factory) where T : class { T newInstance = null; try { typeName = ExpandSimpleVariables(typeName); if (typeName.Contains(',')) { // Possible specification of assembly-name detected var shortName = typeName.Substring(0, typeName.IndexOf(',')).Trim(); if (factory.TryCreateInstance(shortName, out newInstance) && newInstance != null) return newInstance; var assemblyName = typeName.Substring(typeName.IndexOf(',') + 1).Trim(); if (!string.IsNullOrEmpty(assemblyName)) { // Attempt to load the assembly name extracted from the prefix if (RegisterExtensionFromAssemblyName(assemblyName, typeName)) { typeName = shortName; } } } newInstance = factory.CreateInstance(typeName); if (newInstance is null) { throw new NLogConfigurationException($"Factory returned null for {typeof(T).Name} of type: {typeName}"); } } catch (NLogConfigurationException configException) { if (MustThrowConfigException(configException)) throw; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException($"Failed to create {typeof(T).Name} of type: {typeName}", ex); if (MustThrowConfigException(configException)) throw configException; } return newInstance; } private void ConfigureFromAttributesAndElements<T>(T targetObject, ValidatedConfigurationElement element) where T : class { ConfigureObjectFromAttributes(targetObject, element); foreach (var childElement in element.ValidChildren) { SetPropertyValuesFromElement(targetObject, childElement, element); } } private static Target WrapWithAsyncTargetWrapper(Target target) { #if !NET35 if (target is AsyncTaskTarget) { InternalLogger.Debug("Skip wrapping target '{0}' with AsyncTargetWrapper", target.Name); return target; } #endif if (target is AsyncTargetWrapper) { InternalLogger.Debug("Skip wrapping target '{0}' with AsyncTargetWrapper", target.Name); return target; } var asyncTargetWrapper = new AsyncTargetWrapper(); asyncTargetWrapper.WrappedTarget = target; asyncTargetWrapper.Name = target.Name; target.Name = target.Name + "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}", asyncTargetWrapper.Name, target.Name); target = asyncTargetWrapper; return target; } private Target WrapWithDefaultWrapper(Target target, ValidatedConfigurationElement defaultWrapperElement) { string wrapperTypeName = defaultWrapperElement.GetConfigItemTypeAttribute("targets"); Target wrapperTargetInstance = CreateTargetType(wrapperTypeName); WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase; if (wtb is null) { throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper."); } ParseTargetElement(wrapperTargetInstance, defaultWrapperElement); while (wtb.WrappedTarget != null) { wtb = wtb.WrappedTarget as WrapperTargetBase; if (wtb is null) { throw new NLogConfigurationException( "Child target type specified on <default-wrapper /> is not a wrapper."); } } #if !NET35 if (target is AsyncTaskTarget && wrapperTargetInstance is AsyncTargetWrapper && ReferenceEquals(wrapperTargetInstance, wtb)) { InternalLogger.Debug("Skip wrapping target '{0}' with AsyncTargetWrapper", target.Name); return target; } #endif wtb.WrappedTarget = target; wrapperTargetInstance.Name = target.Name; target.Name = target.Name + "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name, wrapperTargetInstance.GetType(), target.Name); return wrapperTargetInstance; } /// <summary> /// Parse boolean /// </summary> /// <param name="propertyName">Name of the property for logging.</param> /// <param name="value">value to parse</param> /// <param name="defaultValue">Default value to return if the parse failed</param> /// <returns>Boolean attribute value or default.</returns> private bool ParseBooleanValue(string propertyName, string value, bool defaultValue) { try { return Convert.ToBoolean(value?.Trim(), CultureInfo.InvariantCulture); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException($"'{propertyName}' hasn't a valid boolean value '{value}'. {defaultValue} will be used", exception); if (MustThrowConfigException(configException)) throw configException; return defaultValue; } } private bool? ParseNullableBooleanValue(string propertyName, string value, bool defaultValue) { return StringHelpers.IsNullOrWhiteSpace(value) ? (bool?)null : ParseBooleanValue(propertyName, value, defaultValue); } private bool MustThrowConfigException(NLogConfigurationException configException) { if (configException.MustBeRethrown()) return true; // Global LogManager says throw if (LogFactory.ThrowConfigExceptions ?? LogFactory.ThrowExceptions) return true; // Local LogFactory says throw return false; } private static bool MatchesName(string key, string expectedKey) { return string.Equals(key?.Trim(), expectedKey, StringComparison.OrdinalIgnoreCase); } private static bool IsTargetElement(string name) { return name.Equals("target", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper-target", StringComparison.OrdinalIgnoreCase) || name.Equals("compound-target", StringComparison.OrdinalIgnoreCase); } private static bool IsTargetRefElement(string name) { return name.Equals("target-ref", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper-target-ref", StringComparison.OrdinalIgnoreCase) || name.Equals("compound-target-ref", StringComparison.OrdinalIgnoreCase); } private static string GetName(Target target) { return string.IsNullOrEmpty(target.Name) ? target.GetType().Name : target.Name; } /// <summary> /// Config element that's validated and having extra context /// </summary> private sealed class ValidatedConfigurationElement : ILoggingConfigurationElement { private static readonly IDictionary<string, string> EmptyDefaultDictionary = new SortHelpers.ReadOnlySingleBucketDictionary<string, string>(); private readonly ILoggingConfigurationElement _element; private readonly bool _throwConfigExceptions; private IList<ValidatedConfigurationElement> _validChildren; public static ValidatedConfigurationElement Create(ILoggingConfigurationElement element, LogFactory logFactory) { if (element is ValidatedConfigurationElement validConfig) return validConfig; bool throwConfigExceptions = (logFactory.ThrowConfigExceptions ?? logFactory.ThrowExceptions) || (LogManager.ThrowConfigExceptions ?? LogManager.ThrowExceptions); return new ValidatedConfigurationElement(element, throwConfigExceptions); } public ValidatedConfigurationElement(ILoggingConfigurationElement element, bool throwConfigExceptions) { _throwConfigExceptions = throwConfigExceptions; Name = element.Name.Trim(); ValueLookup = CreateValueLookup(element, throwConfigExceptions); _element = element; } public string Name { get; } public IDictionary<string, string> ValueLookup { get; } public IEnumerable<ValidatedConfigurationElement> ValidChildren { get { if (_validChildren is null) return YieldAndCacheValidChildren(); else return _validChildren; } } IEnumerable<ValidatedConfigurationElement> YieldAndCacheValidChildren() { IList<ValidatedConfigurationElement> validChildren = null; foreach (var child in _element.Children) { validChildren = validChildren ?? new List<ValidatedConfigurationElement>(); var validChild = new ValidatedConfigurationElement(child, _throwConfigExceptions); validChildren.Add(validChild); yield return validChild; } _validChildren = validChildren ?? ArrayHelper.Empty<ValidatedConfigurationElement>(); } public IEnumerable<KeyValuePair<string, string>> Values => ValueLookup; /// <remarks> /// Explicit cast because NET35 doesn't support covariance. /// </remarks> IEnumerable<ILoggingConfigurationElement> ILoggingConfigurationElement.Children => ValidChildren.Cast<ILoggingConfigurationElement>(); public string GetRequiredValue(string attributeName, string section) { string value = GetOptionalValue(attributeName, null); if (value is null) { throw new NLogConfigurationException($"Expected {attributeName} on {Name} in {section}"); } if (StringHelpers.IsNullOrWhiteSpace(value)) { throw new NLogConfigurationException( $"Expected non-empty {attributeName} on {Name} in {section}"); } return value; } public string GetOptionalValue(string attributeName, string defaultValue) { ValueLookup.TryGetValue(attributeName, out string value); return value ?? defaultValue; } private static IDictionary<string, string> CreateValueLookup(ILoggingConfigurationElement element, bool throwConfigExceptions) { IDictionary<string, string> valueLookup = null; List<string> warnings = null; foreach (var attribute in element.Values) { var attributeKey = attribute.Key?.Trim() ?? string.Empty; valueLookup = valueLookup ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); if (!string.IsNullOrEmpty(attributeKey) && !valueLookup.ContainsKey(attributeKey)) { valueLookup[attributeKey] = attribute.Value; } else { string validationError = string.IsNullOrEmpty(attributeKey) ? $"Invalid property for '{element.Name}' without name. Value={attribute.Value}" : $"Duplicate value for '{element.Name}'. PropertyName={attributeKey}. Skips Value={attribute.Value}. Existing Value={valueLookup[attributeKey]}"; InternalLogger.Debug("Skipping {0}", validationError); if (throwConfigExceptions) { warnings = warnings ?? new List<string>(); warnings.Add(validationError); } } } if (throwConfigExceptions && warnings?.Count > 0) { throw new NLogConfigurationException(StringHelpers.Join(Environment.NewLine, warnings)); } return valueLookup ?? EmptyDefaultDictionary; } public override string ToString() { return Name; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using NLog.Config; /// <summary> /// A specialized layout that renders JSON-formatted events. /// </summary> /// <remarks> /// <a href="https://github.com/NLog/NLog/wiki/JsonLayout">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/NLog/NLog/wiki/JsonLayout">Documentation on NLog Wiki</seealso> [Layout("JsonLayout")] [ThreadAgnostic] public class JsonLayout : Layout { private const int SpacesPerIndent = 2; private Layout[] _precalculateLayouts = null; private LimitRecursionJsonConvert JsonConverter { get => _jsonConverter ?? (_jsonConverter = new LimitRecursionJsonConvert(MaxRecursionLimit, EscapeForwardSlash, ResolveService<IJsonConverter>())); set => _jsonConverter = value; } private LimitRecursionJsonConvert _jsonConverter; private IValueFormatter ValueFormatter { get => _valueFormatter ?? (_valueFormatter = ResolveService<IValueFormatter>()); set => _valueFormatter = value; } private IValueFormatter _valueFormatter; class LimitRecursionJsonConvert : IJsonConverter { readonly IJsonConverter _converter; readonly Targets.DefaultJsonSerializer _serializer; readonly Targets.JsonSerializeOptions _serializerOptions; public LimitRecursionJsonConvert(int maxRecursionLimit, bool escapeForwardSlash, IJsonConverter converter) { _converter = converter; _serializer = converter as Targets.DefaultJsonSerializer; _serializerOptions = new Targets.JsonSerializeOptions() { MaxRecursionLimit = Math.Max(0, maxRecursionLimit), EscapeForwardSlash = escapeForwardSlash }; } public bool SerializeObject(object value, StringBuilder builder) { if (_serializer != null) return _serializer.SerializeObject(value, builder, _serializerOptions); else return _converter.SerializeObject(value, builder); } public bool SerializeObjectNoLimit(object value, StringBuilder builder) { return _converter.SerializeObject(value, builder); } } /// <summary> /// Initializes a new instance of the <see cref="JsonLayout"/> class. /// </summary> public JsonLayout() { ExcludeProperties = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Gets the array of attributes' configurations. /// </summary> /// <docgen category='Layout Options' order='10' /> [ArrayParameter(typeof(JsonAttribute), "attribute")] public IList<JsonAttribute> Attributes { get; } = new List<JsonAttribute>(); /// <summary> /// Gets or sets the option to suppress the extra spaces in the output json /// </summary> /// <docgen category='Layout Options' order='100' /> public bool SuppressSpaces { get; set; } /// <summary> /// Gets or sets the option to render the empty object value {} /// </summary> /// <docgen category='Layout Options' order='100' /> public bool RenderEmptyObject { get => _renderEmptyObject ?? true; set => _renderEmptyObject = value; } private bool? _renderEmptyObject; /// <summary> /// Auto indent and create new lines /// </summary> /// <docgen category='Layout Options' order='100' /> public bool IndentJson { get; set; } /// <summary> /// Gets or sets the option to include all properties from the log event (as JSON) /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeEventProperties { get; set; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="GlobalDiagnosticsContext"/> dictionary. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeGdc { get; set; } /// <summary> /// Gets or sets whether to include the contents of the <see cref="ScopeContext"/> dictionary. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeScopeProperties { get => _includeScopeProperties ?? (_includeMdlc == true || _includeMdc == true); set => _includeScopeProperties = value; } private bool? _includeScopeProperties; /// <summary> /// Gets or sets the option to include all properties from the log event (as JSON) /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeEventProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeAllProperties { get => IncludeEventProperties; set => IncludeEventProperties = value; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary. /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeMdc { get => _includeMdc ?? false; set => _includeMdc = value; } private bool? _includeMdc; /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsLogicalContext"/> dictionary. /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeMdlc { get => _includeMdlc ?? false; set => _includeMdlc = value; } private bool? _includeMdlc; /// <summary> /// Gets or sets the option to exclude null/empty properties from the log event (as JSON) /// </summary> /// <docgen category='Layout Options' order='100' /> public bool ExcludeEmptyProperties { get; set; } /// <summary> /// List of property names to exclude when <see cref="IncludeAllProperties"/> is true /// </summary> /// <docgen category='Layout Options' order='100' /> #if !NET35 public ISet<string> ExcludeProperties { get; set; } #else public HashSet<string> ExcludeProperties { get; set; } #endif /// <summary> /// How far should the JSON serializer follow object references before backing off /// </summary> /// <docgen category='Layout Options' order='100' /> public int MaxRecursionLimit { get; set; } = 1; /// <summary> /// Should forward slashes be escaped? If true, / will be converted to \/ /// </summary> /// <remarks> /// If not set explicitly then the value of the parent will be used as default. /// </remarks> /// <docgen category='Layout Options' order='100' /> public bool EscapeForwardSlash { get => _escapeForwardSlashInternal ?? false; set => _escapeForwardSlashInternal = value; } private bool? _escapeForwardSlashInternal; /// <inheritdoc/> protected override void InitializeLayout() { base.InitializeLayout(); if (IncludeScopeProperties) { ThreadAgnostic = false; } if (IncludeEventProperties) { MutableUnsafe = true; } _precalculateLayouts = (IncludeScopeProperties || IncludeEventProperties) ? null : ResolveLayoutPrecalculation(Attributes.Select(atr => atr.Layout)); if (_escapeForwardSlashInternal.HasValue && Attributes?.Count > 0) { foreach (var attribute in Attributes) { if (!attribute.EscapeForwardSlashInternal.HasValue) { attribute.EscapeForwardSlash = _escapeForwardSlashInternal.Value; } } } if (Attributes?.Count > 0) { foreach (var attribute in Attributes) { if (!attribute.IncludeEmptyValue && !attribute.Encode && attribute.Layout is JsonLayout jsonLayout) { if (!jsonLayout._renderEmptyObject.HasValue) { jsonLayout.RenderEmptyObject = false; } } } } } /// <inheritdoc/> protected override void CloseLayout() { JsonConverter = null; ValueFormatter = null; _precalculateLayouts = null; base.CloseLayout(); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { PrecalculateBuilderInternal(logEvent, target, _precalculateLayouts); } /// <inheritdoc/> protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { int orgLength = target.Length; RenderJsonFormattedMessage(logEvent, target); if (target.Length == orgLength && RenderEmptyObject) { target.Append(SuppressSpaces ? "{}" : "{ }"); } } /// <inheritdoc/> protected override string GetFormattedMessage(LogEventInfo logEvent) { return RenderAllocateBuilder(logEvent); } private void RenderJsonFormattedMessage(LogEventInfo logEvent, StringBuilder sb) { int orgLength = sb.Length; //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < Attributes.Count; i++) { var attrib = Attributes[i]; int beforeAttribLength = sb.Length; if (!RenderAppendJsonPropertyValue(attrib, logEvent, sb, sb.Length == orgLength)) { sb.Length = beforeAttribLength; } } if (IncludeGdc) { var gdcKeys = GlobalDiagnosticsContext.GetNames(); if (gdcKeys.Count > 0) { foreach (string key in gdcKeys) { if (string.IsNullOrEmpty(key)) continue; object propertyValue = GlobalDiagnosticsContext.GetObject(key); AppendJsonPropertyValue(key, propertyValue, null, null, MessageTemplates.CaptureType.Unknown, sb, sb.Length == orgLength); } } } if (IncludeScopeProperties) { bool checkExcludeProperties = ExcludeProperties.Count > 0; using (var scopeEnumerator = ScopeContext.GetAllPropertiesEnumerator()) { while (scopeEnumerator.MoveNext()) { var scopeProperty = scopeEnumerator.Current; if (string.IsNullOrEmpty(scopeProperty.Key)) continue; if (checkExcludeProperties && ExcludeProperties.Contains(scopeProperty.Key)) continue; AppendJsonPropertyValue(scopeProperty.Key, scopeProperty.Value, null, null, MessageTemplates.CaptureType.Unknown, sb, sb.Length == orgLength); } } } if (IncludeEventProperties && logEvent.HasProperties) { bool checkExcludeProperties = ExcludeProperties.Count > 0; IEnumerable<MessageTemplates.MessageTemplateParameter> propertiesList = logEvent.CreateOrUpdatePropertiesInternal(true); foreach (var prop in propertiesList) { if (string.IsNullOrEmpty(prop.Name)) continue; if (checkExcludeProperties && ExcludeProperties.Contains(prop.Name)) continue; AppendJsonPropertyValue(prop.Name, prop.Value, prop.Format, logEvent.FormatProvider, prop.CaptureType, sb, sb.Length == orgLength); } } if (sb.Length > orgLength) CompleteJsonMessage(sb); } private void BeginJsonProperty(StringBuilder sb, string propName, bool beginJsonMessage, bool ensureStringEscape) { if (beginJsonMessage) { if (IndentJson) sb.Append('{').AppendLine().Append(' ', SpacesPerIndent).Append('"'); else sb.Append(SuppressSpaces ? "{\"" : "{ \""); } else { if (IndentJson) sb.Append(',').AppendLine().Append(' ', SpacesPerIndent).Append('"'); else sb.Append(SuppressSpaces ? ",\"" : ", \""); } if (ensureStringEscape) Targets.DefaultJsonSerializer.AppendStringEscape(sb, propName, false, false); else sb.Append(propName); sb.Append(SuppressSpaces ? "\":" : "\": "); } private void CompleteJsonMessage(StringBuilder sb) { if (IndentJson) sb.AppendLine().Append('}'); else sb.Append(SuppressSpaces ? "}" : " }"); } private void AppendJsonPropertyValue(string propName, object propertyValue, string format, IFormatProvider formatProvider, MessageTemplates.CaptureType captureType, StringBuilder sb, bool beginJsonMessage) { if (ExcludeEmptyProperties && propertyValue is null) return; var initialLength = sb.Length; BeginJsonProperty(sb, propName, beginJsonMessage, true); if (MaxRecursionLimit <= 1 && captureType == MessageTemplates.CaptureType.Serialize) { // Overrides MaxRecursionLimit as message-template tells us it is safe if (!JsonConverter.SerializeObjectNoLimit(propertyValue, sb)) { sb.Length = initialLength; return; } } else if (captureType == MessageTemplates.CaptureType.Stringify) { // Overrides MaxRecursionLimit as message-template tells us it is unsafe int originalStart = sb.Length; ValueFormatter.FormatValue(propertyValue, format, captureType, formatProvider, sb); PerformJsonEscapeIfNeeded(sb, originalStart, EscapeForwardSlash); } else { if (!JsonConverter.SerializeObject(propertyValue, sb)) { sb.Length = initialLength; return; } } if (ExcludeEmptyProperties && (sb[sb.Length-1] == '"' && sb[sb.Length-2] == '"')) { sb.Length = initialLength; } } private static void PerformJsonEscapeIfNeeded(StringBuilder sb, int valueStart, bool escapeForwardSlash) { var builderLength = sb.Length; if (builderLength - valueStart <= 2) return; for (int i = valueStart + 1; i < builderLength - 1; ++i) { if (Targets.DefaultJsonSerializer.RequiresJsonEscape(sb[i], false, escapeForwardSlash)) { var jsonEscape = sb.ToString(valueStart + 1, sb.Length - valueStart - 2); sb.Length = valueStart; sb.Append('"'); Targets.DefaultJsonSerializer.AppendStringEscape(sb, jsonEscape, false, escapeForwardSlash); sb.Append('"'); break; } } } private bool RenderAppendJsonPropertyValue(JsonAttribute attrib, LogEventInfo logEvent, StringBuilder sb, bool beginJsonMessage) { BeginJsonProperty(sb, attrib.Name, beginJsonMessage, false); if (!attrib.RenderAppendJsonValue(logEvent, JsonConverter, sb)) { return false; } return true; } /// <inheritdoc/> public override string ToString() { return ToStringWithNestedItems(Attributes, a => string.Concat(a.Name, "-", a.Layout?.ToString())); } } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text.RegularExpressions; namespace NLog.SourceCodeTests { /// <summary> /// Source code tests. /// </summary> public class SourceCodeTests { private static readonly Regex ClassNameRegex = new Regex(@"^\s+(public |abstract |sealed |static |partial |internal )*\s*(class|interface|struct|enum)\s+(?<className>\w+)\b", RegexOptions.Compiled); private static readonly Regex DelegateTypeRegex = new Regex(@"^ (public |internal )delegate .*\b(?<delegateType>\w+)\(", RegexOptions.Compiled); private static List<string> _directoriesToVerify; private readonly bool _verifyNamespaces; private readonly IList<string> _fileNamesToIgnore; private readonly string _rootDir; private string _licenseFile; private readonly string[] _licenseLines; public SourceCodeTests() { _rootDir = FindRootDir(); _directoriesToVerify = GetAppSettingAsList("VerifyFiles.Paths"); _fileNamesToIgnore = GetAppSettingAsList("VerifyFiles.IgnoreFiles"); _verifyNamespaces = false; //off for now (april 2019) - so we could create folders and don't break stuff if (_rootDir != null) { _licenseLines = File.ReadAllLines(_licenseFile); } else { throw new Exception("root not found (where LICENSE.txt is located)"); } } private static List<string> GetAppSettingAsList(string setting) { return ConfigurationManager.AppSettings[setting].Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList(); } /// <summary> /// Find source root by finding LICENSE.txt /// </summary> private string FindRootDir() { var dir = ConfigurationManager.AppSettings["rootdir"]; dir = Path.GetFullPath(dir); while (dir != null) { _licenseFile = Path.Combine(dir, "LICENSE.txt"); if (File.Exists(_licenseFile)) { break; } dir = Path.GetDirectoryName(dir); } return dir; } public bool VerifyFileHeaders() { var missing = FindFilesWithMissingHeaders().ToList(); return ReportErrors(missing, "Missing headers (copy them form other another file)."); } private IEnumerable<string> FindFilesWithMissingHeaders() { foreach (string dir in _directoriesToVerify) { foreach (string file in Directory.GetFiles(Path.Combine(_rootDir, dir), "*.cs", SearchOption.AllDirectories)) { if (ShouldIgnoreFileForVerify(file)) { continue; } if (!VerifyFileHeader(file)) { yield return file; } } } } public bool VerifyNamespacesAndClassNames() { var errors = new List<string>(); foreach (string dir in _directoriesToVerify) { VerifyClassNames(Path.Combine(_rootDir, dir), Path.GetFileName(dir), errors); } return ReportErrors(errors, "Namespace or classname not in-sync with file name."); } bool ShouldIgnoreFileForVerify(string filePath) { string baseName = Path.GetFileName(filePath); if (baseName == null || _fileNamesToIgnore.Contains(baseName)) { return true; } if (baseName.IndexOf(".xaml", StringComparison.OrdinalIgnoreCase) >= 0) { return true; } if (baseName.IndexOf(".g.", StringComparison.OrdinalIgnoreCase) >= 0) { return true; } if (baseName.IndexOf(".designer.", StringComparison.OrdinalIgnoreCase) >= 0) { return true; } if (baseName == "ExtensionAttribute.cs") { return true; } if (baseName == "NUnitAdapter.cs") { return true; } if (baseName == "LocalizableAttribute.cs") { return true; } if (baseName == "Annotations.cs") { return true; } return false; } private bool VerifyFileHeader(string filePath) { if (FileInObjFolder(filePath)) { //don't scan files in obj folder return true; } using (StreamReader reader = File.OpenText(filePath)) { for (int i = 0; i < _licenseLines.Length; ++i) { string line = reader.ReadLine(); string expected = "// " + _licenseLines[i]; if (line != expected) { return false; } } return true; } } private static bool FileInObjFolder(string path) { return path.Contains("/obj/") || path.Contains("\\obj\\") || path.StartsWith("obj/", StringComparison.InvariantCultureIgnoreCase) || path.StartsWith("obj\\", StringComparison.InvariantCultureIgnoreCase); } private void VerifyClassNames(string path, string expectedNamespace, List<string> errors) { if (FileInObjFolder(path)) { return; } foreach (string filePath in Directory.GetFiles(path, "*.cs")) { if (ShouldIgnoreFileForVerify(filePath)) { continue; } string expectedClassName = Path.GetFileNameWithoutExtension(filePath); if (expectedClassName != null) { int p = expectedClassName.IndexOf('-'); if (p >= 0) { expectedClassName = expectedClassName.Substring(0, p); } var fileErrors = VerifySingleFile(filePath, expectedNamespace, expectedClassName); errors.AddRange(fileErrors.Select(errorMessage => $"{filePath}:{errorMessage}")); } } foreach (string dir in Directory.GetDirectories(path)) { VerifyClassNames(dir, expectedNamespace + "." + Path.GetFileName(dir), errors); } } ///<summary>Verify classname and namespace in a file.</summary> ///<returns>errors</returns> private IEnumerable<string> VerifySingleFile(string filePath, string expectedNamespace, string expectedClassName) { //ignore list if (filePath != null && !filePath.EndsWith("nunit.cs", StringComparison.InvariantCultureIgnoreCase)) { HashSet<string> classNames = new HashSet<string>(); using (StreamReader sr = File.OpenText(filePath)) { string line; while ((line = sr.ReadLine()) != null) { if (_verifyNamespaces) { if (line.StartsWith("namespace ", StringComparison.Ordinal)) { string ns = line.Substring(10); if (expectedNamespace != ns) { yield return $"Invalid namespace: '{ns}' Expected: '{expectedNamespace}'"; } } } Match match = ClassNameRegex.Match(line); if (match.Success) { classNames.Add(match.Groups["className"].Value); } match = DelegateTypeRegex.Match(line); if (match.Success) { classNames.Add(match.Groups["delegateType"].Value); } } } if (classNames.Count == 0) { //Console.WriteLine("No classes found in {0}", file); //ignore, because of files not used in other projects } else if (!classNames.Contains(expectedClassName)) { yield return $"Invalid class name. Expected '{expectedClassName}', actual: '{string.Join(",", classNames)}'"; } } } private static bool ReportErrors(List<string> errors, string globalErrorMessage) { var count = errors.Count; if (count == 0) { return true; } var fullMessage = $"{globalErrorMessage}\n{count} errors: \n -------- \n-{string.Join("\n- ", errors)} \n\n"; Console.Error.WriteLine(fullMessage); return false; } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal.NetworkSenders { using System; using System.Collections.Generic; using NLog.Common; using NLog.Targets; /// <summary> /// A base class for network senders that can block or send out-of-order /// </summary> internal abstract class QueuedNetworkSender : NetworkSender { protected struct NetworkRequestArgs { public NetworkRequestArgs(byte[] buffer, int offset, int length, AsyncContinuation asyncContinuation) { AsyncContinuation = asyncContinuation; RequestBuffer = buffer; RequestBufferOffset = offset; RequestBufferLength = length; } public readonly AsyncContinuation AsyncContinuation; public readonly byte[] RequestBuffer; public readonly int RequestBufferOffset; public readonly int RequestBufferLength; } private readonly Queue<NetworkRequestArgs> _pendingRequests = new Queue<NetworkRequestArgs>(); private readonly Queue<NetworkRequestArgs> _activeRequests = new Queue<NetworkRequestArgs>(); private Exception _pendingError; private bool _asyncOperationInProgress; private AsyncContinuation _closeContinuation; private AsyncContinuation _flushContinuation; /// <summary> /// Initializes a new instance of the <see cref="QueuedNetworkSender"/> class. /// </summary> /// <param name="url">URL. Must start with tcp://.</param> protected QueuedNetworkSender(string url) : base(url) { } public int MaxQueueSize { get; set; } public NetworkTargetQueueOverflowAction OnQueueOverflow { get; set; } public event EventHandler<NetworkLogEventDroppedEventArgs> LogEventDropped; protected override void DoSend(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation) { NetworkRequestArgs? eventArgs = new NetworkRequestArgs(bytes, offset, length, asyncContinuation); AsyncContinuation failedContinuation = null; lock (_pendingRequests) { if (_pendingError is null) { if (_pendingRequests.Count >= MaxQueueSize && MaxQueueSize > 0) { switch (OnQueueOverflow) { case NetworkTargetQueueOverflowAction.Discard: InternalLogger.Debug("NetworkTarget - Discarding single item, because queue is full"); OnLogEventDropped(this, NetworkLogEventDroppedEventArgs.MaxQueueOverflow); var dequeued = _pendingRequests.Dequeue(); dequeued.AsyncContinuation?.Invoke(null); break; case NetworkTargetQueueOverflowAction.Grow: InternalLogger.Debug("NetworkTarget - Growing the size of queue, because queue is full"); MaxQueueSize *= 2; break; case NetworkTargetQueueOverflowAction.Block: while (_pendingRequests.Count >= MaxQueueSize && _pendingError is null) { InternalLogger.Debug("NetworkTarget - Blocking until ready, because queue is full"); System.Threading.Monitor.Wait(_pendingRequests); InternalLogger.Trace("NetworkTarget - Entered critical section for queue."); } InternalLogger.Trace("NetworkTarget - Queue Limit ok."); break; } } if (_pendingError is null) { if (!_asyncOperationInProgress) { _asyncOperationInProgress = true; } else { _pendingRequests.Enqueue(eventArgs.Value); eventArgs = null; } } else { failedContinuation = asyncContinuation; eventArgs = null; } } else { failedContinuation = asyncContinuation; eventArgs = null; } } if (eventArgs.HasValue) { BeginRequest(eventArgs.Value); } failedContinuation?.Invoke(_pendingError); } protected override void DoFlush(AsyncContinuation continuation) { lock (_pendingRequests) { if (_asyncOperationInProgress || _pendingRequests.Count != 0 || _activeRequests.Count != 0) { if (_flushContinuation != null) { var flushChain = _flushContinuation; _flushContinuation = (ex) => { flushChain(ex); continuation(ex); }; } else { _flushContinuation = continuation; } return; } } continuation(null); } protected override void DoClose(AsyncContinuation continuation) { lock (_pendingRequests) { if (_asyncOperationInProgress) { _closeContinuation = continuation; return; } } continuation(null); } protected void BeginInitialize() { lock (_pendingRequests) { _asyncOperationInProgress = true; } } protected NetworkRequestArgs? EndRequest(AsyncContinuation asyncContinuation, Exception pendingException) { if (pendingException != null) { lock (_pendingRequests) { _pendingError = pendingException; } } try { asyncContinuation?.Invoke(pendingException); // Will attempt to close socket on error return DequeueNextItem(); } catch (Exception ex) { #if DEBUG if (ex.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application } #endif if (_pendingError is null) InternalLogger.Error(ex, "NetworkTarget: Error completing network request"); else InternalLogger.Error(ex, "NetworkTarget: Error completing failed network request"); return null; } } protected abstract void BeginRequest(NetworkRequestArgs eventArgs); private NetworkRequestArgs? DequeueNextItem() { AsyncContinuation closeContinuation; AsyncContinuation flushContinuation; lock (_activeRequests) { if (_pendingError is null) { if (_activeRequests.Count != 0) { _asyncOperationInProgress = true; return _activeRequests.Dequeue(); } } else { SignalSocketFailedForPendingRequests(_pendingError); } lock (_pendingRequests) { _asyncOperationInProgress = false; if (_pendingRequests.Count == 0) { flushContinuation = _flushContinuation; if (flushContinuation != null) { _flushContinuation = null; } closeContinuation = _closeContinuation; if (closeContinuation != null) { _closeContinuation = null; } } else { try { _asyncOperationInProgress = true; if (_pendingRequests.Count == 1) { return _pendingRequests.Dequeue(); } else { int nextBatchSize = Math.Min(_pendingRequests.Count, MaxQueueSize / 2 + 1000); for (int i = 0; i < nextBatchSize; ++i) { _activeRequests.Enqueue(_pendingRequests.Dequeue()); } return _activeRequests.Dequeue(); } } finally { if (OnQueueOverflow == NetworkTargetQueueOverflowAction.Block) { System.Threading.Monitor.PulseAll(_pendingRequests); } } } } } flushContinuation?.Invoke(_pendingError); closeContinuation?.Invoke(_pendingError); return null; } private void SignalSocketFailedForPendingRequests(Exception pendingException) { lock (_pendingRequests) { while (_pendingRequests.Count != 0) _activeRequests.Enqueue(_pendingRequests.Dequeue()); System.Threading.Monitor.PulseAll(_pendingRequests); } while (_activeRequests.Count != 0) { var eventArgs = _activeRequests.Dequeue(); eventArgs.AsyncContinuation?.Invoke(pendingException); } } private void OnLogEventDropped(object sender, NetworkLogEventDroppedEventArgs logEventDroppedEventArgs) { LogEventDropped?.Invoke(this, logEventDroppedEventArgs); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Globalization; namespace NLog.UnitTests.LayoutRenderers { using NLog.Layouts; using Xunit; public class TicksLayoutRendererTests : NLogTestBase { [Fact] public void RenderTicksLayoutRenderer() { Layout layout = "${ticks}"; var logEventInfo = LogEventInfo.Create(LogLevel.Debug, "logger1","test message"); var now = DateTime.Now; logEventInfo.TimeStamp = now; string actual = layout.Render(logEventInfo); layout.Close(); Assert.NotNull(actual); Assert.Equal(actual, now.Ticks.ToString(CultureInfo.InvariantCulture)); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; /// <summary> /// Value indicating how stack trace should be captured when processing the log event. /// </summary> [Flags] public enum StackTraceUsage { /// <summary> /// No Stack trace needs to be captured. /// </summary> None = 0, /// <summary> /// Stack trace should be captured. This option won't add the filenames and linenumbers /// </summary> WithStackTrace = 1, /// <summary> /// Capture also filenames and linenumbers /// </summary> WithFileNameAndLineNumber = 2, /// <summary> /// Capture the location of the call /// </summary> WithCallSite = 4, /// <summary> /// Capture the class name for location of the call /// </summary> WithCallSiteClassName = 8, /// <summary> /// Stack trace should be captured. This option won't add the filenames and linenumbers. /// </summary> [Obsolete("Replace with `WithStackTrace`. Marked obsolete on NLog 5.0")] WithoutSource = WithStackTrace, /// <summary> /// Stack trace should be captured including filenames and linenumbers. /// </summary> WithSource = WithStackTrace | WithFileNameAndLineNumber, /// <summary> /// Capture maximum amount of the stack trace information supported on the platform. /// </summary> Max = WithSource, } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using System; using System.Threading; using NLog.Common; using NLog.Internal; using NLog.Layouts; /// <summary> /// A target that buffers log events and sends them in batches to the wrapped target. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/BufferingWrapper-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/BufferingWrapper-target">Documentation on NLog Wiki</seealso> [Target("BufferingWrapper", IsWrapper = true)] public class BufferingTargetWrapper : WrapperTargetBase { private AsyncRequestQueue _buffer; private Timer _flushTimer; private readonly object _lockObject = new object(); /// <summary> /// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class. /// </summary> public BufferingTargetWrapper() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class. /// </summary> /// <param name="name">Name of the target.</param> /// <param name="wrappedTarget">The wrapped target.</param> public BufferingTargetWrapper(string name, Target wrappedTarget) : this(wrappedTarget) { Name = name ?? Name; } /// <summary> /// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> public BufferingTargetWrapper(Target wrappedTarget) : this(wrappedTarget, 100) { } /// <summary> /// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="bufferSize">Size of the buffer.</param> public BufferingTargetWrapper(Target wrappedTarget, int bufferSize) : this(wrappedTarget, bufferSize, -1) { } /// <summary> /// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="bufferSize">Size of the buffer.</param> /// <param name="flushTimeout">The flush timeout.</param> public BufferingTargetWrapper(Target wrappedTarget, int bufferSize, int flushTimeout) : this(wrappedTarget, bufferSize, flushTimeout, BufferingTargetWrapperOverflowAction.Flush) { } /// <summary> /// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="bufferSize">Size of the buffer.</param> /// <param name="flushTimeout">The flush timeout.</param> /// <param name="overflowAction">The action to take when the buffer overflows.</param> public BufferingTargetWrapper(Target wrappedTarget, int bufferSize, int flushTimeout, BufferingTargetWrapperOverflowAction overflowAction) { Name = string.IsNullOrEmpty(wrappedTarget?.Name) ? Name : (wrappedTarget.Name + "_wrapped"); WrappedTarget = wrappedTarget; BufferSize = bufferSize; FlushTimeout = flushTimeout; OverflowAction = overflowAction; } /// <summary> /// Gets or sets the number of log events to be buffered. /// </summary> /// <docgen category='Buffering Options' order='10' /> public Layout<int> BufferSize { get; set; } /// <summary> /// Gets or sets the timeout (in milliseconds) after which the contents of buffer will be flushed /// if there's no write in the specified period of time. Use -1 to disable timed flushes. /// </summary> /// <docgen category='Buffering Options' order='100' /> public Layout<int> FlushTimeout { get; set; } /// <summary> /// Gets or sets a value indicating whether to use sliding timeout. /// </summary> /// <remarks> /// This value determines how the inactivity period is determined. If sliding timeout is enabled, /// the inactivity timer is reset after each write, if it is disabled - inactivity timer will /// count from the first event written to the buffer. /// </remarks> /// <docgen category='Buffering Options' order='100' /> public bool SlidingTimeout { get; set; } = true; /// <summary> /// Gets or sets the action to take if the buffer overflows. /// </summary> /// <remarks> /// Setting to <see cref="BufferingTargetWrapperOverflowAction.Discard"/> will replace the /// oldest event with new events without sending events down to the wrapped target, and /// setting to <see cref="BufferingTargetWrapperOverflowAction.Flush"/> will flush the /// entire buffer to the wrapped target. /// </remarks> /// <docgen category='Buffering Options' order='50' /> public BufferingTargetWrapperOverflowAction OverflowAction { get; set; } /// <summary> /// Flushes pending events in the buffer (if any), followed by flushing the WrappedTarget. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { WriteEventsInBuffer("Flush Async"); base.FlushAsync(asyncContinuation); } /// <inheritdoc/> protected override void InitializeTarget() { base.InitializeTarget(); var bufferSize = RenderLogEvent(BufferSize, LogEventInfo.CreateNullEvent()); _buffer = new AsyncRequestQueue(bufferSize, AsyncTargetWrapperOverflowAction.Discard); InternalLogger.Trace("{0}: Create Timer", this); var flushTimeout = RenderLogEvent(FlushTimeout, LogEventInfo.CreateNullEvent()); _flushTimer = new Timer(FlushCallback, (int?)flushTimeout, Timeout.Infinite, Timeout.Infinite); } /// <summary> /// Closes the target by flushing pending events in the buffer (if any). /// </summary> protected override void CloseTarget() { var currentTimer = _flushTimer; if (currentTimer != null) { _flushTimer = null; if (currentTimer.WaitForDispose(TimeSpan.FromSeconds(1))) { if (OverflowAction == BufferingTargetWrapperOverflowAction.Discard) { _buffer.Clear(); } else { WriteEventsInBuffer("Closing Target"); } } } base.CloseTarget(); } /// <summary> /// Adds the specified log event to the buffer and flushes /// the buffer in case the buffer gets full. /// </summary> /// <param name="logEvent">The log event.</param> protected override void Write(AsyncLogEventInfo logEvent) { PrecalculateVolatileLayouts(logEvent.LogEvent); var firstEventInQueue = _buffer.Enqueue(logEvent); if (_buffer.RequestCount >= _buffer.RequestLimit) { // If the OverflowAction action is set to "Discard", the buffer will automatically // roll over the oldest item. if (OverflowAction == BufferingTargetWrapperOverflowAction.Flush) { WriteEventsInBuffer("Exceeding BufferSize"); } } else { if (SlidingTimeout || firstEventInQueue) { var flushTimeout = RenderLogEvent(FlushTimeout, logEvent.LogEvent); if (flushTimeout > 0) { // reset the timer on first item added to the buffer or whenever SlidingTimeout is set to true _flushTimer.Change(flushTimeout, -1); } } } } private void FlushCallback(object state) { bool lockTaken = false; try { var flushTimeout = (state as int?) ?? 0; int timeoutMilliseconds = Math.Min(flushTimeout / 2, 100); lockTaken = Monitor.TryEnter(_lockObject, timeoutMilliseconds); if (lockTaken) { if (_flushTimer is null) return; WriteEventsInBuffer(null); } else { if (!_buffer.IsEmpty) _flushTimer?.Change(timeoutMilliseconds, -1); // Schedule new retry timer } } catch (Exception exception) { #if DEBUG if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } #endif InternalLogger.Error(exception, "{0}: Error in flush procedure.", this); } finally { if (lockTaken) { Monitor.Exit(_lockObject); } } } private void WriteEventsInBuffer(string reason) { if (WrappedTarget is null) { InternalLogger.Error("{0}: WrappedTarget is NULL", this); return; } lock (_lockObject) { AsyncLogEventInfo[] logEvents = _buffer.DequeueBatch(int.MaxValue); if (logEvents.Length > 0) { if (reason != null) InternalLogger.Trace("{0}: Writing {1} events ({2})", this, logEvents.Length, reason); WrappedTarget.WriteAsyncLogEvents(logEvents); } } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Layouts { using System; using System.Collections.Generic; using System.Linq; using NLog.Config; using NLog.Layouts; using NLog.Targets; using Xunit; public class JsonLayoutTests : NLogTestBase { private const string ExpectedIncludeAllPropertiesWithExcludes = "{ \"StringProp\": \"ValueA\", \"IntProp\": 123, \"DoubleProp\": 123.123, \"DecimalProp\": 123.123, \"BoolProp\": true, \"NullProp\": null, \"DateTimeProp\": \"2345-01-23T12:34:56Z\" }"; private const string ExpectedExcludeEmptyPropertiesWithExcludes = "{ \"StringProp\": \"ValueA\", \"IntProp\": 123, \"DoubleProp\": 123.123, \"DecimalProp\": 123.123, \"BoolProp\": true, \"DateTimeProp\": \"2345-01-23T12:34:56Z\", \"NoEmptyProp4\": \"hello\" }"; [Fact] public void JsonLayoutRendering() { var jsonLayout = new JsonLayout() { Attributes = { new JsonAttribute("date", "${longdate}"), new JsonAttribute("level", "${level}"), new JsonAttribute("message", "${message}"), } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" }; Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": \"hello, world\" }", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonLayoutRenderingIndentJson() { var jsonLayout = new JsonLayout() { Attributes = { new JsonAttribute("date", "${longdate}"), new JsonAttribute("level", "${level}"), new JsonAttribute("message", "${message}"), }, IndentJson = true }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" }; Assert.Equal($"{{{Environment.NewLine} \"date\": \"2010-01-01 12:34:56.0000\",{Environment.NewLine} \"level\": \"Info\",{Environment.NewLine} \"message\": \"hello, world\"{Environment.NewLine}}}", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonLayoutRenderingNoSpaces() { var jsonLayout = new JsonLayout() { Attributes = { new JsonAttribute("date", "${longdate}"), new JsonAttribute("level", "${level}"), new JsonAttribute("message", "${message}"), }, SuppressSpaces = true }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" }; Assert.Equal("{\"date\":\"2010-01-01 12:34:56.0000\",\"level\":\"Info\",\"message\":\"hello, world\"}", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonLayoutRenderingEscapeUnicode() { var jsonLayout = new JsonLayout() { Attributes = { new JsonAttribute("logger", "${logger}") { EscapeUnicode = true }, new JsonAttribute("level", "${level}"), new JsonAttribute("message", "${event-properties:msg}") { EscapeUnicode = false }, }, SuppressSpaces = true, IncludeEventProperties = true, }; var logEventInfo = LogEventInfo.Create(LogLevel.Info, "\u00a9", null, "{$a}", new object[] { "\\" }); logEventInfo.Properties["msg"] = "\u00a9"; Assert.Equal("{\"logger\":\"\\u00a9\",\"level\":\"Info\",\"message\":\"\u00a9\",\"a\":\"\\\\\",\"msg\":\"\u00a9\"}", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonLayoutRenderingAndEncodingSpecialCharacters() { var jsonLayout = new JsonLayout() { Attributes = { new JsonAttribute("date", "${longdate}"), new JsonAttribute("level", "${level}"), new JsonAttribute("message", "${message}"), } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "\"hello, world\"" }; Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": \"\\\"hello, world\\\"\" }", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonLayoutRenderingAndEncodingLineBreaks() { var jsonLayout = new JsonLayout() { Attributes = { new JsonAttribute("date", "${longdate}"), new JsonAttribute("level", "${level}"), new JsonAttribute("message", "${message}"), } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello,\n\r world" }; Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": \"hello,\\n\\r world\" }", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonLayoutRenderingAndNotEncodingMessageAttribute() { var jsonLayout = new JsonLayout() { Attributes = { new JsonAttribute("date", "${longdate}"), new JsonAttribute("level", "${level}"), new JsonAttribute("message", "${message}", false), } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "{ \"hello\" : \"world\" }" }; Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": { \"hello\" : \"world\" } }", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonLayoutRenderingAndEncodingMessageAttribute() { var jsonLayout = new JsonLayout() { Attributes = { new JsonAttribute("date", "${longdate}"), new JsonAttribute("level", "${level}"), new JsonAttribute("message", "${message}"), } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "{ \"hello\" : \"world\" }" }; Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": \"{ \\\"hello\\\" : \\\"world\\\" }\" }", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonLayoutValueTypeAttribute() { var jsonLayout = new JsonLayout() { Attributes = { new JsonAttribute("date", "${longdate}") { ValueType = typeof(DateTime) }, new JsonAttribute("level", "${level}"), new JsonAttribute("message", "${message}"), } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "{ \"hello\" : \"world\" }" }; Assert.Equal("{ \"date\": \"2010-01-01T12:34:56Z\", \"level\": \"Info\", \"message\": \"{ \\\"hello\\\" : \\\"world\\\" }\" }", jsonLayout.Render(logEventInfo)); } [Fact] public void JsonAttributeThreadAgnosticTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets async='true'> <target name='debug' type='Debug'> <layout type='JsonLayout'> <attribute name='type' layout='${exception:format=Type}'/> <attribute name='message' layout='${exception:format=Message}'/> <attribute name='threadid' layout='${threadid}'/> </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("B"); var logEventInfo = CreateLogEventWithExcluded(); logger.Debug(logEventInfo); var target = logFactory.Configuration.AllTargets.OfType<DebugTarget>().First(); logFactory.Shutdown(); // Flush var message = target.LastMessage; Assert.Contains(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), message); } [Fact] public void JsonAttributeStackTraceUsageTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' > <layout type='JsonLayout'> <attribute name='type' layout='${exception:format=Type}'/> <attribute name='message' layout='${exception:format=Message}'/> <attribute name='className' layout='${callsite:className=true}'/> </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("C"); var logEventInfo = CreateLogEventWithExcluded(); logger.Debug(logEventInfo); var message = GetDebugLastMessage("debug", logFactory); Assert.Contains(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, message); } [Fact] public void NestedJsonAttrTest() { var jsonLayout = new JsonLayout { Attributes = { new JsonAttribute("type", "${exception:format=Type}"), new JsonAttribute("message", "${exception:format=Message}"), new JsonAttribute("innerException", new JsonLayout { Attributes = { new JsonAttribute("type", "${exception:format=:innerFormat=Type:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"), new JsonAttribute("message", "${exception:format=:innerFormat=Message:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"), } }, //don't escape layout false) } }; var logEventInfo = new LogEventInfo { Exception = new NLogRuntimeException("test", new NullReferenceException("null is bad!")) }; var json = jsonLayout.Render(logEventInfo); Assert.Equal("{ \"type\": \"NLog.NLogRuntimeException\", \"message\": \"test\", \"innerException\": { \"type\": \"System.NullReferenceException\", \"message\": \"null is bad!\" } }", json); } [Fact] public void NestedJsonAttrDoesNotRenderEmptyLiteralIfRenderEmptyObjectIsFalseTest() { var jsonLayout = new JsonLayout { Attributes = { new JsonAttribute("type", "${exception:format=Type}"), new JsonAttribute("message", "${exception:format=Message}"), new JsonAttribute("innerException", new JsonLayout { Attributes = { new JsonAttribute("type", "${exception:format=:innerFormat=Type:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"), new JsonAttribute("message", "${exception:format=:innerFormat=Message:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"), }, RenderEmptyObject = false }, //don't escape layout false) } }; var logEventInfo = new LogEventInfo { Exception = new NLogRuntimeException("test", (Exception)null) }; var json = jsonLayout.Render(logEventInfo); Assert.Equal("{ \"type\": \"NLog.NLogRuntimeException\", \"message\": \"test\" }", json); } [Fact] public void NestedJsonAttrRendersEmptyLiteralIfRenderEmptyObjectIsTrueTest() { var jsonLayout = new JsonLayout { Attributes = { new JsonAttribute("type", "${exception:format=Type}"), new JsonAttribute("message", "${exception:format=Message}"), new JsonAttribute("innerException", new JsonLayout { Attributes = { new JsonAttribute("type", "${exception:format=:innerFormat=Type:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"), new JsonAttribute("message", "${exception:format=:innerFormat=Message:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"), }, RenderEmptyObject = true }, //don't escape layout false) } }; var logEventInfo = new LogEventInfo { Exception = new NLogRuntimeException("test", (Exception)null) }; var json = jsonLayout.Render(logEventInfo); Assert.Equal("{ \"type\": \"NLog.NLogRuntimeException\", \"message\": \"test\", \"innerException\": { } }", json); } [Fact] public void NestedJsonAttrTestFromXML() { var configXml = @" <nlog> <targets> <target name='jsonFile' type='File' fileName='log.json'> <layout type='JsonLayout'> <attribute name='time' layout='${longdate}' /> <attribute name='level' layout='${level:upperCase=true}'/> <attribute name='nested' encode='false' > <layout type='JsonLayout'> <attribute name='message' layout='${message}' /> <attribute name='exception' layout='${exception:message}' /> </layout> </attribute> </layout> </target> </targets> <rules> </rules> </nlog> "; var config = XmlLoggingConfiguration.CreateFromXmlString(configXml); Assert.NotNull(config); var target = config.FindTargetByName<FileTarget>("jsonFile"); Assert.NotNull(target); var jsonLayout = target.Layout as JsonLayout; Assert.NotNull(jsonLayout); var attrs = jsonLayout.Attributes; Assert.NotNull(attrs); Assert.Equal(3, attrs.Count); Assert.Equal(typeof(SimpleLayout), attrs[0].Layout.GetType()); Assert.Equal(typeof(SimpleLayout), attrs[1].Layout.GetType()); Assert.Equal(typeof(JsonLayout), attrs[2].Layout.GetType()); var nestedJsonLayout = (JsonLayout)attrs[2].Layout; Assert.Equal(2, nestedJsonLayout.Attributes.Count); Assert.Equal("${message}", nestedJsonLayout.Attributes[0].Layout.ToString()); Assert.Equal("${exception:message}", nestedJsonLayout.Attributes[1].Layout.ToString()); var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2016, 10, 30, 13, 30, 55), Message = "this is message", Level = LogLevel.Info, Exception = new NLogRuntimeException("test", new NullReferenceException("null is bad!")) }; var json = jsonLayout.Render(logEventInfo); Assert.Equal("{ \"time\": \"2016-10-30 13:30:55.0000\", \"level\": \"INFO\", \"nested\": { \"message\": \"this is message\", \"exception\": \"test\" } }", json); } [Fact] public void IncludeAllJsonProperties() { var jsonLayout = new JsonLayout() { IncludeEventProperties = true }; jsonLayout.ExcludeProperties.Add("Excluded1"); jsonLayout.ExcludeProperties.Add("Excluded2"); var logEventInfo = CreateLogEventWithExcluded(); Assert.Equal(ExpectedIncludeAllPropertiesWithExcludes, jsonLayout.Render(logEventInfo)); } [Fact] public void PropertyKeyWithQuote() { var jsonLayout = new JsonLayout() { IncludeEventProperties = true, }; var logEventInfo = new LogEventInfo(); logEventInfo.Properties.Add(@"fo""o", "bar"); Assert.Equal(@"{ ""fo\""o"": ""bar"" }", jsonLayout.Render(logEventInfo)); } [Fact] public void AttributerKeyWithQuote() { var jsonLayout = new JsonLayout(); jsonLayout.Attributes.Add(new JsonAttribute(@"fo""o", "bar")); Assert.Equal(@"{ ""fo\""o"": ""bar"" }", jsonLayout.Render(LogEventInfo.CreateNullEvent())); } [Fact] public void ExcludeEmptyJsonProperties() { var jsonLayout = new JsonLayout() { IncludeEventProperties = true, ExcludeEmptyProperties = true }; jsonLayout.ExcludeProperties.Add("Excluded1"); jsonLayout.ExcludeProperties.Add("Excluded2"); var logEventInfo = CreateLogEventWithExcluded(); logEventInfo.Properties.Add("EmptyProp", ""); logEventInfo.Properties.Add("EmptyProp1", null); logEventInfo.Properties.Add("EmptyProp2", new DummyContextLogger() { Value = null }); logEventInfo.Properties.Add("EmptyProp3", new DummyContextLogger() { Value = "" }); logEventInfo.Properties.Add("NoEmptyProp4", new DummyContextLogger() { Value = "hello" }); Assert.Equal(ExpectedExcludeEmptyPropertiesWithExcludes, jsonLayout.Render(logEventInfo)); } [Fact] public void IncludeAllJsonPropertiesMaxRecursionLimit() { var jsonLayout = new JsonLayout() { IncludeEventProperties = true, MaxRecursionLimit = 1, }; LogEventInfo logEventInfo = new LogEventInfo() { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, }; logEventInfo.Properties["Message"] = new { data = new Dictionary<int, string>() { { 42, "Hello" } } }; Assert.Equal(@"{ ""Message"": {""data"":{}} }", jsonLayout.Render(logEventInfo)); } [Fact] [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public void IncludeMdcJsonProperties() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'> <target name='debug' type='Debug' > <layout type=""JsonLayout"" IncludeMdc='true' ExcludeProperties='Excluded1,Excluded2'> </layout> </target> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='asyncDebug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); var logEventInfo = CreateLogEventWithExcluded(); MappedDiagnosticsContext.Clear(); foreach (var prop in logEventInfo.Properties) if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2") MappedDiagnosticsContext.Set(prop.Key.ToString(), prop.Value); logEventInfo.Properties.Clear(); logger.Debug(logEventInfo); logFactory.Flush(); logFactory.AssertDebugLastMessage(ExpectedIncludeAllPropertiesWithExcludes); } [Fact] [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public void IncludeMdcNoEmptyJsonProperties() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'> <target name='debug' type='Debug' > <layout type=""JsonLayout"" IncludeMdc='true' ExcludeProperties='Excluded1,Excluded2' ExcludeEmptyProperties='true'> </layout> </target> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='asyncDebug' /> </rules> </nlog>").LogFactory; ILogger logger = logFactory.GetLogger("A"); var logEventInfo = CreateLogEventWithExcluded(); logEventInfo.Properties.Add("EmptyProp", ""); logEventInfo.Properties.Add("EmptyProp1", null); logEventInfo.Properties.Add("EmptyProp2", new DummyContextLogger() { Value = null }); logEventInfo.Properties.Add("EmptyProp3", new DummyContextLogger() { Value = "" }); logEventInfo.Properties.Add("NoEmptyProp4", new DummyContextLogger() { Value = "hello" }); MappedDiagnosticsContext.Clear(); foreach (var prop in logEventInfo.Properties) if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2") MappedDiagnosticsContext.Set(prop.Key.ToString(), prop.Value); logEventInfo.Properties.Clear(); logger.Debug(logEventInfo); logFactory.Flush(); logFactory.AssertDebugLastMessage(ExpectedExcludeEmptyPropertiesWithExcludes); } [Fact] public void IncludeGdcJsonProperties() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'> <target name='debug' type='Debug' > <layout type=""JsonLayout"" IncludeGdc='true' ExcludeProperties='Excluded1,Excluded2'> </layout> </target> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='asyncDebug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); var logEventInfo = CreateLogEventWithExcluded(); GlobalDiagnosticsContext.Clear(); foreach (var prop in logEventInfo.Properties) if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2") GlobalDiagnosticsContext.Set(prop.Key.ToString(), prop.Value); logEventInfo.Properties.Clear(); logger.Debug(logEventInfo); logFactory.Flush(); logFactory.AssertDebugLastMessage(ExpectedIncludeAllPropertiesWithExcludes); } [Fact] public void IncludeGdcNoEmptyJsonProperties() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'> <target name='debug' type='Debug' > <layout type=""JsonLayout"" IncludeGdc='true' ExcludeProperties='Excluded1,Excluded2' ExcludeEmptyProperties='true'> </layout> </target> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='asyncDebug' /> </rules> </nlog>").LogFactory; ILogger logger = logFactory.GetLogger("A"); var logEventInfo = CreateLogEventWithExcluded(); logEventInfo.Properties.Add("EmptyProp", ""); logEventInfo.Properties.Add("EmptyProp1", null); logEventInfo.Properties.Add("EmptyProp2", new DummyContextLogger() { Value = null }); logEventInfo.Properties.Add("EmptyProp3", new DummyContextLogger() { Value = "" }); logEventInfo.Properties.Add("NoEmptyProp4", new DummyContextLogger() { Value = "hello" }); GlobalDiagnosticsContext.Clear(); foreach (var prop in logEventInfo.Properties) if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2") GlobalDiagnosticsContext.Set(prop.Key.ToString(), prop.Value); logEventInfo.Properties.Clear(); logger.Debug(logEventInfo); logFactory.Flush(); logFactory.AssertDebugLastMessage(ExpectedExcludeEmptyPropertiesWithExcludes); } [Fact] [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public void IncludeMdlcJsonProperties() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'> <target name='debug' type='Debug' > <layout type=""JsonLayout"" IncludeMdlc='true' ExcludeProperties='Excluded1,Excluded2'> </layout> </target> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='asyncDebug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); var logEventInfo = CreateLogEventWithExcluded(); MappedDiagnosticsLogicalContext.Clear(); foreach (var prop in logEventInfo.Properties) if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2") MappedDiagnosticsLogicalContext.Set(prop.Key.ToString(), prop.Value); logEventInfo.Properties.Clear(); logger.Debug(logEventInfo); logFactory.Flush(); logFactory.AssertDebugLastMessage(ExpectedIncludeAllPropertiesWithExcludes); } [Fact] [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public void IncludeMdlcNoEmptyJsonProperties() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'> <target name='debug' type='Debug' > <layout type=""JsonLayout"" IncludeMdlc='true' ExcludeProperties='Excluded1,Excluded2' ExcludeEmptyProperties='true'> </layout> </target> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='asyncDebug' /> </rules> </nlog>").LogFactory; ILogger logger = logFactory.GetLogger("A"); var logEventInfo = CreateLogEventWithExcluded(); logEventInfo.Properties.Add("EmptyProp", ""); logEventInfo.Properties.Add("EmptyProp1", null); logEventInfo.Properties.Add("EmptyProp2", new DummyContextLogger() { Value = null }); logEventInfo.Properties.Add("EmptyProp3", new DummyContextLogger() { Value = "" }); logEventInfo.Properties.Add("NoEmptyProp4", new DummyContextLogger() { Value = "hello" }); MappedDiagnosticsLogicalContext.Clear(); foreach (var prop in logEventInfo.Properties) if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2") MappedDiagnosticsLogicalContext.Set(prop.Key.ToString(), prop.Value); logEventInfo.Properties.Clear(); logger.Debug(logEventInfo); logFactory.Flush(); logFactory.AssertDebugLastMessage(ExpectedExcludeEmptyPropertiesWithExcludes); } [Fact] [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public void IncludeMdlcJsonNestedProperties() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'> <target name='debug' type='Debug'> <layout type='JsonLayout'> <attribute name='scope' encode='false' > <layout type='JsonLayout' includeMdlc='true' /> </attribute> </layout> </target> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='asyncDebug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); var logEventInfo = CreateLogEventWithExcluded(); MappedDiagnosticsLogicalContext.Clear(); foreach (var prop in logEventInfo.Properties) if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2") MappedDiagnosticsLogicalContext.Set(prop.Key.ToString(), prop.Value); logEventInfo.Properties.Clear(); logger.Debug(logEventInfo); logFactory.Flush(); logFactory.AssertDebugLastMessage(@"{ ""scope"": " + ExpectedIncludeAllPropertiesWithExcludes + " }"); } /// <summary> /// Test from XML, needed for the list (ExcludeProperties) /// </summary> [Fact] public void IncludeAllJsonPropertiesXml() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' > <layout type=""JsonLayout"" IncludeAllProperties='true' ExcludeProperties='Excluded1,EXCLUDED2'> </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); var logEventInfo = CreateLogEventWithExcluded(); logger.Debug(logEventInfo); logFactory.AssertDebugLastMessage(ExpectedIncludeAllPropertiesWithExcludes); } [Fact] public void IncludeAllJsonPropertiesMutableXml() { // Arrange var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='asyncDebug' type='BufferingWrapper'> <target name='debug' type='Debug'> <layout type='JsonLayout' IncludeAllProperties='true' ExcludeProperties='Excluded1,Excluded2' maxRecursionLimit='0' /> </target> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='asyncDebug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); // Act var logEventInfo = CreateLogEventWithExcluded(); var stringPropBuilder = new System.Text.StringBuilder(logEventInfo.Properties["StringProp"].ToString()); logEventInfo.Properties["StringProp"] = stringPropBuilder; logger.Debug(logEventInfo); stringPropBuilder.Clear(); logFactory.Flush(); // Assert logFactory.AssertDebugLastMessage(ExpectedIncludeAllPropertiesWithExcludes); } [Fact] public void IncludeAllJsonPropertiesMutableNestedXml() { // Arrange var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='asyncDebug' type='BufferingWrapper'> <target name='debug' type='Debug'> <layout type='JsonLayout' maxRecursionLimit='0'> <attribute name='properties' encode='false' > <layout type='JsonLayout' IncludeAllProperties='true' ExcludeProperties='Excluded1,Excluded2' maxRecursionLimit='0'/> </attribute> </layout> </target> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='asyncDebug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); // Act var logEventInfo = CreateLogEventWithExcluded(); var stringPropBuilder = new System.Text.StringBuilder(logEventInfo.Properties["StringProp"].ToString()); logEventInfo.Properties["StringProp"] = stringPropBuilder; logger.Debug(logEventInfo); stringPropBuilder.Clear(); logFactory.Flush(); // Assert logFactory.AssertDebugLastMessage(@"{ ""properties"": " + ExpectedIncludeAllPropertiesWithExcludes + " }"); } /// <summary> /// Serialize object deep /// </summary> [Fact] public void SerializeObjectRecursionSingle() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' > <layout type=""JsonLayout"" IncludeAllProperties='true' maxRecursionLimit='1' > </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); var logEventInfo1 = new LogEventInfo(); logEventInfo1.Properties.Add("nestedObject", new List<object> { new { val = 1, val2 = "value2" }, new { val3 = 3, val4 = "value4" } }); logger.Debug(logEventInfo1); logFactory.AssertDebugLastMessage("{ \"nestedObject\": [{\"val\":1, \"val2\":\"value2\"},{\"val3\":3, \"val4\":\"value4\"}] }"); var logEventInfo2 = new LogEventInfo(); logEventInfo2.Properties.Add("nestedObject", new { val = 1, val2 = "value2" }); logger.Debug(logEventInfo2); logFactory.AssertDebugLastMessage("{ \"nestedObject\": {\"val\":1, \"val2\":\"value2\"} }"); var logEventInfo3 = new LogEventInfo(); logEventInfo3.Properties.Add("nestedObject", new List<object> { new List<object> { new { val = 1, val2 = "value2" } } }); logger.Debug(logEventInfo3); logFactory.AssertDebugLastMessage("{ \"nestedObject\": [[\"{ val = 1, val2 = value2 }\"]] }"); // Allows nested collection, but then only ToString } [Fact] public void SerializeObjectRecursionZero() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' > <layout type=""JsonLayout"" IncludeAllProperties='true' maxRecursionLimit='0' > </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); var logEventInfo1 = new LogEventInfo(); logEventInfo1.Properties.Add("nestedObject", new List<object> { new { val = 1, val2 = "value2" }, new { val3 = 3, val4 = "value5" } }); logger.Debug(logEventInfo1); logFactory.AssertDebugLastMessage("{ \"nestedObject\": [\"{ val = 1, val2 = value2 }\",\"{ val3 = 3, val4 = value5 }\"] }"); // Allows single collection recursion var logEventInfo2 = new LogEventInfo(); logEventInfo2.Properties.Add("nestedObject", new { val = 1, val2 = "value2" }); logger.Debug(logEventInfo2); logFactory.AssertDebugLastMessage("{ \"nestedObject\": \"{ val = 1, val2 = value2 }\" }"); // Never object recursion, only ToString var logEventInfo3 = new LogEventInfo(); logEventInfo3.Properties.Add("nestedObject", new List<object> { new List<object> { new { val = 1, val2 = "value2" } } }); logger.Debug(logEventInfo3); logFactory.AssertDebugLastMessage("{ \"nestedObject\": [[]] }"); // No support for nested collections } [Fact] public void EncodesInvalidCharacters() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' > <layout type=""JsonLayout"" IncludeAllProperties='true' escapeForwardSlash='true'> </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); var logEventInfo1 = new LogEventInfo(); logEventInfo1.Properties.Add("InvalidCharacters", "|#{}%&\"~+\\/:*?<>".ToCharArray()); logger.Debug(logEventInfo1); logFactory.AssertDebugLastMessage("{ \"InvalidCharacters\": [\"|\",\"#\",\"{\",\"}\",\"%\",\"&\",\"\\\"\",\"~\",\"+\",\"\\\\\",\"\\/\",\":\",\"*\",\"?\",\"<\",\">\"] }"); } [Fact] public void EncodesInvalidDoubles() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' > <layout type=""JsonLayout"" IncludeAllProperties='true' > </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); var logEventInfo1 = new LogEventInfo(); logEventInfo1.Properties.Add("DoubleNaN", double.NaN); logEventInfo1.Properties.Add("DoubleInfPositive", double.PositiveInfinity); logEventInfo1.Properties.Add("DoubleInfNegative", double.NegativeInfinity); logEventInfo1.Properties.Add("FloatNaN", float.NaN); logEventInfo1.Properties.Add("FloatInfPositive", float.PositiveInfinity); logEventInfo1.Properties.Add("FloatInfNegative", float.NegativeInfinity); logger.Debug(logEventInfo1); logFactory.AssertDebugLastMessage("{ \"DoubleNaN\": \"NaN\", \"DoubleInfPositive\": \"Infinity\", \"DoubleInfNegative\": \"-Infinity\", \"FloatNaN\": \"NaN\", \"FloatInfPositive\": \"Infinity\", \"FloatInfNegative\": \"-Infinity\" }"); } [Fact] public void EscapeForwardSlashDefaultTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' > <layout type='JsonLayout' escapeForwardSlash='false' includeAllProperties='true'> <attribute name='myurl1' layout='${event-properties:myurl}' /> <attribute name='myurl2' layout='${event-properties:myurl}' escapeForwardSlash='true' /> </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); var logEventInfo1 = new LogEventInfo(); logEventInfo1.Properties.Add("myurl", "http://hello.world.com/"); logger.Debug(logEventInfo1); logFactory.AssertDebugLastMessage("{ \"myurl1\": \"http://hello.world.com/\", \"myurl2\": \"http:\\/\\/hello.world.com\\/\", \"myurl\": \"http://hello.world.com/\" }"); } [Fact] public void SkipInvalidJsonPropertyValues() { var jsonLayout = new JsonLayout() { IncludeEventProperties = true, MaxRecursionLimit = 10 }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = string.Empty, }; var expectedValue = Guid.NewGuid(); logEventInfo.Properties["BadObject"] = new BadObject(); logEventInfo.Properties["EvilObject"] = new EvilObject(); logEventInfo.Properties["RequestId"] = expectedValue; var actualValue = jsonLayout.Render(logEventInfo); Assert.Equal($"{{ \"BadObject\": {{\"Recursive\":[\"Hello\"], \"WeirdProperty\":\"System.Action\"}}, \"RequestId\": \"{expectedValue}\" }}", actualValue); } class BadObject { public IEnumerable<object> Recursive => new List<object>(new [] { "Hello", (object)this }); public IEnumerable<string> EvilProperty => throw new NotSupportedException(); public System.Action WeirdProperty { get; } = new System.Action(() => throw new NotSupportedException()); } class EvilObject : IFormattable { public string ToString(string format, IFormatProvider formatProvider) { throw new ApplicationException("BadObject"); } public override string ToString() { return ToString(null, null); } } private static LogEventInfo CreateLogEventWithExcluded() { var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" }; logEventInfo.Properties.Add("StringProp", "ValueA"); logEventInfo.Properties.Add("IntProp", 123); logEventInfo.Properties.Add("DoubleProp", 123.123); logEventInfo.Properties.Add("DecimalProp", 123.123m); logEventInfo.Properties.Add("BoolProp", true); logEventInfo.Properties.Add("NullProp", null); logEventInfo.Properties.Add("DateTimeProp", new DateTime(2345, 1, 23, 12, 34, 56, DateTimeKind.Utc)); logEventInfo.Properties.Add("Excluded1", "ExcludedValue"); logEventInfo.Properties.Add("Excluded2", "Also excluded"); return logEventInfo; } public class DummyContextLogger { internal string Value { get; set; } public override string ToString() { return Value; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Text.RegularExpressions; namespace NLog.Internal { internal class RegexHelper { private Regex _regex; private string _searchText; private string _regexPattern; private bool _wholeWords; private bool _ignoreCase; private bool _simpleSearchText; public string SearchText { get => _searchText; set { _searchText = value; _regexPattern = null; ResetRegex(); } } public string RegexPattern { get => _regexPattern; set { _regexPattern = value; _searchText = null; ResetRegex(); } } /// <summary> /// Compile the <see cref="Regex"/>? This can improve the performance, but at the costs of more memory usage. If <c>false</c>, the Regex Cache is used. /// </summary> public bool CompileRegex { get; set; } /// <summary> /// Gets or sets a value indicating whether to match whole words only. /// </summary> public bool WholeWords { get => _wholeWords; set { if (_wholeWords != value) { _wholeWords = value; ResetRegex(); } } } /// <summary> /// Gets or sets a value indicating whether to ignore case when comparing texts. /// </summary> public bool IgnoreCase { get => _ignoreCase; set { if (_ignoreCase != value) { _ignoreCase = value; ResetRegex(); } } } public Regex Regex { get { if (_regex != null) return _regex; var regexpression = RegexPattern; if (string.IsNullOrEmpty(regexpression)) return null; return _regex = new Regex(regexpression, GetRegexOptions()); } } private void ResetRegex() { _simpleSearchText = !WholeWords && !IgnoreCase && !string.IsNullOrEmpty(SearchText); if (!string.IsNullOrEmpty(SearchText)) { _regexPattern = Regex.Escape(SearchText); } if (WholeWords && !string.IsNullOrEmpty(_regexPattern)) { _regexPattern = string.Concat("\\b", _regexPattern, "\\b"); } _regex = null; } private RegexOptions GetRegexOptions() { RegexOptions regexOptions = RegexOptions.None; if (IgnoreCase) { regexOptions |= RegexOptions.IgnoreCase; } if (CompileRegex) { regexOptions |= RegexOptions.Compiled; } return regexOptions; } public string Replace(string input, string replacement) { if (_simpleSearchText) { return input.Replace(SearchText, replacement); } else if (CompileRegex) { return Regex?.Replace(input, replacement) ?? input; } else { return _regexPattern != null ? Regex.Replace(input, _regexPattern, replacement, GetRegexOptions()) : input; } } public MatchCollection Matches(string input) { if (CompileRegex) { return Regex?.Matches(input); } else { return _regexPattern != null ? Regex.Matches(input, _regexPattern, GetRegexOptions()) : null; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; /// <summary> /// Interface for loading NLog <see cref="LoggingConfiguration"/> /// </summary> internal interface ILoggingConfigurationLoader : IDisposable { /// <summary> /// Finds and loads the NLog configuration /// </summary> /// <param name="logFactory">LogFactory that owns the NLog configuration</param> /// <param name="filename">Name of NLog.config file (optional)</param> /// <returns>NLog configuration (or null if none found)</returns> LoggingConfiguration Load(LogFactory logFactory, string filename = null); /// <summary> /// Notifies when LoggingConfiguration has been successfully applied /// </summary> /// <param name="logFactory">LogFactory that owns the NLog configuration</param> /// <param name="config">NLog Config</param> void Activated(LogFactory logFactory, LoggingConfiguration config); /// <summary> /// Get file paths (including filename) for the possible NLog config files. /// </summary> /// <param name="filename">Name of NLog.config file (optional)</param> /// <returns>The file paths to the possible config file</returns> IEnumerable<string> GetDefaultCandidateConfigFilePaths(string filename = null); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Conditions { using System; using NLog.Internal; using NLog.Conditions; using NLog.Config; using NLog.LayoutRenderers; using NLog.Layouts; using Xunit; public class ConditionParserTests : NLogTestBase { [Fact] public void ParseNullText() { Assert.Null(ConditionParser.ParseExpression(null)); } [Fact] public void ParseEmptyText() { Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("")); } [Fact] public void ImplicitOperatorTest() { ConditionExpression cond = "true and true"; Assert.IsType<ConditionAndExpression>(cond); } [Fact] public void NullLiteralTest() { Assert.Equal("null", ConditionParser.ParseExpression("null").ToString()); } [Fact] public void BooleanLiteralTest() { Assert.Equal("True", ConditionParser.ParseExpression("true").ToString()); Assert.Equal("True", ConditionParser.ParseExpression("tRuE").ToString()); Assert.Equal("False", ConditionParser.ParseExpression("false").ToString()); Assert.Equal("False", ConditionParser.ParseExpression("fAlSe").ToString()); } [Fact] public void AndTest() { Assert.Equal("(True and True)", ConditionParser.ParseExpression("true and true").ToString()); Assert.Equal("(True and True)", ConditionParser.ParseExpression("tRuE AND true").ToString()); Assert.Equal("(True and True)", ConditionParser.ParseExpression("tRuE && true").ToString()); Assert.Equal("((True and True) and True)", ConditionParser.ParseExpression("true and true && true").ToString()); Assert.Equal("((True and True) and True)", ConditionParser.ParseExpression("tRuE AND true and true").ToString()); Assert.Equal("((True and True) and True)", ConditionParser.ParseExpression("tRuE && true AND true").ToString()); } [Fact] public void OrTest() { Assert.Equal("(True or True)", ConditionParser.ParseExpression("true or true").ToString()); Assert.Equal("(True or True)", ConditionParser.ParseExpression("tRuE OR true").ToString()); Assert.Equal("(True or True)", ConditionParser.ParseExpression("tRuE || true").ToString()); Assert.Equal("((True or True) or True)", ConditionParser.ParseExpression("true or true || true").ToString()); Assert.Equal("((True or True) or True)", ConditionParser.ParseExpression("tRuE OR true or true").ToString()); Assert.Equal("((True or True) or True)", ConditionParser.ParseExpression("tRuE || true OR true").ToString()); } [Fact] public void NotTest() { Assert.Equal("(not True)", ConditionParser.ParseExpression("not true").ToString()); Assert.Equal("(not (not True))", ConditionParser.ParseExpression("not not true").ToString()); Assert.Equal("(not (not (not True)))", ConditionParser.ParseExpression("not not not true").ToString()); } [Fact] public void StringTest() { Assert.Equal("''", ConditionParser.ParseExpression("''").ToString()); Assert.Equal("'Foo'", ConditionParser.ParseExpression("'Foo'").ToString()); Assert.Equal("'Bar'", ConditionParser.ParseExpression("'Bar'").ToString()); Assert.Equal("'d'Artagnan'", ConditionParser.ParseExpression("'d''Artagnan'").ToString()); var cle = ConditionParser.ParseExpression("'${message} ${level}'") as ConditionLayoutExpression; Assert.NotNull(cle); SimpleLayout sl = cle.Layout as SimpleLayout; Assert.NotNull(sl); Assert.Equal(3, sl.Renderers.Count); Assert.IsType<MessageLayoutRenderer>(sl.Renderers[0]); Assert.IsType<LiteralLayoutRenderer>(sl.Renderers[1]); Assert.IsType<LevelLayoutRenderer>(sl.Renderers[2]); } [Fact] public void LogLevelTest() { var result = ConditionParser.ParseExpression("LogLevel.Info") as ConditionLiteralExpression; Assert.NotNull(result); Assert.Same(LogLevel.Info, result.LiteralValue); result = ConditionParser.ParseExpression("LogLevel.Trace") as ConditionLiteralExpression; Assert.NotNull(result); Assert.Same(LogLevel.Trace, result.LiteralValue); } [Fact] public void RelationalOperatorTest() { RelationalOperatorTestInner("=", "=="); RelationalOperatorTestInner("==", "=="); RelationalOperatorTestInner("!=", "!="); RelationalOperatorTestInner("<>", "!="); RelationalOperatorTestInner("<", "<"); RelationalOperatorTestInner(">", ">"); RelationalOperatorTestInner("<=", "<="); RelationalOperatorTestInner(">=", ">="); } [Fact] public void NumberTest() { var conditionExpression = ConditionParser.ParseExpression("3.141592"); Assert.Equal("3.141592", conditionExpression.ToString()); Assert.Equal("42", ConditionParser.ParseExpression("42").ToString()); Assert.Equal("-42", ConditionParser.ParseExpression("-42").ToString()); Assert.Equal("-3.141592", ConditionParser.ParseExpression("-3.141592").ToString()); } [Fact] public void ExtraParenthesisTest() { Assert.Equal("3.141592", ConditionParser.ParseExpression("(((3.141592)))").ToString()); } [Fact] public void MessageTest() { var result = ConditionParser.ParseExpression("message"); Assert.IsType<ConditionMessageExpression>(result); Assert.Equal("message", result.ToString()); } [Fact] public void LevelTest() { var result = ConditionParser.ParseExpression("level"); Assert.IsType<ConditionLevelExpression>(result); Assert.Equal("level", result.ToString()); } [Fact] public void LoggerTest() { var result = ConditionParser.ParseExpression("logger"); Assert.IsType<ConditionLoggerNameExpression>(result); Assert.Equal("logger", result.ToString()); } [Fact] public void ConditionFunctionTests() { var result = ConditionParser.ParseExpression("starts-with(logger, 'x${message}')") as ConditionMethodExpression; Assert.NotNull(result); Assert.Equal("starts-with", result.MethodName); Assert.Equal("starts-with(logger, 'x${message}')", result.ToString()); Assert.Equal(2, result.MethodParameters.Count); } [Fact] public void CustomNLogFactoriesTest() { var configurationItemFactory = new ConfigurationItemFactory(); configurationItemFactory.LayoutRendererFactory.RegisterType<FooLayoutRenderer>("foo"); configurationItemFactory.ConditionMethodFactory.RegisterDefinition("check", typeof(MyConditionMethods).GetMethod("CheckIt")); var result = ConditionParser.ParseExpression("check('${foo}')", configurationItemFactory); Assert.NotNull(result); } [Fact] public void MethodNameWithUnderscores() { var configurationItemFactory = new ConfigurationItemFactory(); configurationItemFactory.LayoutRendererFactory.RegisterType<FooLayoutRenderer>("foo"); configurationItemFactory.ConditionMethodFactory.RegisterDefinition("__check__", typeof(MyConditionMethods).GetMethod("CheckIt")); var result = ConditionParser.ParseExpression("__check__('${foo}')", configurationItemFactory); Assert.NotNull(result); } [Fact] public void UnbalancedParenthesis1Test() { Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("check(")); } [Fact] public void UnbalancedParenthesis2Test() { Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("((1)")); } [Fact] public void UnbalancedParenthesis3Test() { Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("(1))")); } [Fact] public void LogLevelWithoutAName() { Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("LogLevel.'somestring'")); } [Fact] public void InvalidNumberWithUnaryMinusTest() { Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("-a31")); } [Fact] public void InvalidNumberTest() { Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("-123.4a")); } [Fact] public void UnclosedString() { Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("'Hello world")); } [Fact] public void UnrecognizedToken() { Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("somecompletelyunrecognizedtoken")); } [Fact] public void UnrecognizedPunctuation() { Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("#")); } [Fact] public void UnrecognizedUnicodeChar() { Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("\u0090")); } [Fact] public void UnrecognizedUnicodeChar2() { Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("\u0015")); } [Fact] public void UnrecognizedMethod() { Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("unrecognized-method()")); } [Fact] public void TokenizerEOFTest() { var tokenizer = new ConditionTokenizer(new SimpleStringReader(string.Empty)); Assert.Throws<ConditionParseException>(() => tokenizer.GetNextToken()); } private static void RelationalOperatorTestInner(string op, string result) { string operand1 = "3"; string operand2 = "7"; string input = operand1 + " " + op + " " + operand2; string expectedOutput = "(" + operand1 + " " + result + " " + operand2 + ")"; var condition = ConditionParser.ParseExpression(input); Assert.Equal(expectedOutput, condition.ToString()); } public class FooLayoutRenderer : LayoutRenderer { protected override void Append(System.Text.StringBuilder builder, LogEventInfo logEvent) { throw new System.NotImplementedException(); } } public class MyConditionMethods { public static bool CheckIt(string s) { return s == "X"; } } } }<file_sep>namespace MergeApiXml { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; public class NLogApiMerger { private List<KeyValuePair<string, string>> releases = new List<KeyValuePair<string, string>>(); public XDocument Result { get; set; } public void AddRelease(string name, string baseDir) { if (Directory.Exists(baseDir)) { releases.Add(new KeyValuePair<string, string>(name, baseDir)); } } public void Merge() { var resultDoc = new XDocument( new XProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"style.xsl\""), new XElement("types")); foreach (var kvp in releases) { string releaseName = kvp.Key; string basePath = kvp.Value; foreach (string frameworkDir in Directory.GetDirectories(basePath)) { string apiFile = Path.Combine(frameworkDir, "API/NLog.api"); if (File.Exists(apiFile)) { string frameworkName = Path.GetFileName(frameworkDir); Console.WriteLine("Loading {0}", apiFile); XElement apiDoc = XElement.Load(apiFile); FixWhitespace(apiDoc); MergeApiFile(resultDoc.Root, apiDoc, releaseName, frameworkName); } } } foreach (var typeElement in resultDoc.Root.Elements("type")) { this.SortProperties(typeElement); } this.PostProcessSupportedIn(resultDoc.Root); this.Result = resultDoc; } private void FixWhitespace(XElement xmlElement) { foreach (var node in xmlElement.DescendantNodes()) { XElement el = node as XElement; if (el != null) { FixWhitespace(el); continue; } XText txt = node as XText; if (txt != null) { txt.Value = FixWhitespace(txt.Value); } } } private string FixWhitespace(string p) { p = p.Replace("\n", " "); p = p.Replace("\r", " "); string oldP = ""; while (oldP != p) { oldP = p; p = p.Replace(" ", " "); } return p; } private void PostProcessSupportedIn(XElement rootElement) { } private void SortProperties(XElement typeElement) { var propertyElements = typeElement.Elements("property").ToList(); foreach (var prop in propertyElements) { prop.Remove(); } propertyElements.Sort((p1, p2) => { string cat1 = (string)p1.Attribute("category") ?? "Other"; string cat2 = (string)p2.Attribute("category") ?? "Other"; int v1 = GetCategoryValue(cat1); int v2 = GetCategoryValue(cat2); if (v1 != v2) { return v1 - v2; } return string.Compare(cat1, cat2, StringComparison.OrdinalIgnoreCase); }); typeElement.Add(propertyElements); } private int GetCategoryValue(string categoryName) { switch (categoryName) { case "General Options": return 0; case "Layout Options": return 10; default: return 100; } } private void MergeApiFile(XElement resultDoc, XElement apiDoc, string releaseName, string frameworkName) { AddSupportedIn(resultDoc, releaseName, frameworkName); MergeTypes(resultDoc, releaseName, frameworkName, apiDoc); } private void MergeTypes(XElement resultDoc, string releaseName, string frameworkName, XElement apiDoc) { foreach (var type in apiDoc.Elements("type")) { string kind = (string)type.Attribute("kind"); string name = (string)type.Attribute("name"); var mergedElement = resultDoc.Elements("type").Where(c => (string)c.Attribute("kind") == kind && string.Equals(name, (string)c.Attribute("name"), StringComparison.OrdinalIgnoreCase)).SingleOrDefault(); if (mergedElement == null) { Console.WriteLine("kind: {0} name: {1}", kind, name); mergedElement = new XElement("type"); mergedElement.Add(new XAttribute("kind", kind)); mergedElement.Add(new XAttribute("name", name)); resultDoc.Add(mergedElement); } this.AddSupportedIn(mergedElement, releaseName, frameworkName); this.MergeDoc(mergedElement, type); this.MergeAttributes(mergedElement, type); this.MergeProperties(mergedElement, releaseName, frameworkName, type); } } private void MergeAttributes(XElement mergedElement, XElement sourceElement) { foreach (var attrib in sourceElement.Attributes()) { mergedElement.SetAttributeValue(attrib.Name, attrib.Value); } } private void MergeDoc(XElement mergedElement, XElement sourceElement) { var oldDoc = mergedElement.Element("doc"); var sourceDoc = sourceElement.Element("doc"); if (oldDoc != null) { oldDoc.ReplaceWith(sourceDoc); } else { mergedElement.Add(sourceDoc); } } private void MergeProperties(XElement mergedType, string releaseName, string frameworkName, XElement inputType) { foreach (var property in inputType.Elements("property")) { string name = (string)property.Attribute("name"); var mergedProperty = mergedType.Elements("property").Where(c => string.Equals((string)c.Attribute("name"), name, StringComparison.OrdinalIgnoreCase)).SingleOrDefault(); if (mergedProperty == null) { mergedProperty = new XElement("property", new XAttribute("name", name)); mergedType.Add(mergedProperty); } mergedProperty.SetAttributeValue("name", (string)property.Attribute("name")); this.AddSupportedIn(mergedProperty, releaseName, frameworkName); this.MergeDoc(mergedProperty, property); this.MergeAttributes(mergedProperty, property); this.MergeEnumValues(mergedProperty, releaseName, frameworkName, property); var elementType = property.Element("elementType"); if (elementType != null) { var mergedElementType = mergedProperty.Element("elementType"); if (mergedElementType == null) { mergedElementType = new XElement("elementType"); mergedProperty.Add(mergedElementType); } this.AddSupportedIn(mergedElementType, releaseName, frameworkName); this.MergeAttributes(mergedElementType, elementType); this.MergeProperties(mergedElementType, releaseName, frameworkName, elementType); } } } private void MergeEnumValues(XElement mergedProperty, string releaseName, string frameworkName, XElement property) { foreach (var enumElement in property.Elements("enum")) { string enumName = (string)enumElement.Attribute("name"); var mergedEnum = mergedProperty.Elements("enum").Where(c => (string)c.Attribute("name") == enumName).SingleOrDefault(); if (mergedEnum == null) { mergedEnum = new XElement("enum"); mergedProperty.Add(mergedEnum); } this.AddSupportedIn(mergedEnum, releaseName, frameworkName); this.MergeDoc(mergedEnum, enumElement); this.MergeAttributes(mergedEnum, enumElement); } } private void AddSupportedIn(XElement element, string releaseName, string frameworkName) { var supportedIn = element.Element("supported-in"); if (supportedIn == null) { supportedIn = new XElement("supported-in"); element.Add(supportedIn); } supportedIn.Add(new XElement("release", new XAttribute("name", releaseName), new XAttribute("framework", frameworkName))); } } } <file_sep>// // Copyright (c) 2004-2016 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace MakeNLogXSD { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; public class XsdFileGenerator { private static XNamespace xsd = "http://www.w3.org/2001/XMLSchema"; private HashSet<string> typesEmitted; private XElement template; private XElement typesGoHere; private XElement filtersGoHere; public XsdFileGenerator() { this.template = LoadTemplateXSD(); this.filtersGoHere = template.Descendants("filters-go-here").Single(); this.typesGoHere = template.Descendants("types-go-here").Single(); this.typesEmitted = new HashSet<string>(); } public string TargetNamespace { get; set; } public void ProcessApiFile(string apiFile) { Console.WriteLine("Processing API file '{0}'", Path.GetFullPath(apiFile)); XElement api = XElement.Load(apiFile); foreach (var type in api.Elements("type")) { string typeName = (string)type.Attribute("name"); string baseType = null; switch ((string)type.Attribute("kind")) { case "target": baseType = "Target"; if ((string)type.Attribute("iswrapper") == "1") { baseType = "WrapperTargetBase"; } if ((string)type.Attribute("iscompound") == "1") { baseType = "CompoundTargetBase"; } break; case "filter": baseType = "Filter"; break; case "layout": baseType = "Layout"; break; case "time-source": baseType = "TimeSource"; break; } if (baseType == null) { continue; } var typeElement = new XElement(xsd + "complexType", new XAttribute("name", (string)type.Attribute("name")), new XElement(xsd + "complexContent", new XElement(xsd + "extension", new XAttribute("base", baseType), new XElement(xsd + "choice", new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"), GetPropertyElements(type)), GetAttributeElements(type)))); typesGoHere.AddBeforeSelf(typeElement); foreach (var enumProperty in type.Descendants("property").Where(c => (string)c.Attribute("type") == "Enum")) { string enumType = (string)enumProperty.Attribute("enumType"); if (!typesEmitted.Contains(enumType)) { typesEmitted.Add(enumType); typesGoHere.AddBeforeSelf(GenerateEnumType(enumProperty)); } } foreach (var elementType in type.Descendants("elementType")) { string collectionElementType = (string)elementType.Attribute("name"); if (!typesEmitted.Contains(collectionElementType)) { typesEmitted.Add(collectionElementType); typesGoHere.AddBeforeSelf(new XElement(xsd + "complexType", new XAttribute("name", collectionElementType), new XElement(xsd + "choice", new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"), GetPropertyElements(elementType)), GetAttributeElements(elementType))); } } if (baseType == "Filter") { filtersGoHere.AddBeforeSelf(new XElement(xsd + "element", new XAttribute("name", typeName), new XAttribute("type", typeName))); } } } public void SaveResult(string outputFile) { template.Attribute("targetNamespace").Value = this.TargetNamespace; template.Attribute("xmlns").Value = this.TargetNamespace; filtersGoHere.Remove(); typesGoHere.Remove(); Console.WriteLine("Saving '{0}'", Path.GetFullPath(outputFile)); template.Save(outputFile); } private XElement LoadTemplateXSD() { XElement xElement; using (var stream = this.GetType().Assembly.GetManifestResourceStream(this.GetType(), "TemplateXSD.xml")) { using (XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings { IgnoreWhitespace = true })) { xElement = XElement.Load(reader); } } return xElement; } private static IEnumerable<XElement> GetAttributeElements(XElement type) { return type.Elements("property").Select(GetAttributeElement).Where(elem => elem != null).ToList(); } /// <summary> /// Ignore if returns null /// </summary> /// <param name="propertyElement"></param> /// <returns></returns> private static XElement GetAttributeElement(XElement propertyElement) { var result = new XElement(xsd + "attribute", new XAttribute("name", (string)propertyElement.Attribute("camelName"))); var propertyType = (string)propertyElement.Attribute("type"); if (propertyType == "Collection") { return null; } if (propertyType == "Enum") { string enumType = (string)propertyElement.Attribute("enumType"); result.Add(new XAttribute("type", enumType)); } else { string xsdType = GetXsdType(propertyType, true); if (xsdType == null) return null; result.Add(new XAttribute("type", xsdType)); } var doc = propertyElement.Element("doc"); if (doc != null) { var summary = doc.Element("summary"); if (summary != null) { var summaryDoc = summary.Value; if (summary.HasElements) { // Try to expand <see cref="..." /> summaryDoc = string.Empty; foreach (var item in summary.Nodes()) { var element = item as XElement; if (element?.HasAttributes == true) { if (element?.IsEmpty == true) { summaryDoc += element.FirstAttribute.Value; } else { // Something else, abort the attempt to expand summaryDoc = summary.Value; break; } } else if (element != null) { summaryDoc += element.Value.ToString(); } else { summaryDoc += item.ToString(); } } } result.Add(new XElement(xsd + "annotation", new XElement(xsd + "documentation", summaryDoc))); } } return result; } private static XElement GenerateEnumType(XElement enumProperty) { var enumerationValues = enumProperty.Elements("enum") .Select(c => new XElement(xsd + "enumeration", new XAttribute("value", (string)c.Attribute("name")))); return new XElement(xsd + "simpleType", new XAttribute("name", (string)enumProperty.Attribute("enumType")), new XElement(xsd + "restriction", new XAttribute("base", "xs:string"), enumerationValues)); } private static IEnumerable<XElement> GetPropertyElements(XElement type) { var results = new List<XElement>(); foreach (var propertyElement in type.Elements("property")) { var xElement = GetPropertyElement(propertyElement); if (xElement != null) { results.Add(xElement); } } return results; } /// <summary> /// Ignore if returns null. /// </summary> /// <param name="propertyElement"></param> /// <returns></returns> private static XElement GetPropertyElement(XElement propertyElement) { var result = new XElement(xsd + "element", new XAttribute("name", (string)propertyElement.Attribute("camelName"))); string propertyType = (string)propertyElement.Attribute("type"); if (propertyType == "Collection") { result.Add(new XAttribute("minOccurs", "0")); result.Add(new XAttribute("maxOccurs", "unbounded")); var elementType = propertyElement.Element("elementType"); result.Attribute("name").Value = (string)elementType.Attribute("elementTag"); result.Add(new XAttribute("type", (string)elementType.Attribute("name"))); } else if (propertyType == "Enum") { string enumType = (string)propertyElement.Attribute("enumType"); result.Add(new XAttribute("type", enumType)); result.Add(new XAttribute("minOccurs", "0")); result.Add(new XAttribute("maxOccurs", "1")); string defaultValue = (string)propertyElement.Attribute("defaultValue"); if (!string.IsNullOrEmpty(defaultValue)) result.Add(new XAttribute("default", defaultValue)); } else { string xsdType = GetXsdType(propertyType, false); if (xsdType == null) return null; result.Add(new XAttribute("type", xsdType)); string defaultValue = (string)propertyElement.Attribute("defaultValue"); string requiredValue = (string)propertyElement.Attribute("required"); if (requiredValue == "1" && defaultValue == null && (xsdType.StartsWith("xs:") || xsdType == "Layout")) result.Add(new XAttribute("minOccurs", "1")); else result.Add(new XAttribute("minOccurs", "0")); result.Add(new XAttribute("maxOccurs", "1")); if (!string.IsNullOrEmpty(defaultValue) && xsdType.StartsWith("xs:")) result.Add(new XAttribute("default", defaultValue)); } return result; } private static HashSet<string> IgnoreTypes = new HashSet<string> { "NLog.Targets.IFileCompressor" }; private static string GetXsdType(string apiTypeName, bool attribute) { if (string.IsNullOrWhiteSpace(apiTypeName)) { throw new NotSupportedException("Unknown API empty type '" + apiTypeName + "'."); } if (IgnoreTypes.Contains(apiTypeName)) { return null; } switch (apiTypeName) { case "Layout": return GetLayoutType(attribute); case "NLog.Filters.Filter": return attribute ? null : "Filter"; case "Condition": return "Condition"; case "LineEndingMode": return "LineEndingMode"; case "String": return "xs:string"; case "Integer": return "xs:integer"; case "Long": return "xs:long"; case "Byte": return "xs:byte"; case "Boolean": return "xs:boolean"; case "Encoding": return "xs:string"; case "Culture": return "xs:string"; case "Char": return "xs:string"; case "System.Type": return "xs:string"; case "System.Uri": return "xs:anyURI"; case "System.TimeSpan": return "xs:string"; default: if ( apiTypeName.StartsWith("System.Collections.Generic.ISet") || apiTypeName.StartsWith("System.Collections.Generic.HashSet") || apiTypeName.StartsWith("System.Collections.Generic.IList") || apiTypeName.StartsWith("System.Collections.Generic.List") || apiTypeName.StartsWith("System.Collections.Generic.IEnumerable") ) { //comma separated string return "xs:string"; } if (apiTypeName.StartsWith("NLog.Layouts.Layout`1")) { // Layout<T> return GetLayoutType(attribute); } throw new NotSupportedException("Unknown API type '" + apiTypeName + "'."); } } private static string GetLayoutType(bool attribute) { return attribute ? "SimpleLayoutAttribute" : "Layout"; } } } <file_sep>using NLog; using NLog.Targets; class Example { static void Main(string[] args) { ConsoleTarget target = new ConsoleTarget(); target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using Microsoft.CSharp; using NLog.Config; using NLog.UnitTests.Mocks; using Xunit; public sealed class ConfigFileLocatorTests : NLogTestBase, IDisposable { private readonly string _tempDirectory; public ConfigFileLocatorTests() { _tempDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); Directory.CreateDirectory(_tempDirectory); } void IDisposable.Dispose() { if (Directory.Exists(_tempDirectory)) Directory.Delete(_tempDirectory, true); } [Fact] [Obsolete("Replaced by LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] public void GetCandidateConfigTest() { var candidateConfigFilePaths = XmlLoggingConfiguration.GetCandidateConfigFilePaths(); Assert.NotNull(candidateConfigFilePaths); var count = candidateConfigFilePaths.Count(); Assert.NotEqual(0, count); } [Fact] [Obsolete("Replaced by LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] public void GetCandidateConfigTest_list_is_readonly() { Assert.Throws<NotSupportedException>(() => { var list = new List<string> { "c:\\global\\temp.config" }; XmlLoggingConfiguration.SetCandidateConfigFilePaths(list); var candidateConfigFilePaths = XmlLoggingConfiguration.GetCandidateConfigFilePaths(); var list2 = candidateConfigFilePaths as IList; list2.Add("test"); }); } [Fact] [Obsolete("Replaced by LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] public void SetCandidateConfigTest() { var list = new List<string> { "c:\\global\\temp.config" }; XmlLoggingConfiguration.SetCandidateConfigFilePaths(list); Assert.Single(XmlLoggingConfiguration.GetCandidateConfigFilePaths()); //no side effects list.Add("c:\\global\\temp2.config"); Assert.Single(XmlLoggingConfiguration.GetCandidateConfigFilePaths()); } [Fact] [Obsolete("Replaced by LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] public void ResetCandidateConfigTest() { var countBefore = XmlLoggingConfiguration.GetCandidateConfigFilePaths().Count(); var list = new List<string> { "c:\\global\\temp.config" }; XmlLoggingConfiguration.SetCandidateConfigFilePaths(list); Assert.Single(XmlLoggingConfiguration.GetCandidateConfigFilePaths()); XmlLoggingConfiguration.ResetCandidateConfigFilePath(); Assert.Equal(countBefore, XmlLoggingConfiguration.GetCandidateConfigFilePaths().Count()); } [Theory] [MemberData(nameof(GetConfigFile_absolutePath_loads_testData))] public void GetConfigFile_absolutePath_loads(string filename, string accepts, string expected, string baseDir) { // Arrange var appEnvMock = new AppEnvironmentMock(f => f == accepts, f => System.Xml.XmlReader.Create(new StringReader(@"<nlog autoreload=""true""></nlog>"))) { AppDomainBaseDirectory = baseDir }; var fileLoader = new LoggingConfigurationFileLoader(appEnvMock); var logFactory = new LogFactory(fileLoader); // Act var result = fileLoader.Load(logFactory, filename); // Assert Assert.Equal(expected, result?.FileNamesToWatch.First()); } public static IEnumerable<object[]> GetConfigFile_absolutePath_loads_testData() { var d = Path.DirectorySeparatorChar; var baseDir = Path.GetTempPath(); var dirInBaseDir = $"{baseDir}dir1"; if (!IsLinux()) { var rootBaseDir = Path.GetPathRoot(baseDir); yield return new object[] { "nlog.config", $"{rootBaseDir}nlog.config", $"{rootBaseDir}nlog.config", rootBaseDir }; } yield return new object[] { $"{baseDir}configfile", $"{baseDir}configfile", $"{baseDir}configfile", dirInBaseDir }; yield return new object[] { "nlog.config", $"{baseDir}dir1{d}nlog.config", $"{baseDir}dir1{d}nlog.config", dirInBaseDir }; //exists yield return new object[] { "nlog.config", $"{baseDir}dir1{d}nlog2.config", null, dirInBaseDir }; //not existing, fallback } [Fact] public void LoadConfigFile_EmptyEnvironment_UseCurrentDirectory() { // Arrange var appEnvMock = new AppEnvironmentMock(f => true, f => null); var fileLoader = new LoggingConfigurationFileLoader(appEnvMock); // Act var result = fileLoader.GetDefaultCandidateConfigFilePaths().ToList(); // Assert loading from current-directory and from nlog-assembly-directory if (NLog.Internal.PlatformDetector.IsWin32) Assert.Equal(2, result.Count); // Case insensitive Assert.Equal("NLog.config", result.First(), StringComparer.OrdinalIgnoreCase); Assert.Contains("NLog.dll.nlog", result.Last(), StringComparison.OrdinalIgnoreCase); } [Fact] public void LoadConfigFile_NetCoreUnpublished_UseEntryDirectory() { // Arrange var tmpDir = Path.GetTempPath(); var appEnvMock = new AppEnvironmentMock(f => true, f => null) { AppDomainBaseDirectory = Path.Combine(tmpDir, "BaseDir"), #if NETSTANDARD AppDomainConfigurationFile = string.Empty, // NetCore style #else AppDomainConfigurationFile = Path.Combine(tmpDir, "EntryDir", "Entry.exe.config"), #endif CurrentProcessFilePath = Path.Combine(tmpDir, "ProcessDir", "dotnet.exe"), // NetCore dotnet.exe EntryAssemblyLocation = Path.Combine(tmpDir, "EntryDir"), EntryAssemblyFileName = "Entry.dll" }; var fileLoader = new LoggingConfigurationFileLoader(appEnvMock); // Act var result = fileLoader.GetDefaultCandidateConfigFilePaths().ToList(); // Assert base-directory + entry-directory + nlog-assembly-directory AssertResult(tmpDir, "EntryDir", "EntryDir", "Entry", result); } [Fact] public void LoadConfigFile_NetCorePublished_UseBaseDirectory() { // Arrange var tmpDir = Path.GetTempPath(); var appEnvMock = new AppEnvironmentMock(f => true, f => null) { AppDomainBaseDirectory = Path.Combine(tmpDir, "BaseDir"), #if NETSTANDARD AppDomainConfigurationFile = string.Empty, // .NET 6 single-publish-style #else AppDomainConfigurationFile = Path.Combine(tmpDir, "BaseDir", "Entry.exe.config"), #endif CurrentProcessFilePath = Path.Combine(tmpDir, "ProcessDir", "Entry.exe"), EntryAssemblyLocation = string.Empty, // .NET 6 single-publish-style EntryAssemblyFileName = "Entry.dll", }; var fileLoader = new LoggingConfigurationFileLoader(appEnvMock); // Act var result = fileLoader.GetDefaultCandidateConfigFilePaths().ToList(); // Assert base-directory + process-directory + nlog-assembly-directory AssertResult(tmpDir, "BaseDir", null, "Entry", result); } [Fact] public void LoadConfigFile_NetCorePublished_UseProcessDirectory() { // Arrange var tmpDir = Path.GetTempPath(); var appEnvMock = new AppEnvironmentMock(f => true, f => null) { AppDomainBaseDirectory = Path.Combine(tmpDir, "BaseDir"), #if NETSTANDARD AppDomainConfigurationFile = string.Empty, // NetCore style #else AppDomainConfigurationFile = Path.Combine(tmpDir, "ProcessDir", "Entry.exe.config"), #endif CurrentProcessFilePath = Path.Combine(tmpDir, "ProcessDir", "Entry.exe"), // NetCore published exe EntryAssemblyLocation = Path.Combine(tmpDir, "ProcessDir"), EntryAssemblyFileName = "Entry.dll" }; var fileLoader = new LoggingConfigurationFileLoader(appEnvMock); // Act var result = fileLoader.GetDefaultCandidateConfigFilePaths().ToList(); // Assert base-directory + process-directory + nlog-assembly-directory AssertResult(tmpDir, "ProcessDir", "ProcessDir", "Entry", result); } [Fact] public void LoadConfigFile_NetCoreSingleFilePublish_IgnoreTempDirectory() { // Arrange var tmpDir = Path.GetTempPath(); var appEnvMock = new AppEnvironmentMock(f => true, f => null) { AppDomainBaseDirectory = Path.Combine(tmpDir, "BaseDir"), #if NETSTANDARD AppDomainConfigurationFile = string.Empty, // NetCore style #else AppDomainConfigurationFile = Path.Combine(tmpDir, "TempProcessDir", "Entry.exe.config"), #endif CurrentProcessFilePath = Path.Combine(tmpDir, "ProcessDir", "Entry.exe"), // NetCore published exe EntryAssemblyLocation = Path.Combine(tmpDir, "TempProcessDir"), UserTempFilePath = Path.Combine(tmpDir, "TempProcessDir"), EntryAssemblyFileName = "Entry.dll" }; var fileLoader = new LoggingConfigurationFileLoader(appEnvMock); // Act var result = fileLoader.GetDefaultCandidateConfigFilePaths().ToList(); // Assert base-directory + process-directory + nlog-assembly-directory #if NETSTANDARD Assert.Equal(Path.Combine(tmpDir, "ProcessDir", "Entry.exe.nlog"), result.First(), StringComparer.OrdinalIgnoreCase); #endif AssertResult(tmpDir, "TempProcessDir", "ProcessDir", "Entry", result); } [Fact] public void LoadConfigFile_NetCoreSingleFilePublish_IgnoreTmpDirectory() { // Arrange var tmpDir = "/var/tmp/"; var appEnvMock = new AppEnvironmentMock(f => true, f => null) { AppDomainBaseDirectory = Path.Combine(tmpDir, "BaseDir"), #if NETSTANDARD AppDomainConfigurationFile = string.Empty, // NetCore style #else AppDomainConfigurationFile = Path.Combine(tmpDir, "TempProcessDir", "Entry.exe.config"), #endif CurrentProcessFilePath = Path.Combine(tmpDir, "ProcessDir", "Entry.exe"), // NetCore published exe EntryAssemblyLocation = Path.Combine(tmpDir, "TempProcessDir"), UserTempFilePath = "/tmp/", EntryAssemblyFileName = "Entry.dll" }; var fileLoader = new LoggingConfigurationFileLoader(appEnvMock); // Act var result = fileLoader.GetDefaultCandidateConfigFilePaths().ToList(); // Assert base-directory + process-directory + nlog-assembly-directory #if NETSTANDARD Assert.Equal(Path.Combine(tmpDir, "ProcessDir", "Entry.exe.nlog"), result.First(), StringComparer.OrdinalIgnoreCase); #endif AssertResult(tmpDir, "TempProcessDir", "ProcessDir", "Entry", result); } [Fact] public void ValueWithVariableMustNotCauseInfiniteRecursion() { // Header will be printed during initialization, before config fully loaded, verify config is not loaded again var nlogConfigXml = @"<nlog throwExceptions='true'> <variable name='hello' value='header' /> <targets> <target name='debug' type='DebugSystem' header='${var:hello}' /> </targets> <rules> <logger name='*' minLevel='trace' writeTo='debug' /> </rules> </nlog>"; // Arrange var appEnvMock = new AppEnvironmentMock(f => true, f => throw new NLogConfigurationException("Never allow loading config")); var fileLoader = new LoggingConfigurationFileLoader(appEnvMock); var logFactory = new LogFactory(fileLoader).Setup().LoadConfigurationFromXml(nlogConfigXml).LogFactory; // Assert Assert.NotNull(logFactory.Configuration.FindTargetByName("debug")); } [Fact] public void CandidateConfigurationFileOnlyLoadedInitially() { // Arrange var intialLoad = true; var appEnvMock = new AppEnvironmentMock(f => true, f => { if (intialLoad) throw new System.IO.IOException("File not found"); // Non-fatal mock failure else throw new NLogConfigurationException("Never allow loading config"); // Fatal mock failure }); var fileLoader = new LoggingConfigurationFileLoader(appEnvMock); var logFactory = new LogFactory(fileLoader); // Act var firstLogger = logFactory.GetLogger("FirstLogger"); var configuration = logFactory.Configuration; intialLoad = false; // Change mock to fail fatally, if trying to load NLog config again var secondLogger = logFactory.GetLogger("SecondLogger"); // Assert Assert.Null(configuration); } private static void AssertResult(string tmpDir, string appDir, string processDir, string appName, List<string> result) { #if NETSTANDARD Assert.Contains(Path.Combine(tmpDir, processDir ?? appDir, appName + ".exe.nlog"), result, StringComparer.OrdinalIgnoreCase); Assert.Contains(Path.Combine(tmpDir, appDir, "Entry.dll.nlog"), result, StringComparer.OrdinalIgnoreCase); if (NLog.Internal.PlatformDetector.IsWin32) { if (processDir is null) Assert.Equal(4, result.Count); // Single File Publish on .NET 6 - Case insensitive else if (appDir != processDir) Assert.Equal(6, result.Count); // Single File Publish on NetCore 3.1 - Case insensitive else Assert.Equal(5, result.Count); // Case insensitive } // Verify Single File Publish will always load "exe.nlog" before "dll.nlog" var priorityIndexExe = result.FindIndex(s => s.EndsWith(appName+".exe.nlog")); var priorityIndexDll = result.FindIndex(s => s.EndsWith(appName+".dll.nlog")); Assert.True(priorityIndexExe < priorityIndexDll, $"{appName+".exe.nlog"}={priorityIndexExe} < {appName+".dll.nlog"}={priorityIndexDll}"); // Always scan for exe.nlog first #else Assert.Equal(Path.Combine(tmpDir, appDir, appName + ".exe.nlog"), result.First(), StringComparer.OrdinalIgnoreCase); if (NLog.Internal.PlatformDetector.IsWin32) { if (processDir is null) Assert.Equal(3, result.Count); // Case insensitive - No Assembly/Process-Directory else Assert.Equal(4, result.Count); // Case insensitive } #endif Assert.Contains(Path.Combine(tmpDir, "BaseDir", "NLog.config"), result, StringComparer.OrdinalIgnoreCase); Assert.Contains(Path.Combine(tmpDir, appDir, "NLog.config"), result, StringComparer.OrdinalIgnoreCase); Assert.Contains("NLog.dll.nlog", result.Last(), StringComparison.OrdinalIgnoreCase); } #if !NETSTANDARD private string appConfigContents = @" <configuration> <configSections> <section name='nlog' type='NLog.Config.ConfigSectionHandler, NLog' requirePermission='false' /> </configSections> <nlog> <targets> <target name='c' type='Console' layout='AC ${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='c' /> </rules> </nlog> </configuration> "; private string appNLogContents = @" <nlog> <targets> <target name='c' type='Console' layout='AN ${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='c' /> </rules> </nlog> "; private string nlogConfigContents = @" <nlog> <targets> <target name='c' type='Console' layout='NLC ${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='c' /> </rules> </nlog> "; private string nlogDllNLogContents = @" <nlog> <targets> <target name='c' type='Console' layout='NDN ${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='c' /> </rules> </nlog> "; private string appConfigOutput = "--BEGIN--|AC InfoMsg|AC WarnMsg|AC ErrorMsg|AC FatalMsg|--END--|"; private string appNLogOutput = "--BEGIN--|AN InfoMsg|AN WarnMsg|AN ErrorMsg|AN FatalMsg|--END--|"; private string nlogConfigOutput = "--BEGIN--|NLC InfoMsg|NLC WarnMsg|NLC ErrorMsg|NLC FatalMsg|--END--|"; private string nlogDllNLogOutput = "--BEGIN--|NDN InfoMsg|NDN WarnMsg|NDN ErrorMsg|NDN FatalMsg|--END--|"; private string missingConfigOutput = "--BEGIN--|--END--|"; [Fact] public void MissingConfigFileTest() { string output = RunTest(); Assert.Equal(missingConfigOutput, output); } [Fact] public void NLogDotConfigTest() { File.WriteAllText(Path.Combine(_tempDirectory, "NLog.config"), nlogConfigContents); string output = RunTest(); Assert.Equal(nlogConfigOutput, output); } [Fact] public void NLogDotDllDotNLogTest() { File.WriteAllText(Path.Combine(_tempDirectory, "NLog.dll.nlog"), nlogDllNLogContents); string output = RunTest(); Assert.Equal(nlogDllNLogOutput, output); } [Fact] public void NLogDotDllDotNLogInDirectoryWithSpaces() { File.WriteAllText(Path.Combine(_tempDirectory, "NLog.dll.nlog"), nlogDllNLogContents); string output = RunTest(); Assert.Equal(nlogDllNLogOutput, output); } [Fact] public void AppDotConfigTest() { File.WriteAllText(Path.Combine(_tempDirectory, "ConfigFileLocator.exe.config"), appConfigContents); string output = RunTest(); Assert.Equal(appConfigOutput, output); } [Fact] public void AppDotNLogTest() { File.WriteAllText(Path.Combine(_tempDirectory, "ConfigFileLocator.exe.nlog"), appNLogContents); string output = RunTest(); Assert.Equal(appNLogOutput, output); } [Fact] public void PrecedenceTest() { var precedence = new[] { new { File = "ConfigFileLocator.exe.config", Contents = appConfigContents, Output = appConfigOutput }, new { File = "ConfigFileLocator.exe.nlog", Contents = appNLogContents, Output = appNLogOutput }, new { File = "NLog.config", Contents = nlogConfigContents, Output = nlogConfigOutput }, new { File = "NLog.dll.nlog", Contents = nlogDllNLogContents, Output = nlogDllNLogOutput }, }; // deploy all files foreach (var p in precedence) { File.WriteAllText(Path.Combine(_tempDirectory, p.File), p.Contents); } string output; // walk files in precedence order and delete config files foreach (var p in precedence) { output = RunTest(); Assert.Equal(p.Output, output); File.Delete(Path.Combine(_tempDirectory, p.File)); } output = RunTest(); Assert.Equal(missingConfigOutput, output); } private string RunTest() { string sourceCode = @" using System; using System.Reflection; using NLog; class C1 { private static Logger logger = LogManager.GetCurrentClassLogger(); static void Main(string[] args) { Console.WriteLine(""--BEGIN--""); logger.Trace(""TraceMsg""); logger.Debug(""DebugMsg""); logger.Info(""InfoMsg""); logger.Warn(""WarnMsg""); logger.Error(""ErrorMsg""); logger.Fatal(""FatalMsg""); Console.WriteLine(""--END--""); } }"; var provider = new CSharpCodeProvider(); var options = new System.CodeDom.Compiler.CompilerParameters(); options.OutputAssembly = Path.Combine(_tempDirectory, "ConfigFileLocator.exe"); options.GenerateExecutable = true; options.ReferencedAssemblies.Add(typeof(LogFactory).Assembly.Location); options.IncludeDebugInformation = true; if (!File.Exists(options.OutputAssembly)) { var results = provider.CompileAssemblyFromSource(options, sourceCode); Assert.False(results.Errors.HasWarnings); Assert.False(results.Errors.HasErrors); File.Copy(typeof(LogFactory).Assembly.Location, Path.Combine(_tempDirectory, "NLog.dll")); } return RunAndRedirectOutput(options.OutputAssembly); } public static string RunAndRedirectOutput(string exeFile) { using (var proc = new Process()) { #if MONO var sb = new StringBuilder(); sb.AppendFormat("\"{0}\" ", exeFile); proc.StartInfo.Arguments = sb.ToString(); proc.StartInfo.FileName = "mono"; proc.StartInfo.StandardOutputEncoding = Encoding.UTF8; proc.StartInfo.StandardErrorEncoding = Encoding.UTF8; #else proc.StartInfo.FileName = exeFile; #endif proc.StartInfo.UseShellExecute = false; proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal; proc.StartInfo.RedirectStandardInput = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.StartInfo.CreateNoWindow = true; proc.Start(); proc.WaitForExit(); Assert.Equal(string.Empty, proc.StandardError.ReadToEnd()); return proc.StandardOutput.ReadToEnd().Replace("\r", "").Replace("\n", "|"); } } #endif } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using JetBrains.Annotations; using NLog.Layouts; using NLog.Targets; namespace NLog { /// <summary> /// Extensions for NLog <see cref="Layout{T}"/>. /// </summary> public static class LayoutTypedExtensions { /// <summary> /// Renders the logevent into a result-value by using the provided layout /// </summary> /// <remarks>Inside a <see cref="Target"/>, <see cref="Target.RenderLogEvent"/> is preferred for performance reasons.</remarks> /// <typeparam name="T"></typeparam> /// <param name="layout">The layout.</param> /// <param name="logEvent">The logevent info.</param> /// <param name="defaultValue">Fallback value when no value available</param> /// <returns>Result value when available, else fallback to defaultValue</returns> public static T RenderValue<T>([CanBeNull] this Layout<T> layout, [CanBeNull] LogEventInfo logEvent, T defaultValue = default(T)) { if (layout is null) return defaultValue; else return layout.RenderTypedValue(logEvent, defaultValue); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LayoutRenderers { using System; using System.Collections.Generic; using NLog.Config; using NLog.Internal; using NLog.LayoutRenderers; using NLog.Layouts; using NLog.Targets; using Xunit; public class ExceptionTests : NLogTestBase { const int E_FAIL = 80004005; private const string ExceptionDataFormat = "{0}: {1}"; [Fact] public void ExceptionWithStackTraceTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception}' /> <target name='debug2' type='Debug' layout='${exception:format=stacktrace}' /> <target name='debug3' type='Debug' layout='${exception:format=type}' /> <target name='debug4' type='Debug' layout='${exception:format=shorttype}' /> <target name='debug5' type='Debug' layout='${exception:format=tostring}' /> <target name='debug6' type='Debug' layout='${exception:format=message}' /> <target name='debug7' type='Debug' layout='${exception:format=method}' /> <target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' /> <target name='debug9' type='Debug' layout='${exception:format=data}' /> <target name='debug10' type='Debug' layout='${exception:format=source}' /> <target name='debug11' type='Debug' layout='${exception:format=hresult}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9,debug10,debug11' /> </rules> </nlog>").LogFactory; const string exceptionMessage = "Test exception"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); ex.Data.Add(exceptionDataKey, exceptionDataValue); logFactory.GetCurrentClassLogger().Error(ex, "msg"); var dataText = string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue); logFactory.AssertDebugLastMessage("debug1", ex.ToString() + " " + dataText); logFactory.AssertDebugLastMessage("debug2", ex.StackTrace); logFactory.AssertDebugLastMessage("debug3", typeof(CustomArgumentException).FullName); logFactory.AssertDebugLastMessage("debug4", typeof(CustomArgumentException).Name); logFactory.AssertDebugLastMessage("debug5", ex.ToString()); logFactory.AssertDebugLastMessage("debug6", exceptionMessage); logFactory.AssertDebugLastMessage("debug8", exceptionMessage + "*" + typeof(CustomArgumentException).Name); logFactory.AssertDebugLastMessage("debug9", dataText); logFactory.AssertDebugLastMessage("debug10", GetType().ToString()); #if !NET35 && !NET40 logFactory.AssertDebugLastMessage("debug11", $"0x{E_FAIL:X8}"); #endif // each version of the framework produces slightly different information for MethodInfo, so we just // make sure it's not empty var debug7Target = logFactory.Configuration.FindTargetByName<DebugTarget>("debug7"); Assert.False(string.IsNullOrEmpty(debug7Target.LastMessage)); } /// <summary> /// Just wrrite exception, no message argument. /// </summary> [Fact] public void ExceptionWithoutMessageParam() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception}' /> <target name='debug2' type='Debug' layout='${exception:format=stacktrace}' /> <target name='debug3' type='Debug' layout='${exception:format=type}' /> <target name='debug4' type='Debug' layout='${exception:format=shorttype}' /> <target name='debug5' type='Debug' layout='${exception:format=tostring}' /> <target name='debug6' type='Debug' layout='${exception:format=message}' /> <target name='debug7' type='Debug' layout='${exception:format=method}' /> <target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' /> <target name='debug9' type='Debug' layout='${exception:format=data}' /> <target name='debug10' type='Debug' layout='${exception:format=source}' /> <target name='debug11' type='Debug' layout='${exception:format=hresult}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9,debug10,debug11' /> </rules> </nlog>").LogFactory; const string exceptionMessage = "I don't like nullref exception!"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); ex.Data.Add(exceptionDataKey, exceptionDataValue); logFactory.GetCurrentClassLogger().Error(ex); var dataText = string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue); logFactory.AssertDebugLastMessage("debug1", ex.ToString() + " " + dataText); logFactory.AssertDebugLastMessage("debug2", ex.StackTrace); logFactory.AssertDebugLastMessage("debug3", typeof(CustomArgumentException).FullName); logFactory.AssertDebugLastMessage("debug4", typeof(CustomArgumentException).Name); logFactory.AssertDebugLastMessage("debug5", ex.ToString()); logFactory.AssertDebugLastMessage("debug6", exceptionMessage); logFactory.AssertDebugLastMessage("debug8", exceptionMessage + "*" + typeof(CustomArgumentException).Name); logFactory.AssertDebugLastMessage("debug9", dataText); logFactory.AssertDebugLastMessage("debug10", GetType().ToString()); #if !NET35 && !NET40 logFactory.AssertDebugLastMessage("debug11", $"0x{E_FAIL:X8}"); #endif // each version of the framework produces slightly different information for MethodInfo, so we just // make sure it's not empty var debug7Target = logFactory.Configuration.FindTargetByName<DebugTarget>("debug7"); Assert.False(string.IsNullOrEmpty(debug7Target.LastMessage)); } [Fact] public void ExceptionWithoutStackTraceTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception}' /> <target name='debug2' type='Debug' layout='${exception:format=stacktrace}' /> <target name='debug3' type='Debug' layout='${exception:format=type}' /> <target name='debug4' type='Debug' layout='${exception:format=shorttype}' /> <target name='debug5' type='Debug' layout='${exception:format=tostring}' /> <target name='debug6' type='Debug' layout='${exception:format=message}' /> <target name='debug7' type='Debug' layout='${exception:format=method}' /> <target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' /> <target name='debug9' type='Debug' layout='${exception:format=data}' /> <target name='debug10' type='Debug' layout='${exception:format=source}' /> <target name='debug11' type='Debug' layout='${exception:format=hresult}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9,debug10,debug11' /> </rules> </nlog>").LogFactory; const string exceptionMessage = "Test exception"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; Exception ex = GetExceptionWithoutStackTrace(exceptionMessage); ex.Data.Add(exceptionDataKey, exceptionDataValue); logFactory.GetCurrentClassLogger().Error(ex, "msg"); var dataText = string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue); logFactory.AssertDebugLastMessage("debug1", ex.ToString() + " " + dataText); logFactory.AssertDebugLastMessage("debug2", ""); logFactory.AssertDebugLastMessage("debug3", typeof(CustomArgumentException).FullName); logFactory.AssertDebugLastMessage("debug4", typeof(CustomArgumentException).Name); logFactory.AssertDebugLastMessage("debug5", ex.ToString()); logFactory.AssertDebugLastMessage("debug6", exceptionMessage); logFactory.AssertDebugLastMessage("debug7", ""); logFactory.AssertDebugLastMessage("debug8", "Test exception*" + typeof(CustomArgumentException).Name); logFactory.AssertDebugLastMessage("debug9", dataText); logFactory.AssertDebugLastMessage("debug10", ""); #if !NET35 && !NET40 logFactory.AssertDebugLastMessage("debug11", $"0x{E_FAIL:X8}"); #endif } [Fact] public void ExceptionNewLineSeparatorTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception:format=message,shorttype:separator=&#13;&#10;}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); logFactory.GetCurrentClassLogger().Error(ex, "msg"); logFactory.AssertDebugLastMessage("Test exception\r\n" + typeof(CustomArgumentException).Name); } [Fact] public void ExceptionNewLineSeparatorLayoutTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception:separator= ${NewLine} :format=message,shorttype}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); logFactory.GetCurrentClassLogger().Error(ex, "msg"); logFactory.AssertDebugLastMessage($"Test exception {System.Environment.NewLine} {typeof(CustomArgumentException).Name}"); } [Fact] public void ExceptionUsingLogMethodTest() { var logFactory = BuildConfigurationForExceptionTests(); string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); logFactory.GetCurrentClassLogger().Log(LogLevel.Error, ex, "msg"); logFactory.AssertDebugLastMessage("ERROR*msg*Test exception*" + typeof(CustomArgumentException).Name); logFactory.GetCurrentClassLogger().Log(LogLevel.Error, ex, () => "msg func"); logFactory.AssertDebugLastMessage("ERROR*msg func*Test exception*" + typeof(CustomArgumentException).Name); } [Fact] public void ExceptionUsingTraceMethodTest() { var logFactory = BuildConfigurationForExceptionTests(); string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); logFactory.GetCurrentClassLogger().Trace(ex, "msg"); logFactory.AssertDebugLastMessage("TRACE*msg*Test exception*" + typeof(CustomArgumentException).Name); logFactory.GetCurrentClassLogger().Trace(ex, () => "msg func"); logFactory.AssertDebugLastMessage("TRACE*msg func*Test exception*" + typeof(CustomArgumentException).Name); } [Fact] public void ExceptionUsingDebugMethodTest() { var logFactory = BuildConfigurationForExceptionTests(); string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); logFactory.GetCurrentClassLogger().Debug(ex, "msg"); logFactory.AssertDebugLastMessage("DEBUG*msg*Test exception*" + typeof(CustomArgumentException).Name); logFactory.GetCurrentClassLogger().Debug(ex, () => "msg func"); logFactory.AssertDebugLastMessage("DEBUG*msg func*Test exception*" + typeof(CustomArgumentException).Name); } [Fact] public void ExceptionUsingInfoMethodTest() { var logFactory = BuildConfigurationForExceptionTests(); string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); logFactory.GetCurrentClassLogger().Info(ex, "msg"); logFactory.AssertDebugLastMessage("INFO*msg*Test exception*" + typeof(CustomArgumentException).Name); logFactory.GetCurrentClassLogger().Info(ex, () => "msg func"); logFactory.AssertDebugLastMessage("INFO*msg func*Test exception*" + typeof(CustomArgumentException).Name); } [Fact] public void ExceptionUsingWarnMethodTest() { var logFactory = BuildConfigurationForExceptionTests(); string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); logFactory.GetCurrentClassLogger().Warn(ex, "msg"); logFactory.AssertDebugLastMessage("WARN*msg*Test exception*" + typeof(CustomArgumentException).Name); logFactory.GetCurrentClassLogger().Warn(ex, () => "msg func"); logFactory.AssertDebugLastMessage("WARN*msg func*Test exception*" + typeof(CustomArgumentException).Name); } [Fact] public void ExceptionUsingErrorMethodTest() { var logFactory = BuildConfigurationForExceptionTests(); string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); logFactory.GetCurrentClassLogger().Error(ex, "msg"); logFactory.AssertDebugLastMessage("ERROR*msg*Test exception*" + typeof(CustomArgumentException).Name); logFactory.GetCurrentClassLogger().Error(ex, () => "msg func"); logFactory.AssertDebugLastMessage("ERROR*msg func*Test exception*" + typeof(CustomArgumentException).Name); } [Fact] public void ExceptionUsingFatalMethodTest() { var logFactory = BuildConfigurationForExceptionTests(); string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); logFactory.GetCurrentClassLogger().Fatal(ex, "msg"); logFactory.AssertDebugLastMessage("FATAL*msg*Test exception*" + typeof(CustomArgumentException).Name); logFactory.GetCurrentClassLogger().Fatal(ex, () => "msg func"); logFactory.AssertDebugLastMessage("FATAL*msg func*Test exception*" + typeof(CustomArgumentException).Name); } [Fact] public void InnerExceptionTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=3}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; string exceptionMessage = "Test exception"; Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage); logFactory.GetCurrentClassLogger().Error(ex, "msg"); logFactory.AssertDebugLastMessage("ApplicationException Wrapper2" + EnvironmentHelper.NewLine + "ArgumentException Wrapper1" + EnvironmentHelper.NewLine + "CustomArgumentException Test exception"); } [Fact] public void InnerExceptionTest_Serialize() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception:format=@}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; string exceptionMessage = "Test exception"; Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage); logFactory.GetCurrentClassLogger().Error(ex, "msg"); var lastMessage = logFactory.AssertDebugLastMessageNotEmpty(); Assert.StartsWith("{\"Type\":\"System.ApplicationException\", ", lastMessage); Assert.Contains("\"InnerException\":{\"Type\":\"System.ArgumentException\", ", lastMessage); Assert.Contains("\"ParamName\":\"exceptionMessage\"", lastMessage); Assert.Contains("1Really_Bad_Boy_", lastMessage); } [Fact] public void CustomInnerExceptionTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator=&#13;&#10;----INNER----&#13;&#10;:innerFormat=type,message}' /> <target name='debug2' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator=&#13;&#10;----INNER----&#13;&#10;:innerFormat=type,message,data}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1' /> <logger minlevel='Info' writeTo='debug2' /> </rules> </nlog>").LogFactory; var t = (DebugTarget)logFactory.Configuration.AllTargets[0]; var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer; Assert.Equal("\r\n----INNER----\r\n", elr.InnerExceptionSeparator); string exceptionMessage = "Test exception"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage); ex.InnerException.Data.Add(exceptionDataKey, exceptionDataValue); logFactory.GetCurrentClassLogger().Error(ex, "msg"); logFactory.AssertDebugLastMessage("debug1", "ApplicationException Wrapper2" + "\r\n----INNER----\r\n" + "System.ArgumentException Wrapper1"); logFactory.AssertDebugLastMessage("debug2", string.Format("ApplicationException Wrapper2" + "\r\n----INNER----\r\n" + "System.ArgumentException Wrapper1 " + ExceptionDataFormat, exceptionDataKey, exceptionDataValue)); } [Fact] public void ErrorException_should_not_throw_exception_when_exception_message_property_throw_exception() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetCurrentClassLogger(); var ex = new ExceptionWithBrokenMessagePropertyException(); var exRecorded = Record.Exception(() => logger.Error(ex, "msg")); Assert.Null(exRecorded); } [Fact] public void ErrorException_should_not_throw_exception_when_exception_message_property_throw_exception_serialize() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception:format=@}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetCurrentClassLogger(); var ex = new ExceptionWithBrokenMessagePropertyException(); var exRecorded = Record.Exception(() => logger.Error(ex, "msg")); Assert.Null(exRecorded); } #if NET35 [Fact(Skip = "NET35 not supporting AggregateException")] #else [Fact] #endif public void AggregateExceptionMultiTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=5}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; var task1 = System.Threading.Tasks.Task.Factory.StartNew(() => { throw new Exception("Test exception 1", new Exception("Test Inner 1")); }, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default); var task2 = System.Threading.Tasks.Task.Factory.StartNew(() => { throw new Exception("Test exception 2", new Exception("Test Inner 2")); }, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default); var aggregateExceptionMessage = "nothing thrown!"; try { System.Threading.Tasks.Task.WaitAll(new[] { task1, task2 }); } catch (AggregateException ex) { aggregateExceptionMessage = ex.ToString(); logFactory.GetCurrentClassLogger().Error(ex, "msg"); } Assert.Contains("Test exception 1", aggregateExceptionMessage); Assert.Contains("Test exception 2", aggregateExceptionMessage); Assert.Contains("Test Inner 1", aggregateExceptionMessage); Assert.Contains("Test Inner 2", aggregateExceptionMessage); logFactory.AssertDebugLastMessageContains("AggregateException"); logFactory.AssertDebugLastMessageContains("One or more errors occurred"); logFactory.AssertDebugLastMessageContains("Test exception 1"); logFactory.AssertDebugLastMessageContains("Test exception 2"); logFactory.AssertDebugLastMessageContains("Test Inner 1"); logFactory.AssertDebugLastMessageContains("Test Inner 2"); } #if NET35 [Fact(Skip = "NET35 not supporting AggregateException")] #else [Fact] #endif public void AggregateExceptionWithExceptionDataMultiTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception:format=shorttype,data,message:maxInnerExceptionLevel=5}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; string exceptionData1Key = "ex1Key"; string exceptionData1Value = "ex1Value"; var task1 = System.Threading.Tasks.Task.Factory.StartNew(() => { var ex1 = new Exception("Test exception 1", new Exception("Test Inner 1")); ex1.Data.Add(exceptionData1Key, exceptionData1Value); throw ex1; }, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default); string exceptionData2Key = "ex2Key"; string exceptionData2Value = "ex2Value"; var task2 = System.Threading.Tasks.Task.Factory.StartNew(() => { var ex2 = new Exception("Test exception 2", new Exception("Test Inner 2")); ex2.Data.Add(exceptionData2Key, exceptionData2Value); throw ex2; }, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default); string aggregateExceptionDataKey = "aggreKey"; string aggregateExceptionDataValue = "aggreValue"; var aggregateExceptionMessage = "nothing thrown!"; try { System.Threading.Tasks.Task.WaitAll(new[] { task1, task2 }); } catch (AggregateException ex) { ex.Data.Add(aggregateExceptionDataKey, aggregateExceptionDataValue); aggregateExceptionMessage = ex.ToString(); logFactory.GetCurrentClassLogger().Error(ex, "msg"); } Assert.Contains("Test exception 1", aggregateExceptionMessage); Assert.Contains("Test exception 2", aggregateExceptionMessage); Assert.Contains("Test Inner 1", aggregateExceptionMessage); Assert.Contains("Test Inner 2", aggregateExceptionMessage); logFactory.AssertDebugLastMessageContains("AggregateException"); logFactory.AssertDebugLastMessageContains("One or more errors occurred"); logFactory.AssertDebugLastMessageContains("Test exception 1"); logFactory.AssertDebugLastMessageContains("Test exception 2"); logFactory.AssertDebugLastMessageContains("Test Inner 1"); logFactory.AssertDebugLastMessageContains("Test Inner 2"); logFactory.AssertDebugLastMessageContains(string.Format(ExceptionDataFormat, exceptionData1Key, exceptionData1Value)); logFactory.AssertDebugLastMessageContains(string.Format(ExceptionDataFormat, exceptionData2Key, exceptionData2Value)); logFactory.AssertDebugLastMessageContains(string.Format(ExceptionDataFormat, aggregateExceptionDataKey, aggregateExceptionDataValue)); } #if NET35 [Fact(Skip = "NET35 not supporting AggregateException")] #else [Fact] #endif public void AggregateExceptionSingleTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception:format=message,shorttype:maxInnerExceptionLevel=5}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; var task1 = System.Threading.Tasks.Task.Factory.StartNew(() => { throw new Exception("Test exception 1", new Exception("Test Inner 1")); }, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default); var aggregateExceptionMessage = "nothing thrown!"; try { System.Threading.Tasks.Task.WaitAll(new[] { task1 }); } catch (AggregateException ex) { aggregateExceptionMessage = ex.ToString(); logFactory.GetCurrentClassLogger().Error(ex, "msg"); } Assert.Contains(typeof(AggregateException).Name, aggregateExceptionMessage); Assert.Contains("Test exception 1", aggregateExceptionMessage); Assert.Contains("Test Inner 1", aggregateExceptionMessage); var lastMessage = logFactory.AssertDebugLastMessageNotEmpty(); Assert.StartsWith("Test exception 1", lastMessage); Assert.Contains("Test Inner 1", lastMessage); } #if NET35 [Fact(Skip = "NET35 not supporting AggregateException")] #else [Fact] #endif public void AggregateExceptionWithExceptionDataSingleTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception:format=message,data,shorttype:maxInnerExceptionLevel=5}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; string exceptionDataKey = "ex1Key"; string exceptionDataValue = "ex1Value"; var task1 = System.Threading.Tasks.Task.Factory.StartNew(() => { var ex = new Exception("Test exception 1", new Exception("Test Inner 1")); ex.Data.Add(exceptionDataKey, exceptionDataValue); throw ex; }, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default); string aggregateExceptionDataKey = "aggreKey"; string aggregateExceptionDataValue = "aggreValue"; var aggregateExceptionMessage = "nothing thrown!"; try { System.Threading.Tasks.Task.WaitAll(new[] { task1 }); } catch (AggregateException ex) { ex.Data.Add(aggregateExceptionDataKey, aggregateExceptionDataValue); aggregateExceptionMessage = ex.ToString(); logFactory.GetCurrentClassLogger().Error(ex, "msg"); } Assert.Contains(typeof(AggregateException).Name, aggregateExceptionMessage); Assert.Contains("Test exception 1", aggregateExceptionMessage); Assert.Contains("Test Inner 1", aggregateExceptionMessage); var lastMessage = logFactory.AssertDebugLastMessageNotEmpty(); Assert.StartsWith("Test exception 1", lastMessage); Assert.Contains("Test Inner 1", lastMessage); Assert.Contains(string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue), lastMessage); Assert.Contains(string.Format(ExceptionDataFormat, aggregateExceptionDataKey, aggregateExceptionDataValue), lastMessage); } [Fact] public void CustomExceptionProperties_Layout_Test() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception:format=Properties}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; var ex = new CustomArgumentException("Goodbye World", "Nuke"); logFactory.GetCurrentClassLogger().Fatal(ex, "msg"); logFactory.AssertDebugLastMessage($"{nameof(CustomArgumentException.ParamName)}: Nuke"); } [Fact] public void BaseExceptionTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception:format=Message:BaseException=true}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; var ex = GetNestedExceptionWithStackTrace("Goodbye World"); logFactory.GetCurrentClassLogger().Fatal(ex, "msg"); logFactory.AssertDebugLastMessage("Goodbye World"); } #if NET35 [Fact(Skip = "NET35 not supporting AggregateException")] #else [Fact] #endif public void RecursiveAsyncExceptionWithoutFlattenException() { var recursionCount = 3; Func<int> innerAction = () => throw new ApplicationException("Life is hard"); var t1 = System.Threading.Tasks.Task<int>.Factory.StartNew(() => { return NestedFunc(recursionCount, innerAction); }); try { t1.Wait(); } catch (AggregateException ex) { var layoutRenderer = new ExceptionLayoutRenderer() { Format = "ToString", FlattenException = false }; var logEvent = LogEventInfo.Create(LogLevel.Error, null, null, (object)ex); var result = layoutRenderer.Render(logEvent); int needleCount = 0; int foundIndex = result.IndexOf(nameof(NestedFunc), 0); while (foundIndex >= 0) { ++needleCount; foundIndex = result.IndexOf(nameof(NestedFunc), foundIndex + nameof(NestedFunc).Length); } Assert.True(needleCount >= recursionCount, $"{needleCount} too small"); } } private class ExceptionWithBrokenMessagePropertyException : NLogConfigurationException { public override string Message => throw new Exception("Exception from Message property"); } private static LogFactory BuildConfigurationForExceptionTests() { return new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${level:uppercase=true}*${message}*${exception:format=message,shorttype:separator=*}' /> </targets> <rules> <logger minlevel='Trace' writeTo='debug' /> </rules> </nlog>").LogFactory; } /// <summary> /// Get an exception with stacktrace by generating a exception /// </summary> /// <param name="exceptionMessage"></param> /// <returns></returns> private Exception GetExceptionWithStackTrace(string exceptionMessage) { try { GenericClass<int, string, bool>.Method1("aaa", true, null, 42, DateTime.Now, exceptionMessage); return null; } catch (Exception exception) { exception.Source = GetType().ToString(); return exception; } } private static Exception GetNestedExceptionWithStackTrace(string exceptionMessage) { try { try { try { GenericClass<int, string, bool>.Method1("aaa", true, null, 42, DateTime.Now, exceptionMessage); } catch (Exception exception) { throw new System.ArgumentException("Wrapper1", exception); } } catch (Exception exception) { throw new ApplicationException("Wrapper2", exception); } return null; } catch (Exception ex) { ex.Data["1Really.Bad-Boy!"] = "Hello World"; return ex; } } private int NestedFunc(int recursion, Func<int> innerAction) { try { if (recursion-- == 0) return System.Threading.Tasks.Task<int>.Factory.StartNew(() => innerAction.Invoke()) .Result; return NestedFunc(recursion, innerAction); } catch { throw; // Just to make the method complex, and avoid inline } } private static Exception GetExceptionWithoutStackTrace(string exceptionMessage) { return new CustomArgumentException(exceptionMessage, "exceptionMessage"); } private class GenericClass<TA, TB, TC> { internal static List<GenericClass<TA, TB, TC>> Method1(string aaa, bool b, object o, int i, DateTime now, string exceptionMessage) { Method2(aaa, b, o, i, now, null, null, exceptionMessage); return null; } internal static int Method2<T1, T2, T3>(T1 aaa, T2 b, T3 o, int i, DateTime now, Nullable<int> gfff, List<int>[] something, string exceptionMessage) { throw new CustomArgumentException(exceptionMessage, "exceptionMessage"); } } public class CustomArgumentException : ApplicationException { public CustomArgumentException(string message, string paramName) : base(message) { ParamName = paramName; StrangeProperty = "Strange World"; HResult = E_FAIL; } public string ParamName { get; } public string StrangeProperty { private get; set; } } [Fact] public void ExcpetionTestAPI() { var logFactory = new LogFactory().Setup().LoadConfiguration(builder => { var debugTarget = new DebugTarget("debug"); debugTarget.Layout = @"${exception:format=shorttype,message:maxInnerExceptionLevel=3}"; builder.ForLogger().WriteTo(debugTarget); }).LogFactory; string exceptionMessage = "Test exception"; Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage); logFactory.GetCurrentClassLogger().Error(ex, "msg"); logFactory.AssertDebugLastMessage("ApplicationException Wrapper2" + EnvironmentHelper.NewLine + "ArgumentException Wrapper1" + EnvironmentHelper.NewLine + "CustomArgumentException Test exception"); var t = (DebugTarget)logFactory.Configuration.AllTargets[0]; var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer; Assert.Equal(ExceptionRenderingFormat.ShortType, elr.Formats[0]); Assert.Equal(ExceptionRenderingFormat.Message, elr.Formats[1]); } [Fact] public void InnerExceptionTestAPI() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=3:innerFormat=message}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; string exceptionMessage = "Test exception"; Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage); logFactory.GetCurrentClassLogger().Error(ex, "msg"); logFactory.AssertDebugLastMessage("ApplicationException Wrapper2" + EnvironmentHelper.NewLine + "Wrapper1" + EnvironmentHelper.NewLine + "Test exception"); var t = (DebugTarget)logFactory.Configuration.AllTargets[0]; var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer; Assert.Equal(ExceptionRenderingFormat.ShortType, elr.Formats[0]); Assert.Equal(ExceptionRenderingFormat.Message, elr.Formats[1]); Assert.Equal(ExceptionRenderingFormat.Message, elr.InnerFormats[0]); } [Fact] public void CustomExceptionLayoutRendrerInnerExceptionTest() { var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterLayoutRenderer<CustomExceptionLayoutRendrer>("exception-custom")) .LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception-custom:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator=&#13;&#10;----INNER----&#13;&#10;:innerFormat=type,message}' /> <target name='debug2' type='Debug' layout='${exception-custom:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator=&#13;&#10;----INNER----&#13;&#10;:innerFormat=type,message,data}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1' /> <logger minlevel='Info' writeTo='debug2' /> </rules> </nlog>").LogFactory; var t = (DebugTarget)logFactory.Configuration.AllTargets[0]; var elr = ((SimpleLayout)t.Layout).Renderers[0] as CustomExceptionLayoutRendrer; Assert.Equal("\r\n----INNER----\r\n", elr.InnerExceptionSeparator); string exceptionMessage = "Test exception"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage); ex.InnerException.Data.Add(exceptionDataKey, exceptionDataValue); logFactory.GetCurrentClassLogger().Error(ex, "msg"); logFactory.AssertDebugLastMessage("debug1", "ApplicationException Wrapper2" + "\r\ncustom-exception-renderer" + "\r\n----INNER----\r\n" + "System.ArgumentException Wrapper1" + "\r\ncustom-exception-renderer"); logFactory.AssertDebugLastMessage("debug2", string.Format("ApplicationException Wrapper2" + "\r\ncustom-exception-renderer" + "\r\n----INNER----\r\n" + "System.ArgumentException Wrapper1" + "\r\ncustom-exception-renderer " + ExceptionDataFormat, exceptionDataKey, exceptionDataValue + "\r\ncustom-exception-renderer-data")); } [Fact] public void ExceptionDataWithDifferentSeparators() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception:format=data}' /> <target name='debug2' type='Debug' layout='${exception:format=data:ExceptionDataSeparator=*}' /> <target name='debug3' type='Debug' layout='${exception:format=data:ExceptionDataSeparator=## **}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1, debug2, debug3' /> </rules> </nlog>").LogFactory; const string defaultExceptionDataSeparator = ";"; const string exceptionMessage = "message for exception"; const string exceptionDataKey1 = "testkey1"; const string exceptionDataValue1 = "testvalue1"; const string exceptionDataKey2 = "testkey2"; const string exceptionDataValue2 = "testvalue2"; var target = (DebugTarget)logFactory.Configuration.AllTargets[0]; var exceptionLayoutRenderer = ((SimpleLayout)target.Layout).Renderers[0] as ExceptionLayoutRenderer; Assert.NotNull(exceptionLayoutRenderer); Assert.Equal(defaultExceptionDataSeparator, exceptionLayoutRenderer.ExceptionDataSeparator); Exception ex = GetExceptionWithStackTrace(exceptionMessage); ex.Data.Add(exceptionDataKey1, exceptionDataValue1); ex.Data.Add(exceptionDataKey2, exceptionDataValue2); logFactory.GetCurrentClassLogger().Error(ex); logFactory.AssertDebugLastMessage("debug1", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + defaultExceptionDataSeparator + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2)); logFactory.AssertDebugLastMessage("debug2", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + "*" + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2)); logFactory.AssertDebugLastMessage("debug3", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + "## **" + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2)); } [Fact] public void ExceptionDataWithNewLineSeparator() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception:format=data:ExceptionDataSeparator=\r\n}' /> <target name='debug2' type='Debug' layout='${exception:format=data:ExceptionDataSeparator=\r\n----DATA----\r\n}' /> <target name='debug3' type='Debug' layout='${exception:format=data:ExceptionDataSeparator=&#13;&#10;----DATA----&#13;&#10;}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1, debug2, debug3' /> </rules> </nlog>").LogFactory; const string exceptionMessage = "message for exception"; const string exceptionDataKey1 = "testkey1"; const string exceptionDataValue1 = "testvalue1"; const string exceptionDataKey2 = "testkey2"; const string exceptionDataValue2 = "testvalue2"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); ex.Data.Add(exceptionDataKey1, exceptionDataValue1); ex.Data.Add(exceptionDataKey2, exceptionDataValue2); logFactory.GetCurrentClassLogger().Error(ex); logFactory.AssertDebugLastMessage("debug1", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + "\r\n" + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2)); logFactory.AssertDebugLastMessage("debug2", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + "\r\n----DATA----\r\n" + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2)); logFactory.AssertDebugLastMessage("debug3", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + "\r\n----DATA----\r\n" + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2)); } [Fact] public void ExceptionWithSeparatorForExistingRender() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception:format=tostring,data:separator=\r\nXXX}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; const string exceptionMessage = "message for exception"; const string exceptionDataKey1 = "testkey1"; const string exceptionDataValue1 = "testvalue1"; Exception ex = GetExceptionWithoutStackTrace(exceptionMessage); ex.Data.Add(exceptionDataKey1, exceptionDataValue1); logFactory.GetCurrentClassLogger().Error(ex); logFactory.AssertDebugLastMessage(string.Format(ExceptionDataFormat, ex.GetType().FullName, exceptionMessage) + "\r\nXXX" + string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1)); } [Fact] public void ExceptionWithSeparatorForExistingBetweenRender() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception:format=tostring,data,type:separator=\r\nXXX}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; const string exceptionMessage = "message for exception"; const string exceptionDataKey1 = "testkey1"; const string exceptionDataValue1 = "testvalue1"; Exception ex = GetExceptionWithoutStackTrace(exceptionMessage); ex.Data.Add(exceptionDataKey1, exceptionDataValue1); logFactory.GetCurrentClassLogger().Error(ex); logFactory.AssertDebugLastMessage( string.Format(ExceptionDataFormat, ex.GetType().FullName, exceptionMessage) + "\r\nXXX" + string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + "\r\nXXX" + ex.GetType().FullName); } [Fact] public void ExceptionWithoutSeparatorForNoRender() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception:format=tostring,data:separator=\r\nXXX}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; const string exceptionMessage = "message for exception"; Exception ex = GetExceptionWithoutStackTrace(exceptionMessage); logFactory.GetCurrentClassLogger().Error(ex); logFactory.AssertDebugLastMessage(string.Format(ExceptionDataFormat, ex.GetType().FullName, exceptionMessage)); } [Fact] public void ExceptionWithoutSeparatorForNoBetweenRender() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets> <target name='debug' type='Debug' layout='${exception:format=tostring,data,type:separator=\r\nXXX}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug' /> </rules> </nlog>").LogFactory; const string exceptionMessage = "message for exception"; Exception ex = GetExceptionWithoutStackTrace(exceptionMessage); logFactory.GetCurrentClassLogger().Error(ex); logFactory.AssertDebugLastMessage( string.Format(ExceptionDataFormat, ex.GetType().FullName, exceptionMessage) + "\r\nXXX" + ex.GetType().FullName); } } [LayoutRenderer("exception-custom")] [ThreadAgnostic] public class CustomExceptionLayoutRendrer : ExceptionLayoutRenderer { protected override void AppendMessage(System.Text.StringBuilder sb, Exception ex) { base.AppendMessage(sb, ex); sb.Append("\r\ncustom-exception-renderer"); } protected override void AppendData(System.Text.StringBuilder sb, Exception ex) { base.AppendData(sb, ex); sb.Append("\r\ncustom-exception-renderer-data"); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; /// <summary> /// Writes log events to all targets. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/SplitGroup-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/SplitGroup-target">Documentation on NLog Wiki</seealso> /// <example> /// <p>This example causes the messages to be written to both file1.txt or file2.txt /// </p> /// <p> /// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/SplitGroup/NLog.config" /> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/SplitGroup/Simple/Example.cs" /> /// </example> [Target("SplitGroup", IsCompound = true)] public class SplitGroupTarget : CompoundTargetBase { /// <summary> /// Initializes a new instance of the <see cref="SplitGroupTarget" /> class. /// </summary> public SplitGroupTarget() : this(NLog.Internal.ArrayHelper.Empty<Target>()) { } /// <summary> /// Initializes a new instance of the <see cref="SplitGroupTarget" /> class. /// </summary> /// <param name="name">Name of the target.</param> /// <param name="targets">The targets.</param> public SplitGroupTarget(string name, params Target[] targets) : this(targets) { Name = name; } /// <summary> /// Initializes a new instance of the <see cref="SplitGroupTarget" /> class. /// </summary> /// <param name="targets">The targets.</param> public SplitGroupTarget(params Target[] targets) : base(targets) { } /// <summary> /// Forwards the specified log event to all sub-targets. /// </summary> /// <param name="logEvent">The log event.</param> protected override void Write(AsyncLogEventInfo logEvent) { if (Targets.Count == 0) { logEvent.Continuation(null); } else { if (Targets.Count > 1) { logEvent = logEvent.LogEvent.WithContinuation(CreateCountedContinuation(logEvent.Continuation, Targets.Count)); } for (int i = 0; i < Targets.Count; ++i) { Targets[i].WriteAsyncLogEvent(logEvent); } } } /// <summary> /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected override void Write(IList<AsyncLogEventInfo> logEvents) { InternalLogger.Trace("{0}: Writing {1} events", this, logEvents.Count); if (logEvents.Count == 1) { Write(logEvents[0]); // Skip array allocation for each destination target } else if (Targets.Count == 0 || logEvents.Count == 0) { for (int i = 0; i < logEvents.Count; ++i) { logEvents[i].Continuation(null); } } else { if (Targets.Count > 1) { for (int i = 0; i < logEvents.Count; ++i) { AsyncLogEventInfo ev = logEvents[i]; logEvents[i] = ev.LogEvent.WithContinuation(CreateCountedContinuation(ev.Continuation, Targets.Count)); } } for (int i = 0; i < Targets.Count; ++i) { InternalLogger.Trace("{0}: Sending {1} events to {2}", this, logEvents.Count, Targets[i]); var targetLogEvents = logEvents; if (i < Targets.Count - 1) { // WriteAsyncLogEvents will modify the input-array (so we make clones here) AsyncLogEventInfo[] cloneLogEvents = new AsyncLogEventInfo[logEvents.Count]; logEvents.CopyTo(cloneLogEvents, 0); targetLogEvents = cloneLogEvents; } Targets[i].WriteAsyncLogEvents(targetLogEvents); } } } private static AsyncContinuation CreateCountedContinuation(AsyncContinuation originalContinuation, int targetCounter) { var exceptions = new List<Exception>(); AsyncContinuation wrapper = ex => { if (ex != null) { lock (exceptions) { exceptions.Add(ex); } } int pendingTargets = Interlocked.Decrement(ref targetCounter); if (pendingTargets == 0) { var combinedException = AsyncHelpers.GetCombinedException(exceptions); InternalLogger.Trace("SplitGroup: Combined exception: {0}", combinedException); originalContinuation(combinedException); } else { InternalLogger.Trace("SplitGroup: {0} remaining.", pendingTargets); } }; return wrapper; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Layouts { using System; using System.Text; using NLog.Config; using NLog.Internal; using NLog.LayoutRenderers; using NLog.Layouts; using Xunit; public class SimpleLayoutOutputTests : NLogTestBase { [Fact] public void VeryLongRendererOutput() { int stringLength = 100000; SimpleLayout l = new string('x', stringLength) + "${message}"; string output = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal(new string('x', stringLength), output); string output2 = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal(new string('x', stringLength), output); Assert.NotSame(output, output2); } [Fact] public void LayoutRendererThrows() { using (new NoThrowNLogExceptions()) { ConfigurationItemFactory configurationItemFactory = new ConfigurationItemFactory(); configurationItemFactory.LayoutRendererFactory.RegisterType<ThrowsExceptionRenderer>("throwsException"); SimpleLayout l = new SimpleLayout("xx${throwsException}yy", configurationItemFactory); string output = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("xxyy", output); } } [Fact] public void SimpleLayoutCachingTest() { var l = new SimpleLayout("xx${threadid}yy"); var ev = LogEventInfo.CreateNullEvent(); string output1 = l.Render(ev); string output2 = l.Render(ev); Assert.Same(output1, output2); } [Fact] public void SimpleLayoutToStringTest() { var l = new SimpleLayout("xx${level}yy"); Assert.Equal("xx${level}yy", l.ToString()); var l2 = new SimpleLayout(ArrayHelper.Empty<LayoutRenderer>(), "someFakeText", ConfigurationItemFactory.Default); Assert.Equal("someFakeText", l2.ToString()); var l3 = new SimpleLayout(""); Assert.Equal("", l3.ToString()); } [Fact] public void LayoutRendererThrows2() { string internalLogOutput = RunAndCaptureInternalLog( () => { using (new NoThrowNLogExceptions()) { ConfigurationItemFactory configurationItemFactory = new ConfigurationItemFactory(); configurationItemFactory.LayoutRendererFactory.RegisterType<ThrowsExceptionRenderer>("throwsException"); SimpleLayout l = new SimpleLayout("xx${throwsException:msg1}yy${throwsException:msg2}zz", configurationItemFactory); string output = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("xxyyzz", output); } }, LogLevel.Warn); Assert.Contains("msg1", internalLogOutput); Assert.Contains("msg2", internalLogOutput); } [Fact] public void LayoutInitTest1() { var lr = new MockLayout(); Assert.Equal(0, lr.InitCount); Assert.Equal(0, lr.CloseCount); // make sure render will call Init lr.Render(LogEventInfo.CreateNullEvent()); Assert.Equal(1, lr.InitCount); Assert.Equal(0, lr.CloseCount); lr.Close(); Assert.Equal(1, lr.InitCount); Assert.Equal(1, lr.CloseCount); // second call to Close() will be ignored lr.Close(); Assert.Equal(1, lr.InitCount); Assert.Equal(1, lr.CloseCount); } [Fact] public void LayoutInitTest2() { var lr = new MockLayout(); Assert.Equal(0, lr.InitCount); Assert.Equal(0, lr.CloseCount); // calls to Close() will be ignored because lr.Close(); Assert.Equal(0, lr.InitCount); Assert.Equal(0, lr.CloseCount); lr.Initialize(null); Assert.Equal(1, lr.InitCount); // make sure render will not call another Init lr.Render(LogEventInfo.CreateNullEvent()); Assert.Equal(1, lr.InitCount); Assert.Equal(0, lr.CloseCount); lr.Close(); Assert.Equal(1, lr.InitCount); Assert.Equal(1, lr.CloseCount); } [Fact] public void TryGetRawValue_SingleLayoutRender_ShouldGiveRawValue() { // Arrange SimpleLayout l = "${sequenceid}"; var logEventInfo = LogEventInfo.CreateNullEvent(); // Act var success = l.TryGetRawValue(logEventInfo, out var value); // Assert Assert.True(success, "success"); Assert.IsType<int>(value); Assert.True((int)value >= 0, "(int)value >= 0"); } [Fact] public void TryGetRawValue_MultipleLayoutRender_ShouldGiveNullRawValue() { // Arrange SimpleLayout l = "${sequenceid} "; var logEventInfo = LogEventInfo.CreateNullEvent(); // Act var success = l.TryGetRawValue(logEventInfo, out var value); // Assert Assert.False(success); Assert.Null(value); } [Fact] public void TryGetRawValue_MutableLayoutRender_ShouldGiveNullRawValue() { // Arrange SimpleLayout l = "${event-properties:builder}"; var logEventInfo = LogEventInfo.CreateNullEvent(); logEventInfo.Properties["builder"] = new StringBuilder("mybuilder"); l.Precalculate(logEventInfo); // Act var success = l.TryGetRawValue(logEventInfo, out var value); // Assert Assert.False(success); Assert.Null(value); } [Fact] public void TryGetRawValue_ImmutableLayoutRender_ShouldGiveRawValue() { // Arrange SimpleLayout l = "${event-properties:correlationid}"; var logEventInfo = LogEventInfo.CreateNullEvent(); var correlationId = Guid.NewGuid(); logEventInfo.Properties["correlationid"] = correlationId; l.Precalculate(logEventInfo); // Act var success = l.TryGetRawValue(logEventInfo, out var value); // Assert Assert.True(success, "success"); Assert.IsType<Guid>(value); Assert.Equal(correlationId, value); } [Fact] public void TryGetRawValue_WhenEmpty_ShouldNotFailWithNullException() { // Arrange SimpleLayout l = "${event-properties:eventId:whenEmpty=0}"; var logEventInfo = LogEventInfo.CreateNullEvent(); l.Precalculate(logEventInfo); // Act var success = l.TryGetRawValue(logEventInfo, out var value); // Assert Assert.False(success, "Missing EventId"); } public class ThrowsExceptionRenderer : LayoutRenderer { public ThrowsExceptionRenderer() { Message = "Some message."; } [RequiredParameter] [DefaultParameter] public string Message { get; set; } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { throw new ApplicationException(Message); } } public class MockLayout : Layout { public int InitCount { get; set; } public int CloseCount { get; set; } protected override void InitializeLayout() { base.InitializeLayout(); InitCount++; } protected override void CloseLayout() { base.CloseLayout(); CloseCount++; } protected override string GetFormattedMessage(LogEventInfo logEvent) { return "foo"; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections; using System.Collections.Generic; using System.Dynamic; using System.Globalization; using System.Text.RegularExpressions; using NLog.Config; using NLog.Internal; using NLog.Targets; using Xunit; namespace NLog.UnitTests.Targets { /// <summary> /// Base class for the <see cref="DefaultJsonSerializer"/> (<see cref="IJsonConverter"/> and <see cref="IJsonSerializer"/> interfaces) /// </summary> public abstract class DefaultJsonSerializerTestsBase : NLogTestBase { protected abstract string SerializeObject(object o); [Fact] public void SingleLineString_Test() { var text = "This is, sort of, surprising the 1. time you see that test-result."; var expected = "\"This is, sort of, surprising the 1. time you see that test-result.\""; var actual = SerializeObject(text); Assert.Equal(expected, actual); } [Fact] public void MultiLineString_Test() { var text = "First line followed by Windows line break\r\nNow this is second with UNIX\nand third at last"; var expected = "\"First line followed by Windows line break\\r\\nNow this is second with UNIX\\nand third at last\""; var actual = SerializeObject(text); Assert.Equal(expected, actual); } [Fact] public void StringWithTabBackSpaceFormfeed_Test() { var text = "A tab\tis followed by a feed\fand finally cancel last character\b"; var expected = "\"A tab\\tis followed by a feed\\fand finally cancel last character\\b\""; var actual = SerializeObject(text); Assert.Equal(expected, actual); } [Fact] public void StringWithSlashAndQuotes_Test() { var text = "This sentence/text is \"normal\", we think."; var expected = "\"This sentence/text is \\\"normal\\\", we think.\""; var actual = SerializeObject(text); Assert.Equal(expected, actual); } [Fact] public void SerializeUnicode_test() { var actual = SerializeObject("©"); Assert.Equal("\"©\"", actual); } [Fact] public void SerializeUnicodeInAnomObject_test() { var item = new { text = "©" }; var actual = SerializeObject(item); Assert.Equal("{\"text\":\"©\"}", actual); } [Fact] public void ReferenceLoopInDictionary_Test() { var d = new Dictionary<string, object>(); d.Add("First", 17); d.Add("Loop", d); var target = new Dictionary<string, object> { {"Name", "TestObject" }, {"Assets" , d } }; var expected = "{\"Name\":\"TestObject\",\"Assets\":{\"First\":17}}"; var actual = SerializeObject(target); Assert.Equal(expected, actual); } [Fact] public void ReferenceLoopInList_Test() { var d = new List<object>(); d.Add(17); d.Add(d); d.Add(3.14); var target = new List<object> { {"TestObject" }, {d } }; var expected = "[\"TestObject\",[17,3.14]]"; var actual = SerializeObject(target); Assert.Equal(expected, actual); } [Fact] public void InfiniteLoop_Test() { var d = new TestList(); var actual = SerializeObject(d); var cnt = Regex.Matches(actual, "\\[\"alpha\",\"bravo\"\\]").Count; Assert.Equal(10, cnt); } [Fact] public void StringWithMixedControlCharacters_Test() { var text = "First\\Second\tand" + (char)3 + "for" + (char)0x1f + "with" + (char)0x10 + "but" + (char)0x0d + "and no" + (char)0x20; var expected = "\"First\\\\Second\\tand\\u0003for\\u001fwith\\u0010but\\rand no \""; var actual = SerializeObject(text); Assert.Equal(expected, actual); } [Theory] [InlineData((short)177, "177")] [InlineData((ushort)177, "177")] [InlineData((int)177, "177")] [InlineData((uint)177, "177")] [InlineData((long)32711520331, "32711520331")] [InlineData((ulong)32711520331, "32711520331")] [InlineData(3.14159265, "3.14159265")] [InlineData(2776145.7743, "2776145.7743")] [InlineData(0D, "0.0")] [InlineData(0F, "0.0")] [InlineData(1D, "1.0")] [InlineData(1F, "1.0")] [InlineData(-1D, "-1.0")] [InlineData(-1F, "-1.0")] [InlineData(5e30D, "5E+30")] [InlineData(5e30F, "5E+30")] [InlineData(-5e30D, "-5E+30")] [InlineData(-5e30F, "-5E+30")] [InlineData(double.NaN, "\"NaN\"")] [InlineData(double.PositiveInfinity, "\"Infinity\"")] [InlineData(float.NaN, "\"NaN\"")] [InlineData(float.PositiveInfinity, "\"Infinity\"")] public void SerializeNumber_Test(object o, string expected) { var actual = SerializeObject(o); Assert.Equal(expected, actual); } [Fact] public void SerializeBool_Test() { var actual = SerializeObject(true); Assert.Equal("true", actual); actual = SerializeObject(false); Assert.Equal("false", actual); } [Fact] public void SerializeNumberDecimal_Test() { var actual = SerializeObject(-1M); Assert.Equal("-1.0", actual); actual = SerializeObject(0M); Assert.Equal("0.0", actual); actual = SerializeObject(1M); Assert.Equal("1.0", actual); actual = SerializeObject(2M); Assert.Equal("2.0", actual); actual = SerializeObject(3M); Assert.Equal("3.0", actual); actual = SerializeObject(4M); Assert.Equal("4.0", actual); actual = SerializeObject(5M); Assert.Equal("5.0", actual); actual = SerializeObject(6M); Assert.Equal("6.0", actual); actual = SerializeObject(7M); Assert.Equal("7.0", actual); actual = SerializeObject(8M); Assert.Equal("8.0", actual); actual = SerializeObject(9M); Assert.Equal("9.0", actual); actual = SerializeObject(3.14159265M); Assert.Equal("3.14159265", actual); } [Fact] public void SerializeDateTime_Test() { DateTime utcNow = DateTime.UtcNow; utcNow = utcNow.AddTicks(-utcNow.Ticks % TimeSpan.TicksPerSecond); var actual = SerializeObject(utcNow); Assert.Equal("\"" + utcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture) + "\"", actual); } [Fact] public void SerializeDateTime_Test2() { var culture = System.Threading.Thread.CurrentThread.CurrentCulture; try { System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); // uses "." instead of ":" for time var val = new DateTime(2016, 12, 31); var actual = SerializeObject(val); Assert.Equal("\"" + "2016-12-31T00:00:00Z" + "\"", actual); } finally { // Restore System.Threading.Thread.CurrentThread.CurrentCulture = culture; } } [Fact] public void SerializeDateTimeOffset_Test() { var culture = System.Threading.Thread.CurrentThread.CurrentCulture; try { System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); // uses "." instead of ":" for time var val = new DateTimeOffset(new DateTime(2016, 12, 31, 2, 30, 59), new TimeSpan(4, 30, 0)); var actual = SerializeObject(val); Assert.Equal("\"" + "2016-12-31 02:30:59 +04:30" + "\"", actual); } finally { // Restore System.Threading.Thread.CurrentThread.CurrentCulture = culture; } } [Fact] public void SerializeTime_Test() { var actual = SerializeObject(new TimeSpan(1, 2, 3, 4)); Assert.Equal("\"1.02:03:04\"", actual); } [Fact] public void SerializeTime2_Test() { var actual = SerializeObject(new TimeSpan(0, 2, 3, 4)); Assert.Equal("\"02:03:04\"", actual); } [Fact] public void SerializeTime3_Test() { var culture = System.Threading.Thread.CurrentThread.CurrentCulture; try { System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); // uses "." instead of ":" for time var actual = SerializeObject(new TimeSpan(0, 0, 2, 3, 4)); Assert.Equal("\"00:02:03.0040000\"", actual); } finally { // Restore System.Threading.Thread.CurrentThread.CurrentCulture = culture; } } [Fact] public void SerializeEmptyDict_Test() { var actual = SerializeObject(new Dictionary<string, int>()); Assert.Equal("{}", actual); } [Fact] public void SerializeDict_Test() { var dictionary = new Dictionary<string, object>(); dictionary.Add("key1", 13); dictionary.Add("key 2", 1.3m); var actual = SerializeObject(dictionary); Assert.Equal("{\"key1\":13,\"key 2\":1.3}", actual); } [Fact] public void SerializeCustomNullDict_Test() { var dictionary = new Dictionary<string, object>(); dictionary.Add("key1", 13); dictionary.Add("key 2", new CustomNullProperty()); var actual = SerializeObject(dictionary); Assert.Equal("{\"key1\":13,\"key 2\":null}", actual); } [Fact] public void SerializeTrickyDict_Test() { IDictionary<object,object> dictionary = new Internal.TrickyTestDictionary(); dictionary.Add("key1", 13); dictionary.Add("key 2", 1.3m); var actual = SerializeObject(dictionary); Assert.Equal("{\"key1\":13,\"key 2\":1.3}", actual); } [Fact] public void SerializeExpandoDict_Test() { IDictionary<string, IFormattable> dictionary = new Internal.ExpandoTestDictionary(); dictionary.Add("key 2", 1.3m); dictionary.Add("level", LogLevel.Info); var actual = SerializeObject(dictionary); Assert.Equal("{\"key 2\":1.3, \"level\":\"Info\"}", actual); } [Fact] public void SerializEmptyExpandoDict_Test() { IDictionary<string, IFormattable> dictionary = new Internal.ExpandoTestDictionary(); var actual = SerializeObject(dictionary); Assert.Equal("{}", actual); } #if !NET35 && !NET40 [Fact] public void SerializeReadOnlyExpandoDict_Test() { var dictionary = new Dictionary<string, object>(); dictionary.Add("key 2", 1.3m); dictionary.Add("level", LogLevel.Info); var readonlyDictionary = new Internal.ReadOnlyExpandoTestDictionary(dictionary); var actual = SerializeObject(readonlyDictionary); Assert.Equal("{\"key 2\":1.3, \"level\":\"Info\"}", actual); } #endif [Fact] public void SerializeIntegerKeyDict_Test() { var dictionary = new Dictionary<int, string>(); dictionary.Add(1, "One"); dictionary.Add(2, "Two"); var actual = SerializeObject(dictionary); Assert.Equal("{\"1\":\"One\",\"2\":\"Two\"}", actual); } [Fact] public void SerializeEnumKeyDict_Test() { var dictionary = new Dictionary<ExceptionRenderingFormat, int>(); dictionary.Add(ExceptionRenderingFormat.Method, 4); dictionary.Add(ExceptionRenderingFormat.StackTrace, 5); var actual = SerializeObject(dictionary); Assert.Equal("{\"Method\":4,\"StackTrace\":5}", actual); } [Fact] public void SerializeObjectKeyDict_Test() { var dictionary = new Dictionary<object, string>(); dictionary.Add(new { Name = "Hello" }, "World"); dictionary.Add(new { Name = "Goodbye" }, "Money"); var actual = SerializeObject(dictionary); Assert.Equal("{\"{ Name = Hello }\":\"World\",\"{ Name = Goodbye }\":\"Money\"}", actual); } [Fact] public void SerializeBadStringKeyDict_Test() { var dictionary = new Dictionary<string, string>(); dictionary.Add("\t", "Tab"); dictionary.Add("\n", "Newline"); var actual = SerializeObject(dictionary); Assert.Equal("{\"\\t\":\"Tab\",\"\\n\":\"Newline\"}", actual); } [Fact] public void SerializeNull_Test() { var actual = SerializeObject(null); Assert.Equal("null", actual); } [Fact] public void SerializeGuid_Test() { Guid newGuid = Guid.NewGuid(); var actual = SerializeObject(newGuid); Assert.Equal("\"" + newGuid.ToString() + "\"", actual); } [Fact] public void SerializeEnum_Test() { var val = ExceptionRenderingFormat.Method; var actual = SerializeObject(val); Assert.Equal("\"Method\"", actual); } [Fact] public void SerializeFlagEnum_Test() { var val = UrlHelper.EscapeEncodingOptions.LegacyRfc2396 | UrlHelper.EscapeEncodingOptions.LowerCaseHex; var actual = SerializeObject(val); Assert.Equal("\"LegacyRfc2396, LowerCaseHex\"", actual); } [Fact] public void SerializeObject_Test() { var object1 = new TestObject("object1"); var object2 = new TestObject("object2"); object1.Linked = object2; var actual = SerializeObject(object1); Assert.Equal("{\"Name\":\"object1\", \"Linked\":{\"Name\":\"object2\"}}", actual); } [Fact] public void SerializeRecusiveObject_Test() { var object1 = new TestObject("object1"); object1.Linked = object1; var actual = SerializeObject(object1); Assert.Equal("{\"Name\":\"object1\"}", actual); } [Fact] public void SerializeListObject_Test() { var object1 = new TestObject("object1"); var object2 = new TestObject("object2"); object1.Linked = object2; var list = new[] { object1, object2 }; var actual = SerializeObject(list); Assert.Equal("[{\"Name\":\"object1\", \"Linked\":{\"Name\":\"object2\"}},{\"Name\":\"object2\"}]", actual); } [Fact] public void SerializeNoPropsObject_Test() { var object1 = new NoPropsObject(); var actual = SerializeObject(object1); Assert.Equal("\"something\"", actual); } [Fact] public void SerializeObjectWithExceptionAndPrivateSetter_Test() { var object1 = new ObjectWithExceptionAndPrivateSetter("test name"); var actual = SerializeObject(object1); Assert.Equal("{\"Name\":\"test name\"}", actual); } #if !NET35 && !NET45 [Fact] public void SerializeValueTuple_Test() { // Could perform reflection on fields, but one have to lookup TupleElementNamesAttribute to get names // ValueTuples are for internal usage, better to use AnonymousObject for key/value-pairs var object1 = (Name: "<NAME>", Id: 1); var actual = SerializeObject(object1); Assert.Equal("\"(test name, 1)\"", actual); } #endif [Fact] public void SerializeAnonymousObject_Test() { var object1 = new { Id = 123, Name = "<NAME>" }; var actual = SerializeObject(object1); Assert.Equal("{\"Id\":123, \"Name\":\"<NAME>\"}", actual); } /// <summary> /// Simulate behavior of JProperty("nullValue", null) from Newtonsoft.Json /// </summary> private class CustomNullProperty : IConvertible { TypeCode IConvertible.GetTypeCode() => TypeCode.Empty; bool IConvertible.ToBoolean(IFormatProvider provider) => default(bool); byte IConvertible.ToByte(IFormatProvider provider) => default(byte); char IConvertible.ToChar(IFormatProvider provider) => default(char); DateTime IConvertible.ToDateTime(IFormatProvider provider) => default(DateTime); decimal IConvertible.ToDecimal(IFormatProvider provider) => default(decimal); double IConvertible.ToDouble(IFormatProvider provider) => default(double); short IConvertible.ToInt16(IFormatProvider provider) => default(short); int IConvertible.ToInt32(IFormatProvider provider) => default(int); long IConvertible.ToInt64(IFormatProvider provider) => default(long); sbyte IConvertible.ToSByte(IFormatProvider provider) => default(sbyte); float IConvertible.ToSingle(IFormatProvider provider) => default(float); string IConvertible.ToString(IFormatProvider provider) => default(string); object IConvertible.ToType(Type conversionType, IFormatProvider provider) => default(object); ushort IConvertible.ToUInt16(IFormatProvider provider) => default(ushort); uint IConvertible.ToUInt32(IFormatProvider provider) => default(uint); ulong IConvertible.ToUInt64(IFormatProvider provider) => default(ulong); public override string ToString() => "nullValue"; } #if !NET35 && !NET40 [Fact] public void SerializeExpandoObject_Test() { dynamic object1 = new ExpandoObject(); object1.Id = 123; object1.Name = "<NAME>"; var actual = SerializeObject(object1); Assert.Equal("{\"Id\":123, \"Name\":\"<NAME>\"}", actual); } [Fact] public void SerializeDynamicObject_Test() { var object1 = new MyDynamicClass(); var actual = SerializeObject(object1); Assert.Equal("{\"Id\":123, \"Name\":\"<NAME>\"}", actual); } private class MyDynamicClass : DynamicObject { private int _id = 123; private string _name = "<NAME>"; public override bool TryGetMember(GetMemberBinder binder, out object result) { if (binder.Name == "Id") { result = _id; return true; } if (binder.Name == "Name") { result = _name; return true; } result = null; return false; } public override bool TrySetMember(SetMemberBinder binder, object value) { if (binder.Name == "Id") { _id = (int)value; return true; } if (binder.Name == "Name") { _name = (string)value; return true; } return false; } public override IEnumerable<string> GetDynamicMemberNames() { return new List<string>() { "Id", "Name" }; } } #endif [Fact] public void SingleItemOptimizedHashSetTest() { var hashSet = default(NLog.Internal.SingleItemOptimizedHashSet<object>); Assert.Empty(hashSet); Assert.DoesNotContain(new object(), hashSet); foreach (var obj in hashSet) throw new Exception("Wrong"); hashSet.Clear(); Assert.Empty(hashSet); hashSet.Add(new object()); Assert.Single(hashSet); hashSet.Add(new object()); Assert.Equal(2, hashSet.Count); foreach (var obj in hashSet) Assert.Contains(obj, hashSet); object[] objArray = new object[2]; hashSet.CopyTo(objArray, 0); foreach (var obj in objArray) { Assert.NotNull(obj); hashSet.Remove(obj); } Assert.Empty(hashSet); hashSet.Clear(); Assert.Empty(hashSet); } protected class TestObject { public TestObject(string name) { Name = name; } public string Name { get; set; } public TestObject Linked { get; set; } } protected class NoPropsObject { private readonly string something = "something"; #region Overrides of Object /// <summary>Returns a string that represents the current object.</summary> /// <returns>A string that represents the current object.</returns> public override string ToString() { return something; } #endregion } private class ObjectWithExceptionAndPrivateSetter { public ObjectWithExceptionAndPrivateSetter(string name) { Name = name; } public string Name { get; } public string SetOnly { private get; set; } public object Ex => throw new Exception("oops"); } private class TestList : IEnumerable<IEnumerable> { static List<int> _list1 = new List<int> { 17, 3 }; static List<string> _list2 = new List<string> { "alpha", "bravo" }; public IEnumerator<IEnumerable> GetEnumerator() { yield return _list1; yield return _list2; yield return new TestList(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public override bool Equals(object obj) { throw new Exception("object.Equals should never be called"); } public override int GetHashCode() { throw new Exception("GetHashCode should never be called"); } } } }<file_sep>using NLog; using NLog.Targets; using NLog.Targets.Wrappers; class Example { static void Main(string[] args) { FileTarget target = new FileTarget(); target.Layout = "${longdate} ${logger} ${message}"; target.FileName = "${basedir}/logs/logfile.txt"; target.ArchiveFileName = "${basedir}/archives/log.{#####}.txt"; target.ArchiveAboveSize = 10 * 1024; // archive files greater than 10 KB target.ArchiveNumbering = FileTarget.ArchiveNumberingMode.Sequence; // this speeds up things when no other processes are writing to the file target.ConcurrentWrites = true; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); // generate a large volume of messages for (int i = 0; i < 1000; ++i) { logger.Debug("log message {0}", i); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace System.Diagnostics.CodeAnalysis { [AttributeUsage( AttributeTargets.Field | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct, Inherited = false)] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="DynamicallyAccessedMembersAttribute"/> class /// with the specified member types. /// </summary> /// <param name="memberTypes">The types of members dynamically accessed.</param> public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } /// <summary> /// Gets the <see cref="DynamicallyAccessedMemberTypes"/> which specifies the type /// of members dynamically accessed. /// </summary> public DynamicallyAccessedMemberTypes MemberTypes { get; } } /// <summary> /// Specifies the types of members that are dynamically accessed. /// /// This enumeration has a <see cref="FlagsAttribute"/> attribute that allows a /// bitwise combination of its member values. /// </summary> [Flags] internal enum DynamicallyAccessedMemberTypes { /// <summary> /// Specifies no members. /// </summary> None = 0, /// <summary> /// Specifies the default, parameterless public constructor. /// </summary> PublicParameterlessConstructor = 0x0001, /// <summary> /// Specifies all public constructors. /// </summary> PublicConstructors = 0x0002 | PublicParameterlessConstructor, /// <summary> /// Specifies all non-public constructors. /// </summary> NonPublicConstructors = 0x0004, /// <summary> /// Specifies all public methods. /// </summary> PublicMethods = 0x0008, /// <summary> /// Specifies all non-public methods. /// </summary> NonPublicMethods = 0x0010, /// <summary> /// Specifies all public fields. /// </summary> PublicFields = 0x0020, /// <summary> /// Specifies all non-public fields. /// </summary> NonPublicFields = 0x0040, /// <summary> /// Specifies all public nested types. /// </summary> PublicNestedTypes = 0x0080, /// <summary> /// Specifies all non-public nested types. /// </summary> NonPublicNestedTypes = 0x0100, /// <summary> /// Specifies all public properties. /// </summary> PublicProperties = 0x0200, /// <summary> /// Specifies all non-public properties. /// </summary> NonPublicProperties = 0x0400, /// <summary> /// Specifies all public events. /// </summary> PublicEvents = 0x0800, /// <summary> /// Specifies all non-public events. /// </summary> NonPublicEvents = 0x1000, /// <summary> /// Specifies all interfaces implemented by the type. /// </summary> Interfaces = 0x2000, /// <summary> /// Specifies all members. /// </summary> All = ~None } /// <summary> /// Suppresses reporting of a specific rule violation, allowing multiple suppressions on a /// single code artifact. /// </summary> /// <remarks> /// <see cref="UnconditionalSuppressMessageAttribute"/> is different than /// <see cref="SuppressMessageAttribute"/> in that it doesn't have a /// <see cref="ConditionalAttribute"/>. So it is always preserved in the compiled assembly. /// </remarks> [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] internal sealed class UnconditionalSuppressMessageAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="UnconditionalSuppressMessageAttribute"/> /// class, specifying the category of the tool and the identifier for an analysis rule. /// </summary> /// <param name="category">The category for the attribute.</param> /// <param name="checkId">The identifier of the analysis rule the attribute applies to.</param> public UnconditionalSuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } /// <summary> /// Gets the category identifying the classification of the attribute. /// </summary> /// <remarks> /// The <see cref="Category"/> property describes the tool or tool analysis category /// for which a message suppression attribute applies. /// </remarks> public string Category { get; } /// <summary> /// Gets the identifier of the analysis tool rule to be suppressed. /// </summary> /// <remarks> /// Concatenated together, the <see cref="Category"/> and <see cref="CheckId"/> /// properties form a unique check identifier. /// </remarks> public string CheckId { get; } /// <summary> /// Gets or sets the scope of the code that is relevant for the attribute. /// </summary> /// <remarks> /// The Scope property is an optional argument that specifies the metadata scope for which /// the attribute is relevant. /// </remarks> public string Scope { get; set; } /// <summary> /// Gets or sets a fully qualified path that represents the target of the attribute. /// </summary> /// <remarks> /// The <see cref="Target"/> property is an optional argument identifying the analysis target /// of the attribute. An example value is "System.IO.Stream.ctor():System.Void". /// Because it is fully qualified, it can be long, particularly for targets such as parameters. /// The analysis tool user interface should be capable of automatically formatting the parameter. /// </remarks> public string Target { get; set; } /// <summary> /// Gets or sets an optional argument expanding on exclusion criteria. /// </summary> /// <remarks> /// The <see cref="MessageId "/> property is an optional argument that specifies additional /// exclusion where the literal metadata target is not sufficiently precise. For example, /// the <see cref="UnconditionalSuppressMessageAttribute"/> cannot be applied within a method, /// and it may be desirable to suppress a violation against a statement in the method that will /// give a rule violation, but not against all statements in the method. /// </remarks> public string MessageId { get; set; } /// <summary> /// Gets or sets the justification for suppressing the code analysis message. /// </summary> public string Justification { get; set; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Fluent { using System; using System.Collections.Generic; using System.IO; using NLog.Config; using NLog.Fluent; using NLog.Targets; using Xunit; [Obsolete("Obsoleted since it allocates unnecessary. Instead use ILogger.ForLogEvent and LogEventBuilder. Obsoleted in NLog 5.0")] public class LogBuilderTests : NLogTestBase { private static readonly Logger _logger = LogManager.GetLogger("logger1"); private LogEventInfo _lastLogEventInfo; public LogBuilderTests() { var configuration = new LoggingConfiguration(); var t1 = new MethodCallTarget("t1", (l, parms) => _lastLogEventInfo = l); t1.Parameters.Add(new MethodCallParameter("CallSite", "${callsite}")); var t2 = new DebugTarget { Name = "t2", Layout = "${message}" }; configuration.AddTarget(t1); configuration.AddTarget(t2); configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, t1)); configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, t2)); LogManager.Configuration = configuration; } [Fact] public void TraceWrite() { TraceWrite_internal(() => _logger.Trace()); } #if !NET35 && !NET40 [Fact] public void TraceWrite_static_builder() { TraceWrite_internal(() => Log.Trace(), true); } #endif ///<remarks> /// func because 1 logbuilder creates 1 message /// /// Caution: don't use overloading, that will break xUnit: /// CATASTROPHIC ERROR OCCURRED: /// System.ArgumentException: Ambiguous method named TraceWrite in type NLog.UnitTests.Fluent.LogBuilderTests /// </remarks> private void TraceWrite_internal(Func<LogBuilder> logBuilder, bool isStatic = false) { logBuilder() .Message("This is a test fluent message.") .Property("Test", "TraceWrite") .Write(); var loggerName = isStatic ? "LogBuilderTests" : "logger1"; { var expectedEvent = new LogEventInfo(LogLevel.Trace, loggerName, "This is a test fluent message."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); } var ticks = DateTime.Now.Ticks; logBuilder() .Message("This is a test fluent message '{0}'.", ticks) .Property("Test", "TraceWrite") .Write(); { var rendered = $"This is a test fluent message '{ticks}'."; var expectedEvent = new LogEventInfo(LogLevel.Trace, loggerName, "This is a test fluent message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessage("t2", rendered); } } [Fact] public void TraceWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; _logger.Trace() .Message("This is a test fluent message.") .Properties(props).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } [Fact] public void WarnWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; _logger.Warn() .Message("This is a test fluent message.") .Properties(props).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Warn, "logger1", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } [Fact] public void LogWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; // Loop to verify caller-attribute-caching-lookup for (int i = 0; i < 2; ++i) { _logger.Log(LogLevel.Fatal) .Message("This is a test fluent message.") .Properties(props).Write(); var expectedEvent = new LogEventInfo(LogLevel.Fatal, "logger1", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); #if !NET35 && !NET40 Assert.Equal(GetType().ToString(), _lastLogEventInfo.CallerClassName); #endif } } [Fact] public void LogOffWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; var props2 = new Dictionary<string, object> { {"prop1", "4"}, {"prop2", "5"}, }; _logger.Log(LogLevel.Fatal) .Message("This is a test fluent message.") .Properties(props).Write(); _logger.Log(LogLevel.Off) .Message("dont log this.") .Properties(props2).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Fatal, "logger1", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } #if !NET35 && !NET40 [Fact] public void LevelWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; Log.Level(LogLevel.Fatal) .Message("This is a test fluent message.") .Properties(props).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Fatal, "LogBuilderTests", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } #endif [Fact] public void TraceIfWrite() { _logger.Trace() .Message("This is a test fluent message.1") .Property("Test", "TraceWrite") .Write(); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent message.1"); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); } int v = 1; _logger.Trace() .Message("This is a test fluent WriteIf message '{0}'.", DateTime.Now.Ticks) .Property("Test", "TraceWrite") .WriteIf(() => v == 1); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent WriteIf message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent WriteIf message "); } _logger.Trace() .Message("dont write this! '{0}'.", DateTime.Now.Ticks) .Property("Test", "TraceWrite") .WriteIf(() => { return false; }); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent WriteIf message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent WriteIf message "); } _logger.Trace() .Message("This is a test fluent WriteIf message '{0}'.", DateTime.Now.Ticks) .Property("Test", "TraceWrite") .WriteIf(v == 1); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent WriteIf message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent WriteIf message "); } _logger.Trace() .Message("Should Not WriteIf message '{0}'.", DateTime.Now.Ticks) .Property("Test", "TraceWrite") .WriteIf(v > 1); { //previous var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent WriteIf message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent WriteIf message "); } } [Fact] public void InfoWrite() { InfoWrite_internal(() => _logger.Info()); } #if !NET35 && !NET40 [Fact] public void InfoWrite_static_builder() { InfoWrite_internal(() => Log.Info(), true); } #endif ///<remarks> /// func because 1 logbuilder creates 1 message /// /// Caution: don't use overloading, that will break xUnit: /// CATASTROPHIC ERROR OCCURRED: /// System.ArgumentException: Ambiguous method named TraceWrite in type NLog.UnitTests.Fluent.LogBuilderTests /// </remarks> private void InfoWrite_internal(Func<LogBuilder> logBuilder, bool isStatic = false) { logBuilder() .Message("This is a test fluent message.") .Property("Test", "InfoWrite") .Write(); var loggerName = isStatic ? "LogBuilderTests" : "logger1"; { //previous var expectedEvent = new LogEventInfo(LogLevel.Info, loggerName, "This is a test fluent message."); expectedEvent.Properties["Test"] = "InfoWrite"; AssertLastLogEventTarget(expectedEvent); } logBuilder() .Message("This is a test fluent message '{0}'.", DateTime.Now.Ticks) .Property("Test", "InfoWrite") .Write(); { //previous var expectedEvent = new LogEventInfo(LogLevel.Info, loggerName, "This is a test fluent message '{0}'."); expectedEvent.Properties["Test"] = "InfoWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent message '"); } } [Fact] public void DebugWrite() { ErrorWrite_internal(() => _logger.Debug(), LogLevel.Debug); } #if !NET35 && !NET40 [Fact] public void DebugWrite_static_builder() { ErrorWrite_internal(() => Log.Debug(), LogLevel.Debug, true); } #endif [Fact] public void FatalWrite() { ErrorWrite_internal(() => _logger.Fatal(), LogLevel.Fatal); } #if !NET35 && !NET40 [Fact] public void FatalWrite_static_builder() { ErrorWrite_internal(() => Log.Fatal(), LogLevel.Fatal, true); } #endif [Fact] public void ErrorWrite() { ErrorWrite_internal(() => _logger.Error(), LogLevel.Error); } #if !NET35 && !NET40 [Fact] public void ErrorWrite_static_builder() { ErrorWrite_internal(() => Log.Error(), LogLevel.Error, true); } #endif [Fact] public void LogBuilder_null_lead_to_ArgumentNullException() { var logger = LogManager.GetLogger("a"); Assert.Throws<ArgumentNullException>(() => new LogBuilder(null, LogLevel.Debug)); Assert.Throws<ArgumentNullException>(() => new LogBuilder(null)); Assert.Throws<ArgumentNullException>(() => new LogBuilder(logger, null)); var logBuilder = new LogBuilder(logger); Assert.Throws<ArgumentNullException>(() => logBuilder.Properties(null)); Assert.Throws<ArgumentNullException>(() => logBuilder.Property(null, "b")); } [Fact] public void LogBuilder_nLogEventInfo() { var d = new DateTime(2015, 01, 30, 14, 30, 5); var logEventInfo = new LogBuilder(LogManager.GetLogger("a")).LoggerName("b").Level(LogLevel.Fatal).TimeStamp(d).LogEventInfo; Assert.Equal("b", logEventInfo.LoggerName); Assert.Equal(LogLevel.Fatal, logEventInfo.Level); Assert.Equal(d, logEventInfo.TimeStamp); } [Fact] public void LogBuilder_exception_only() { var ex = new Exception("Exception message1"); _logger.Error() .Exception(ex) .Write(); var expectedEvent = new LogEventInfo(LogLevel.Error, "logger1", null) { Exception = ex }; AssertLastLogEventTarget(expectedEvent); } [Fact] public void LogBuilder_null_logLevel() { Assert.Throws<ArgumentNullException>(() => _logger.Error().Level(null)); } [Fact] public void LogBuilder_message_overloadsTest() { LogManager.ThrowExceptions = true; _logger.Debug() .Message("Message with {0} arg", 1) .Write(); AssertDebugLastMessage("t2", "Message with 1 arg"); _logger.Debug() .Message("Message with {0} args. {1}", 2, "YES") .Write(); AssertDebugLastMessage("t2", "Message with 2 args. YES"); _logger.Debug() .Message("Message with {0} args. {1} {2}", 3, ":) ", 2) .Write(); AssertDebugLastMessage("t2", "Message with 3 args. :) 2"); _logger.Debug() .Message("Message with {0} args. {1} {2}{3}", "more", ":) ", 2, "b") .Write(); AssertDebugLastMessage("t2", "Message with more args. :) 2b"); } [Fact] public void LogBuilder_message_cultureTest() { if (IsLinux()) { Console.WriteLine("[SKIP] LogBuilderTests.LogBuilder_message_cultureTest because we are running in Travis"); return; } LogManager.Configuration.DefaultCultureInfo = GetCultureInfo("en-US"); _logger.Debug() .Message("Message with {0} {1} {2} {3}", 4.1, 4.001, new DateTime(2016, 12, 31), true) .Write(); AssertDebugLastMessage("t2", "Message with 4.1 4.001 12/31/2016 12:00:00 AM True"); _logger.Debug() .Message(GetCultureInfo("nl-nl"), "Message with {0} {1} {2} {3}", 4.1, 4.001, new DateTime(2016, 12, 31), true) .Write(); AssertDebugLastMessage("t2", "Message with 4,1 4,001 31-12-2016 00:00:00 True"); } [Fact] public void LogBuilder_Structured_Logging_Test() { var logEvent = _logger.Info().Property("Property1Key", "Property1Value").Message("{@message}", "My custom message").LogEventInfo; Assert.NotEmpty(logEvent.Properties); Assert.Contains("message", logEvent.Properties.Keys); Assert.Contains("Property1Key", logEvent.Properties.Keys); } ///<remarks> /// func because 1 logbuilder creates 1 message /// /// Caution: don't use overloading, that will break xUnit: /// CATASTROPHIC ERROR OCCURRED: /// System.ArgumentException: Ambiguous method named TraceWrite in type NLog.UnitTests.Fluent.LogBuilderTests /// </remarks> private void ErrorWrite_internal(Func<LogBuilder> logBuilder, LogLevel logLevel, bool isStatic = false) { Exception catchedException = null; string path = "blah.txt"; try { string text = File.ReadAllText(path); } catch (Exception ex) { catchedException = ex; logBuilder() .Message("Error reading file '{0}'.", path) .Exception(ex) .Property("Test", "ErrorWrite") .Write(); } var loggerName = isStatic ? "LogBuilderTests" : "logger1"; { var expectedEvent = new LogEventInfo(logLevel, loggerName, "Error reading file '{0}'."); expectedEvent.Properties["Test"] = "ErrorWrite"; expectedEvent.Exception = catchedException; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "Error reading file '"); } logBuilder() .Message("This is a test fluent message.") .Property("Test", "ErrorWrite") .Write(); { var expectedEvent = new LogEventInfo(logLevel, loggerName, "This is a test fluent message."); expectedEvent.Properties["Test"] = "ErrorWrite"; AssertLastLogEventTarget(expectedEvent); } logBuilder() .Message("This is a test fluent message '{0}'.", DateTime.Now.Ticks) .Property("Test", "ErrorWrite") .Write(); { var expectedEvent = new LogEventInfo(logLevel, loggerName, "This is a test fluent message '{0}'."); expectedEvent.Properties["Test"] = "ErrorWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent message '"); } } /// <summary> /// Test the written logevent /// </summary> /// <param name="expected">exptected event to be logged.</param> void AssertLastLogEventTarget(LogEventInfo expected) { Assert.NotNull(_lastLogEventInfo); Assert.Equal(expected.Message, _lastLogEventInfo.Message); Assert.NotNull(_lastLogEventInfo.Properties); Assert.Equal(expected.Properties, _lastLogEventInfo.Properties); Assert.Equal(expected.LoggerName, _lastLogEventInfo.LoggerName); Assert.Equal(expected.Level, _lastLogEventInfo.Level); Assert.Equal(expected.Exception, _lastLogEventInfo.Exception); Assert.Equal(expected.FormatProvider, _lastLogEventInfo.FormatProvider); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class BufferingTargetWrapperTests : NLogTestBase { [Fact] public void BufferingTargetWrapperSyncTest1() { var myTarget = new MyTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = 10, }; InitializeTargets(myTarget, targetWrapper); const int totalEvents = 100; var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; var hitCount = 0; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); }; // write 9 events - they will all be buffered and no final continuation will be reached var eventCounter = 0; for (var i = 0; i < 9; ++i) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } Assert.Equal(0, hitCount); Assert.Equal(0, myTarget.WriteCount); // write one more event - everything will be flushed targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Assert.Equal(10, hitCount); Assert.Equal(1, myTarget.BufferedWriteCount); Assert.Equal(10, myTarget.BufferedTotalEvents); Assert.Equal(10, myTarget.WriteCount); for (var i = 0; i < hitCount; ++i) { Assert.Same(Thread.CurrentThread, continuationThread[i]); Assert.Null(lastException[i]); } // write 9 more events - they will all be buffered and no final continuation will be reached for (var i = 0; i < 9; ++i) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } // no change Assert.Equal(10, hitCount); Assert.Equal(1, myTarget.BufferedWriteCount); Assert.Equal(10, myTarget.BufferedTotalEvents); Assert.Equal(10, myTarget.WriteCount); Exception flushException = null; var flushHit = new ManualResetEvent(false); targetWrapper.Flush( ex => { flushException = ex; flushHit.Set(); }); Assert.True(flushHit.WaitOne(5000), "Wait Flush Timeout"); Assert.Null(flushException); // make sure remaining events were written Assert.Equal(19, hitCount); Assert.Equal(2, myTarget.BufferedWriteCount); Assert.Equal(19, myTarget.BufferedTotalEvents); Assert.Equal(19, myTarget.WriteCount); Assert.Equal(1, myTarget.FlushCount); // flushes happen on the same thread for (var i = 10; i < hitCount; ++i) { Assert.NotNull(continuationThread[i]); Assert.Same(Thread.CurrentThread, continuationThread[i]); Assert.Null(lastException[i]); } // flush again - should just invoke Flush() on the wrapped target flushHit.Reset(); targetWrapper.Flush( ex => { flushException = ex; flushHit.Set(); }); Assert.True(flushHit.WaitOne(5000), "Wait Again Flush Timeout"); Assert.Equal(19, hitCount); Assert.Equal(2, myTarget.BufferedWriteCount); Assert.Equal(19, myTarget.BufferedTotalEvents); Assert.Equal(19, myTarget.WriteCount); Assert.Equal(2, myTarget.FlushCount); targetWrapper.Close(); myTarget.Close(); } [Theory] [InlineData(false)] [InlineData(true)] public void BufferingTargetWithFallbackGroupAndFirstTargetFails_Write_SecondTargetWritesEvents(bool enableBatchWrite) { const int totalEvents = 10; var myTarget = new MyTarget { FailCounter = totalEvents / 2 }; var myTarget2 = new MyTarget(); var fallbackGroup = new FallbackGroupTarget(myTarget, myTarget2) { EnableBatchWrite = enableBatchWrite }; var targetWrapper = new BufferingTargetWrapper { WrappedTarget = fallbackGroup, BufferSize = totalEvents, }; InitializeTargets(myTarget, targetWrapper, myTarget2, fallbackGroup); var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; }; using (new NoThrowNLogExceptions()) { // write 9 events - they will all be buffered and no final continuation will be reached var eventCounter = 0; for (var i = 0; i < totalEvents - 1; ++i) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } Assert.Equal(0, myTarget.WriteCount); // write one more event - everything will be flushed targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); if (enableBatchWrite) { Assert.Equal(1, myTarget.BufferedWriteCount); Assert.Equal(totalEvents, myTarget.BufferedTotalEvents); Assert.Equal(totalEvents, myTarget.WriteCount); Assert.Equal(totalEvents / 2, myTarget2.WriteCount); } else { Assert.Equal(0, myTarget.BufferedTotalEvents); Assert.Equal(0, myTarget.BufferedWriteCount); Assert.Equal(1, myTarget.WriteCount); Assert.Equal(totalEvents, myTarget2.WriteCount); } targetWrapper.Close(); myTarget.Close(); } } [Fact] public void BufferingTargetWrapperSyncWithTimedFlushTest() { var myTarget = new MyTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = 10, FlushTimeout = 50, }; var writeHit = new ManualResetEvent(false); InitializeTargets(myTarget, targetWrapper); const int totalEvents = 100; var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; var hitCount = 0; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); writeHit.Set(); }; // write 9 events - they will all be buffered and no final continuation will be reached var eventCounter = 0; for (var i = 0; i < 9; ++i) { targetWrapper.WriteAsyncLogEvent( new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } Assert.Equal(0, hitCount); Assert.Equal(0, myTarget.WriteCount); // sleep and wait for the trigger timer to flush all events Assert.True(writeHit.WaitOne(5000), "Wait Write Timeout"); WaitAndAssertExpectedValue(ref hitCount, 9); Assert.Equal(1, myTarget.BufferedWriteCount); Assert.Equal(9, myTarget.BufferedTotalEvents); Assert.Equal(9, myTarget.WriteCount); for (var i = 0; i < hitCount; ++i) { Assert.NotSame(Thread.CurrentThread, continuationThread[i]); Assert.Null(lastException[i]); } // write 11 more events, 10 will be hit immediately because the buffer will fill up // 1 will be pending for (var i = 0; i < 11; ++i) { targetWrapper.WriteAsyncLogEvent( new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } Assert.Equal(19, hitCount); Assert.Equal(2, myTarget.BufferedWriteCount); Assert.Equal(19, myTarget.BufferedTotalEvents); Assert.Equal(19, myTarget.WriteCount); // sleep and wait for the remaining one to be flushed WaitAndAssertExpectedValue(ref hitCount, 20); Assert.Equal(3, myTarget.BufferedWriteCount); Assert.Equal(20, myTarget.BufferedTotalEvents); Assert.Equal(20, myTarget.WriteCount); } [Fact] public void BufferingTargetWrapperAsyncTest1() { RetryingIntegrationTest(3, () => { var myTarget = new MyAsyncTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = 10, }; var writeHit = new ManualResetEvent(false); InitializeTargets(myTarget, targetWrapper); const int totalEvents = 100; var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; var hitCount = 0; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); writeHit.Set(); }; // write 9 events - they will all be buffered and no final continuation will be reached var eventCounter = 0; for (var i = 0; i < 9; ++i) { targetWrapper.WriteAsyncLogEvent( new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } Assert.Equal(0, hitCount); // write one more event - everything will be flushed targetWrapper.WriteAsyncLogEvent( new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Assert.True(writeHit.WaitOne(5000), "Wait Write Timeout"); WaitAndAssertExpectedValue(ref hitCount, 10); Assert.Equal(1, myTarget.BufferedWriteCount); Assert.Equal(10, myTarget.BufferedTotalEvents); for (var i = 0; i < hitCount; ++i) { Assert.NotSame(Thread.CurrentThread, continuationThread[i]); Assert.Null(lastException[i]); } // write 9 more events - they will all be buffered and no final continuation will be reached for (var i = 0; i < 9; ++i) { targetWrapper.WriteAsyncLogEvent( new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } // no change Assert.Equal(10, hitCount); Assert.Equal(1, myTarget.BufferedWriteCount); Assert.Equal(10, myTarget.BufferedTotalEvents); Exception flushException = null; var flushHit = new ManualResetEvent(false); targetWrapper.Flush( ex => { flushException = ex; flushHit.Set(); }); Assert.True(flushHit.WaitOne(5000), "Wait Flush Timeout"); Assert.Null(flushException); // make sure remaining events were written Assert.Equal(19, hitCount); Assert.Equal(2, myTarget.BufferedWriteCount); Assert.Equal(19, myTarget.BufferedTotalEvents); // flushes happen on another thread for (var i = 10; i < hitCount; ++i) { Assert.NotNull(continuationThread[i]); Assert.NotSame(Thread.CurrentThread, continuationThread[i]); Assert.Null(lastException[i]); } // flush again - should not do anything flushHit.Reset(); targetWrapper.Flush( ex => { flushException = ex; flushHit.Set(); }); Assert.True(flushHit.WaitOne(5000), "Wait Again Flush Timeout"); Assert.Equal(19, hitCount); Assert.Equal(2, myTarget.BufferedWriteCount); Assert.Equal(19, myTarget.BufferedTotalEvents); targetWrapper.Close(); myTarget.Close(); }); } [Fact] public void BufferingTargetWrapperSyncWithTimedFlushNonSlidingTest() { RetryingIntegrationTest(3, () => { var myTarget = new MyTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = 10, FlushTimeout = 400, SlidingTimeout = false, }; InitializeTargets(myTarget, targetWrapper); const int totalEvents = 100; var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; var hitCount = 0; var resetEvent = new ManualResetEvent(false); CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); if (eventNumber > 0) { resetEvent.Set(); } }; var eventCounter = 0; targetWrapper.WriteAsyncLogEvent( new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Assert.Equal(0, hitCount); Assert.Equal(0, myTarget.WriteCount); targetWrapper.WriteAsyncLogEvent( new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Assert.True(resetEvent.WaitOne(5000), "Wait Write Timeout"); Assert.Equal(2, hitCount); Assert.Equal(2, myTarget.WriteCount); }); } [Fact] public void BufferingTargetWrapperSyncWithTimedFlushSlidingTest() { var myTarget = new MyTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = 10, FlushTimeout = 400, }; var writeEvent = new ManualResetEvent(false); InitializeTargets(myTarget, targetWrapper); const int totalEvents = 100; var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; var hitCount = 0; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); writeEvent.Set(); }; var eventCounter = 0; targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Thread.Sleep(100); Assert.Equal(0, hitCount); Assert.Equal(0, myTarget.WriteCount); targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Thread.Sleep(100); Assert.Equal(0, hitCount); Assert.Equal(0, myTarget.WriteCount); Assert.True(writeEvent.WaitOne(5000), "Wait Write Timeout"); WaitAndAssertExpectedValue(ref hitCount, 2); Assert.Equal(2, myTarget.WriteCount); } [Fact] public void WhenWrappedTargetThrowsExceptionThisIsHandled() { using (new NoThrowNLogExceptions()) { var myTarget = new MyTarget { ThrowException = true }; var bufferingTargetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, FlushTimeout = -1 }; InitializeTargets(myTarget, bufferingTargetWrapper); bufferingTargetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(_ => { })); var flushHit = new ManualResetEvent(false); bufferingTargetWrapper.Flush(ex => flushHit.Set()); Assert.True(flushHit.WaitOne(5000), "Wait Flush Timeout"); Assert.Equal(1, myTarget.FlushCount); } } [Fact] public void BufferingTargetWrapperSyncWithOverflowDiscardTest() { const int totalEvents = 15; const int bufferSize = 10; var myTarget = new MyTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = bufferSize, OverflowAction = BufferingTargetWrapperOverflowAction.Discard }; InitializeTargets(myTarget, targetWrapper); var continuationHit = new bool[totalEvents]; var hitCount = 0; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); }; Assert.Equal(0, myTarget.WriteCount); for (int i = 0; i < totalEvents; i++) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(i))); } // No events should be written to the wrapped target unless flushing manually. Assert.Equal(0, myTarget.WriteCount); Assert.Equal(0, myTarget.BufferedWriteCount); Assert.Equal(0, myTarget.BufferedTotalEvents); targetWrapper.Flush(e => { }); Assert.Equal(bufferSize, hitCount); Assert.Equal(bufferSize, myTarget.WriteCount); Assert.Equal(1, myTarget.BufferedWriteCount); Assert.Equal(bufferSize, myTarget.BufferedTotalEvents); // Validate that we dropped the oldest events. Assert.False(continuationHit[totalEvents - bufferSize - 1]); Assert.True(continuationHit[totalEvents - bufferSize]); // Make sure the events do not stay in the buffer. targetWrapper.Flush(e => { }); Assert.Equal(bufferSize, hitCount); Assert.Equal(bufferSize, myTarget.WriteCount); Assert.Equal(1, myTarget.BufferedWriteCount); Assert.Equal(bufferSize, myTarget.BufferedTotalEvents); // Make sure that events are discarded when closing target (config-reload + shutdown) targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(totalEvents))); targetWrapper.Close(); Assert.Equal(bufferSize, hitCount); Assert.Equal(bufferSize, myTarget.WriteCount); Assert.Equal(1, myTarget.BufferedWriteCount); Assert.Equal(bufferSize, myTarget.BufferedTotalEvents); } private static void InitializeTargets(params Target[] targets) { foreach (var target in targets) { target.Initialize(null); } } private class MyAsyncTarget : Target { private readonly NLog.Internal.AsyncOperationCounter _pendingWriteCounter = new NLog.Internal.AsyncOperationCounter(); public int BufferedWriteCount { get; private set; } public int BufferedTotalEvents { get; private set; } protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); } protected override void Write(IList<AsyncLogEventInfo> logEvents) { _pendingWriteCounter.BeginOperation(); BufferedWriteCount++; BufferedTotalEvents += logEvents.Count; for (int i = 0; i < logEvents.Count; ++i) { var @event = logEvents[i]; ThreadPool.QueueUserWorkItem( s => { try { if (ThrowExceptions) { @event.Continuation(new ApplicationException("Some problem!")); } else { @event.Continuation(null); } } finally { _pendingWriteCounter.CompleteOperation(null); } }); } } protected override void FlushAsync(AsyncContinuation asyncContinuation) { var wrappedContinuation = _pendingWriteCounter.RegisterCompletionNotification(asyncContinuation); ThreadPool.QueueUserWorkItem( s => { wrappedContinuation(null); }); } public bool ThrowExceptions { get; set; } } private class MyTarget : Target { public int FlushCount { get; private set; } public int WriteCount { get; private set; } public int BufferedWriteCount { get; private set; } public int BufferedTotalEvents { get; private set; } public bool ThrowException { get; set; } public int FailCounter { get; set; } protected override void Write(IList<AsyncLogEventInfo> logEvents) { BufferedWriteCount++; BufferedTotalEvents += logEvents.Count; base.Write(logEvents); } protected override void Write(LogEventInfo logEvent) { Assert.True(FlushCount <= WriteCount); WriteCount++; if (ThrowException) { throw new Exception("Target exception"); } if (FailCounter > 0) { FailCounter--; throw new ApplicationException("Some failure."); } } protected override void FlushAsync(AsyncContinuation asyncContinuation) { FlushCount++; asyncContinuation(null); } } private delegate AsyncContinuation CreateContinuationFunc(int eventNumber); private static void WaitAndAssertExpectedValue(ref int hitCount, int expectedValue) { for (int i = 0; i < 100; ++i) { if (Thread.VolatileRead(ref hitCount) >= expectedValue) break; // Ready to assert Thread.Sleep(50); } Assert.Equal(expectedValue, hitCount); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Globalization; using System.Text; using NLog.Config; using NLog.Internal; /// <summary> /// Current date and time. /// </summary> [LayoutRenderer("date")] [ThreadAgnostic] public class DateLayoutRenderer : LayoutRenderer, IRawValue, IStringValueRenderer { /// <summary> /// Initializes a new instance of the <see cref="DateLayoutRenderer" /> class. /// </summary> public DateLayoutRenderer() { Format = "yyyy/MM/dd HH:mm:ss.fff"; } /// <summary> /// Gets or sets the culture used for rendering. /// </summary> /// <docgen category='Layout Options' order='100' /> public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; /// <summary> /// Gets or sets the date format. Can be any argument accepted by DateTime.ToString(format). /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultParameter] public string Format { get => _format; set { _format = value; // Check if caching should be used _cachedDateFormatted = IsLowTimeResolutionLayout(_format) ? new CachedDateFormatted(DateTime.MaxValue, string.Empty) // Cache can be used, will update cache-value : null; // No cache support } } private string _format; private const string _lowTimeResolutionChars = "YyMDdHh"; private CachedDateFormatted _cachedDateFormatted = null; /// <summary> /// Gets or sets a value indicating whether to output UTC time instead of local time. /// </summary> /// <docgen category='Layout Options' order='50' /> public bool UniversalTime { get => _universalTime ?? false; set => _universalTime = value; } private bool? _universalTime; /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(GetStringValue(logEvent)); } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = GetValue(logEvent); return true; } string IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) => GetStringValue(logEvent); private string GetStringValue(LogEventInfo logEvent) { var formatProvider = GetFormatProvider(logEvent, Culture); DateTime timestamp = GetValue(logEvent); var cachedDateFormatted = _cachedDateFormatted; if (!ReferenceEquals(formatProvider, CultureInfo.InvariantCulture)) { cachedDateFormatted = null; } else { if (cachedDateFormatted != null && cachedDateFormatted.Date == timestamp.Date.AddHours(timestamp.Hour)) { return cachedDateFormatted.FormattedDate; // Cache hit } } string formatTime = timestamp.ToString(_format, formatProvider); if (cachedDateFormatted != null) { _cachedDateFormatted = new CachedDateFormatted(timestamp.Date.AddHours(timestamp.Hour), formatTime); } return formatTime; } private DateTime GetValue(LogEventInfo logEvent) { var timestamp = logEvent.TimeStamp; if (_universalTime.HasValue) { if (_universalTime.Value) timestamp = timestamp.ToUniversalTime(); else timestamp = timestamp.ToLocalTime(); } return timestamp; } private static bool IsLowTimeResolutionLayout(string dateTimeFormat) { for (int i = 0; i < dateTimeFormat.Length; ++i) { char ch = dateTimeFormat[i]; if (char.IsLetter(ch) && _lowTimeResolutionChars.IndexOf(ch) < 0) return false; } return true; } private sealed class CachedDateFormatted { public CachedDateFormatted(DateTime date, string formattedDate) { Date = date; FormattedDate = formattedDate; } public readonly DateTime Date; public readonly string FormattedDate; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal.FileAppenders { using System; using System.IO; using System.Runtime.InteropServices; using System.Security; using NLog.Common; using NLog.Internal; /// <summary> /// Base class for optimized file appenders. /// </summary> [SecuritySafeCritical] internal abstract class BaseFileAppender : IDisposable { #pragma warning disable S2245 // Make sure that using this pseudorandom number generator is safe here (Not security sensitive) private readonly Random _random = new Random(); //NOSONAR #pragma warning restore S2245 // Make sure that using this pseudorandom number generator is safe here /// <summary> /// Initializes a new instance of the <see cref="BaseFileAppender" /> class. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="createParameters">The create parameters.</param> protected BaseFileAppender(string fileName, ICreateFileParameters createParameters) { CreateFileParameters = createParameters; FileName = fileName; OpenTimeUtc = DateTime.UtcNow; // to be consistent with timeToKill in FileTarget.AutoClosingTimerCallback } /// <summary> /// Gets the path of the file, including file extension. /// </summary> /// <value>The name of the file.</value> public string FileName { get; } /// <summary> /// Gets or sets the creation time for a file associated with the appender. The time returned is in Coordinated /// Universal Time [UTC] standard. /// </summary> /// <returns>The creation time of the file.</returns> public DateTime CreationTimeUtc { get => _creationTimeUtc; internal set { _creationTimeUtc = value; CreationTimeSource = Time.TimeSource.Current.FromSystemTime(value); // Performance optimization to skip converting every time } } DateTime _creationTimeUtc; /// <summary> /// Gets or sets the creation time for a file associated with the appender. Synchronized by <see cref="CreationTimeUtc"/> /// The time format is based on <see cref="NLog.Time.TimeSource" /> /// </summary> public DateTime CreationTimeSource { get; private set; } /// <summary> /// Gets the last time the file associated with the appender is opened. The time returned is in Coordinated /// Universal Time [UTC] standard. /// </summary> /// <returns>The time the file was last opened.</returns> public DateTime OpenTimeUtc { get; private set; } /// <summary> /// Gets the file creation parameters. /// </summary> /// <value>The file creation parameters.</value> public ICreateFileParameters CreateFileParameters { get; private set; } /// <summary> /// Writes the specified bytes. /// </summary> /// <param name="bytes">The bytes.</param> public void Write(byte[] bytes) { Write(bytes, 0, bytes.Length); } /// <summary> /// Writes the specified bytes to a file. /// </summary> /// <param name="bytes">The bytes array.</param> /// <param name="offset">The bytes array offset.</param> /// <param name="count">The number of bytes.</param> public abstract void Write(byte[] bytes, int offset, int count); /// <summary> /// Flushes this file-appender instance. /// </summary> public abstract void Flush(); /// <summary> /// Closes this file-appender instance. /// </summary> public abstract void Close(); /// <summary> /// Gets the creation time for a file associated with the appender. The time returned is in Coordinated Universal /// Time [UTC] standard. /// </summary> /// <returns>The file creation time.</returns> public abstract DateTime? GetFileCreationTimeUtc(); /// <summary> /// Gets the length in bytes of the file associated with the appender. /// </summary> /// <returns>A long value representing the length of the file in bytes.</returns> public abstract long? GetFileLength(); /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { Close(); } } /// <summary> /// Creates the file stream. /// </summary> /// <param name="allowFileSharedWriting">If set to <c>true</c> sets the file stream to allow shared writing.</param> /// <param name="overrideBufferSize">If larger than 0 then it will be used instead of the default BufferSize for the FileStream.</param> /// <returns>A <see cref="FileStream"/> object which can be used to write to the file.</returns> protected FileStream CreateFileStream(bool allowFileSharedWriting, int overrideBufferSize = 0) { int currentDelay = CreateFileParameters.FileOpenRetryDelay; InternalLogger.Trace("{0}: Opening {1} with allowFileSharedWriting={2}", CreateFileParameters, FileName, allowFileSharedWriting); for (int i = 0; i <= CreateFileParameters.FileOpenRetryCount; ++i) { try { try { return TryCreateFileStream(allowFileSharedWriting, overrideBufferSize); } catch (DirectoryNotFoundException) { //we don't check the directory on beforehand, as that will really slow down writing. if (!CreateFileParameters.CreateDirs) { throw; } InternalLogger.Debug("{0}: DirectoryNotFoundException - Attempting to create directory for FileName: {1}", CreateFileParameters, FileName); var directoryName = Path.GetDirectoryName(FileName); try { Directory.CreateDirectory(directoryName); } catch (DirectoryNotFoundException) { //if creating a directory failed, don't retry for this message (e.g the FileOpenRetryCount below) throw new NLogRuntimeException($"Could not create directory {directoryName}"); } return TryCreateFileStream(allowFileSharedWriting, overrideBufferSize); } } catch (IOException ex) { if (i + 1 >= CreateFileParameters.FileOpenRetryCount) { throw; // rethrow } int actualDelay = _random.Next(currentDelay); InternalLogger.Warn("{0}: Attempt #{1} to open {2} failed - {3} {4}. Sleeping for {5}ms", CreateFileParameters, i, FileName, ex.GetType(), ex.Message, actualDelay); currentDelay *= 2; AsyncHelpers.WaitForDelay(TimeSpan.FromMilliseconds(actualDelay)); } } throw new InvalidOperationException("Should not be reached."); } #if !MONO && !NETSTANDARD private FileStream WindowsCreateFile(string fileName, bool allowFileSharedWriting, int overrideBufferSize) { int fileShare = Win32FileNativeMethods.FILE_SHARE_READ; if (allowFileSharedWriting) { fileShare |= Win32FileNativeMethods.FILE_SHARE_WRITE; } if (CreateFileParameters.EnableFileDelete && PlatformDetector.CurrentOS != RuntimeOS.Windows) { fileShare |= Win32FileNativeMethods.FILE_SHARE_DELETE; } Microsoft.Win32.SafeHandles.SafeFileHandle handle = null; FileStream fileStream = null; try { handle = Win32FileNativeMethods.CreateFile( fileName, Win32FileNativeMethods.FileAccess.GenericWrite, fileShare, IntPtr.Zero, Win32FileNativeMethods.CreationDisposition.OpenAlways, CreateFileParameters.FileAttributes, IntPtr.Zero); if (handle.IsInvalid) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } fileStream = new FileStream(handle, FileAccess.Write, overrideBufferSize > 0 ? overrideBufferSize : CreateFileParameters.BufferSize); fileStream.Seek(0, SeekOrigin.End); return fileStream; } catch { fileStream?.Dispose(); if ((handle != null) && (!handle.IsClosed)) handle.Close(); throw; } } #endif private FileStream TryCreateFileStream(bool allowFileSharedWriting, int overrideBufferSize) { UpdateCreationTime(); #if !MONO && !NETSTANDARD try { if (!CreateFileParameters.ForceManaged && PlatformDetector.IsWin32 && !PlatformDetector.IsMono) { return WindowsCreateFile(FileName, allowFileSharedWriting, overrideBufferSize); } } catch (SecurityException) { InternalLogger.Debug("{0}: Could not use native Windows create file, falling back to managed filestream: {1}", CreateFileParameters, FileName); } #endif FileShare fileShare = allowFileSharedWriting ? FileShare.ReadWrite : FileShare.Read; if (CreateFileParameters.EnableFileDelete) { fileShare |= FileShare.Delete; } return new FileStream( FileName, FileMode.Append, FileAccess.Write, fileShare, overrideBufferSize > 0 ? overrideBufferSize : CreateFileParameters.BufferSize); } private void UpdateCreationTime() { CreationTimeUtc = DateTime.UtcNow; try { FileInfo fileInfo = new FileInfo(FileName); if (fileInfo.Exists) { CreationTimeUtc = fileInfo.LookupValidFileCreationTimeUtc(); } else { File.Create(FileName).Dispose(); // Set the file's creation time to avoid being thwarted by Windows' Tunneling capabilities (https://support.microsoft.com/en-us/kb/172190). File.SetCreationTimeUtc(FileName, CreationTimeUtc); } } catch (NotSupportedException ex) { InternalLogger.Debug(ex, "{0}: Failed to retrieve FileInfo.CreationTimeUtc from FileName: {1}", CreateFileParameters, FileName); } catch (IOException ex) { InternalLogger.Debug(ex, "{0}: Failed to retrieve FileInfo.CreationTimeUtc from FileName: {1}", CreateFileParameters, FileName); } } protected static void CloseFileSafe(ref FileStream fileStream, string fileName) { if (fileStream is null) { return; } InternalLogger.Trace("FileTarget: Closing '{0}'", fileName); try { fileStream.Close(); } catch (Exception ex) { // Swallow exception as the file-stream now is in final state (broken instead of closed) InternalLogger.Warn(ex, "FileTarget: Failed to close file '{0}'", fileName); AsyncHelpers.WaitForDelay(TimeSpan.FromMilliseconds(1)); // Artificial delay to avoid hammering a bad file location } finally { fileStream = null; } } protected static bool MonitorForEnableFileDeleteEvent(string fileName, ref int lastSimpleMonitorCheckTickCount) { int ticksDelta = Environment.TickCount - lastSimpleMonitorCheckTickCount; if (ticksDelta > 1000 || ticksDelta < -1000) { lastSimpleMonitorCheckTickCount = Environment.TickCount; try { if (!File.Exists(fileName)) { return true; } } catch (Exception ex) { InternalLogger.Error(ex, "FileTarget: Failed to check if File.Exists: '{0}'", fileName); return true; } } return false; } } }<file_sep>using NLog; using NLog.Targets; class Example { static void Main(string[] args) { ChainsawTarget target = new ChainsawTarget(); target.Address = "udp://localhost:4000"; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Trace("log message 1"); logger.Debug("log message 2"); logger.Info("log message 3"); logger.Warn("log message 4"); logger.Error("log message 5"); logger.Fatal("log message 6"); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class PostFilteringTargetWrapperTests : NLogTestBase { [Fact] public void PostFilteringTargetWrapperUsingDefaultFilterTest() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, Rules = { // if we had any warnings, log debug too new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"), // when there is an error, emit everything new FilteringRule { Exists = "level >= LogLevel.Error", Filter = "true", }, }, // by default log info and above DefaultFilter = "level >= LogLevel.Info", }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new [] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), }; wrapper.WriteAsyncLogEvents(events); // make sure all Info events went through Assert.Equal(3, target.Events.Count); Assert.Same(events[1].LogEvent, target.Events[0]); Assert.Same(events[2].LogEvent, target.Events[1]); Assert.Same(events[5].LogEvent, target.Events[2]); Assert.Equal(events.Length, exceptions.Count); } [Fact] public void PostFilteringTargetWrapperUsingDefaultNonFilterTest() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, Rules = { // if we had any warnings, log debug too new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"), // when there is an error, emit everything new FilteringRule("level >= LogLevel.Error", "true"), }, // by default log info and above DefaultFilter = "level >= LogLevel.Info", }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Warn, "Logger1", "Hello").WithContinuation(exceptions.Add), }; string result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace); Assert.True(result.IndexOf("Running on 7 events") != -1); Assert.True(result.IndexOf("Rule matched: (level >= Warn)") != -1); Assert.True(result.IndexOf("Filter to apply: (level >= Debug)") != -1); Assert.True(result.IndexOf("After filtering: 6 events.") != -1); Assert.True(result.IndexOf("Sending to MyTarget") != -1); // make sure all Debug,Info,Warn events went through Assert.Equal(6, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Same(events[3].LogEvent, target.Events[3]); Assert.Same(events[5].LogEvent, target.Events[4]); Assert.Same(events[6].LogEvent, target.Events[5]); Assert.Equal(events.Length, exceptions.Count); } [Fact] public void PostFilteringTargetWrapperUsingDefaultNonFilterTest2() { // in this case both rules would match, but first one is picked var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, Rules = { // when there is an error, emit everything new FilteringRule("level >= LogLevel.Error", "true"), // if we had any warnings, log debug too new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"), }, // by default log info and above DefaultFilter = "level >= LogLevel.Info", }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new [] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add), }; var result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace); Assert.True(result.IndexOf("Running on 7 events") != -1); Assert.True(result.IndexOf("Rule matched: (level >= Error)") != -1); Assert.True(result.IndexOf("Filter to apply: True") != -1); Assert.True(result.IndexOf("After filtering: 7 events.") != -1); Assert.True(result.IndexOf("Sending to MyTarget") != -1); // make sure all events went through Assert.Equal(7, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Same(events[3].LogEvent, target.Events[3]); Assert.Same(events[4].LogEvent, target.Events[4]); Assert.Same(events[5].LogEvent, target.Events[5]); Assert.Same(events[6].LogEvent, target.Events[6]); Assert.Equal(events.Length, exceptions.Count); } [Fact] public void PostFilteringTargetWrapperOnlyDefaultFilter() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, DefaultFilter = "level >= LogLevel.Info", // by default log info and above }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); wrapper.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add)); Assert.Single(target.Events); wrapper.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add)); Assert.Single(target.Events); } [Fact] public void PostFilteringTargetWrapperNoFiltersDefined() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add), }; wrapper.WriteAsyncLogEvents(events); // make sure all events went through Assert.Equal(7, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Same(events[3].LogEvent, target.Events[3]); Assert.Same(events[4].LogEvent, target.Events[4]); Assert.Same(events[5].LogEvent, target.Events[5]); Assert.Same(events[6].LogEvent, target.Events[6]); Assert.Equal(events.Length, exceptions.Count); } public class MyTarget : Target { public MyTarget() { Events = new List<LogEventInfo>(); } public MyTarget(string name) : this() { Name = name; } public List<LogEventInfo> Events { get; set; } protected override void Write(LogEventInfo logEvent) { Events.Add(logEvent); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets { using System; using System.Linq; using NLog.Targets; using Xunit; public class MemoryTargetTests : NLogTestBase { [Fact] public void MemoryTarget_LogLevelTest() { var memoryTarget = new MemoryTarget { Layout = "${level} ${message}" }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(memoryTarget); }).GetCurrentClassLogger(); Assert.Empty(memoryTarget.Logs); logger.Trace("TTT"); logger.Debug("DDD"); logger.Info("III"); logger.Warn("WWW"); logger.Error("EEE"); logger.Fatal("FFF"); logger.Factory.Configuration = null; Assert.True(memoryTarget.Logs.Count == 6); Assert.True(memoryTarget.Logs[0] == "Trace TTT"); Assert.True(memoryTarget.Logs[1] == "Debug DDD"); Assert.True(memoryTarget.Logs[2] == "Info III"); Assert.True(memoryTarget.Logs[3] == "Warn WWW"); Assert.True(memoryTarget.Logs[4] == "Error EEE"); Assert.True(memoryTarget.Logs[5] == "Fatal FFF"); } [Fact] public void MemoryTarget_ReconfigureTest_SameTarget_ExpectLogsEmptied() { var memoryTarget = new MemoryTarget { Layout = "${level} ${message}" }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(memoryTarget); }).GetCurrentClassLogger(); logger.Debug("DDD"); logger.Info("III"); logger.Warn("WWW"); Assert.True(memoryTarget.Logs.Count == 3); Assert.True(memoryTarget.Logs[0] == "Debug DDD"); Assert.True(memoryTarget.Logs[1] == "Info III"); Assert.True(memoryTarget.Logs[2] == "Warn WWW"); logger.Factory.Configuration = null; // Reconfigure the logger to use a new MemoryTarget. memoryTarget = new MemoryTarget { Layout = "${level} ${message}" }; logger.Factory.Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(memoryTarget); }).GetCurrentClassLogger(); logger.Trace("TTT"); logger.Error("EEE"); logger.Fatal("FFF"); Assert.True(memoryTarget.Logs.Count == 3); Assert.True(memoryTarget.Logs[0] == "Trace TTT"); Assert.True(memoryTarget.Logs[1] == "Error EEE"); Assert.True(memoryTarget.Logs[2] == "Fatal FFF"); } [Fact] public void MemoryTarget_ClearLogsTest() { var memoryTarget = new MemoryTarget { Layout = "${level} ${message}" }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(memoryTarget); }).GetCurrentClassLogger(); logger.Warn("WWW"); logger.Error("EEE"); logger.Fatal("FFF"); memoryTarget.Logs.Clear(); logger.Trace("TTT"); logger.Debug("DDD"); logger.Info("III"); logger.Factory.Configuration = null; Assert.True(memoryTarget.Logs.Count == 3); Assert.True(memoryTarget.Logs[0] == "Trace TTT"); Assert.True(memoryTarget.Logs[1] == "Debug DDD"); Assert.True(memoryTarget.Logs[2] == "Info III"); } [Fact] public void MemoryTarget_NullMessageTest() { var memoryTarget = new MemoryTarget { Layout = "${level} ${message}" }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(memoryTarget); }).GetCurrentClassLogger(); string nullMessage = null; logger.Trace("TTT"); logger.Debug((String)null); logger.Info("III"); logger.Warn(nullMessage); logger.Error("EEE"); logger.Factory.Configuration = null; Assert.True(memoryTarget.Logs.Count == 5); Assert.True(memoryTarget.Logs[0] == "Trace TTT"); Assert.True(memoryTarget.Logs[1] == "Debug "); Assert.True(memoryTarget.Logs[2] == "Info III"); Assert.True(memoryTarget.Logs[3] == "Warn "); Assert.True(memoryTarget.Logs[4] == "Error EEE"); } [Fact] public void MemoryTarget_EmptyMessageTest() { var memoryTarget = new MemoryTarget { Layout = "${level} ${message}" }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(memoryTarget); }).GetCurrentClassLogger(); logger.Trace("TTT"); logger.Debug(String.Empty); logger.Info("III"); logger.Warn(""); logger.Error("EEE"); logger.Factory.Configuration = null; Assert.True(memoryTarget.Logs.Count == 5); Assert.True(memoryTarget.Logs[0] == "Trace TTT"); Assert.True(memoryTarget.Logs[1] == "Debug "); Assert.True(memoryTarget.Logs[2] == "Info III"); Assert.True(memoryTarget.Logs[3] == "Warn "); Assert.True(memoryTarget.Logs[4] == "Error EEE"); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading; using NLog.Common; using NLog.Conditions; using NLog.Config; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using NLog.Targets.Wrappers; using NLog.UnitTests.Config; using Xunit; public class TargetTests : NLogTestBase { /// <summary> /// Test the following things: /// - Target has default ctor /// - Target has ctor with name (string) arg. /// - Both ctors are creating the same instances /// </summary> [Fact] public void TargetContructorWithNameTest() { var targetTypes = typeof(Target).Assembly.GetTypes().Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(Target))).ToList(); int neededCheckCount = targetTypes.Count; int checkCount = 0; Target fileTarget = new FileTarget(); Target memoryTarget = new MemoryTarget(); foreach (Type targetType in targetTypes) { string lastPropertyName = null; try { // Check if the Target can be created using a default constructor var name = targetType + "_name"; var isWrapped = targetType.IsSubclassOf(typeof(WrapperTargetBase)); var isCompound = targetType.IsSubclassOf(typeof(CompoundTargetBase)); if (isWrapped) { neededCheckCount++; var args = new List<object> { fileTarget }; //default ctor var defaultConstructedTarget = (WrapperTargetBase)Activator.CreateInstance(targetType); defaultConstructedTarget.Name = name; defaultConstructedTarget.WrappedTarget = fileTarget; //specials cases if (targetType == typeof(FilteringTargetWrapper)) { ConditionLoggerNameExpression cond = null; args.Add(cond); var target = (FilteringTargetWrapper)defaultConstructedTarget; target.Condition = cond; } else if (targetType == typeof(RepeatingTargetWrapper)) { var repeatCount = 5; args.Add(repeatCount); var target = (RepeatingTargetWrapper)defaultConstructedTarget; target.RepeatCount = repeatCount; } else if (targetType == typeof(RetryingTargetWrapper)) { var retryCount = 10; var retryDelayMilliseconds = 100; args.Add(retryCount); args.Add(retryDelayMilliseconds); var target = (RetryingTargetWrapper)defaultConstructedTarget; target.RetryCount = retryCount; target.RetryDelayMilliseconds = retryDelayMilliseconds; } //ctor: target var targetConstructedTarget = (WrapperTargetBase)Activator.CreateInstance(targetType, args.ToArray()); targetConstructedTarget.Name = name; args.Insert(0, name); //ctor: target+name var namedConstructedTarget = (WrapperTargetBase)Activator.CreateInstance(targetType, args.ToArray()); CheckEquals(targetType, targetConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount); CheckEquals(targetType, defaultConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount); } else if (isCompound) { neededCheckCount++; //multiple targets var args = new List<object> { fileTarget, memoryTarget }; //specials cases //default ctor var defaultConstructedTarget = (CompoundTargetBase)Activator.CreateInstance(targetType); defaultConstructedTarget.Name = name; defaultConstructedTarget.Targets.Add(fileTarget); defaultConstructedTarget.Targets.Add(memoryTarget); //ctor: target var targetConstructedTarget = (CompoundTargetBase)Activator.CreateInstance(targetType, args.ToArray()); targetConstructedTarget.Name = name; args.Insert(0, name); //ctor: target+name var namedConstructedTarget = (CompoundTargetBase)Activator.CreateInstance(targetType, args.ToArray()); CheckEquals(targetType, targetConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount); CheckEquals(targetType, defaultConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount); } else { //default ctor var targetConstructedTarget = (Target)Activator.CreateInstance(targetType); targetConstructedTarget.Name = name; // ctor: name var namedConstructedTarget = (Target)Activator.CreateInstance(targetType, name); CheckEquals(targetType, targetConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount); } } catch (Exception ex) { var constructionFailed = true; string failureMessage = $"Error testing constructors for '{targetType}.{lastPropertyName}`\n{ex.ToString()}"; Assert.False(constructionFailed, failureMessage); } } Assert.Equal(neededCheckCount, checkCount); } private static void CheckEquals(Type targetType, Target defaultConstructedTarget, Target namedConstructedTarget, ref string lastPropertyName, ref int @checked) { var checkedAtLeastOneProperty = false; var properties = targetType.GetProperties( System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static); foreach (System.Reflection.PropertyInfo pi in properties) { lastPropertyName = pi.Name; if (pi.CanRead && !pi.Name.Equals("SyncRoot")) { var value1 = pi.GetValue(defaultConstructedTarget, null); var value2 = pi.GetValue(namedConstructedTarget, null); if (value1 != null && value2 != null) { if (value1 is IRenderable) { Assert.Equal((IRenderable)value1, (IRenderable)value2, new RenderableEq()); } else if (value1 is AsyncRequestQueue) { Assert.Equal((AsyncRequestQueue)value1, (AsyncRequestQueue)value2, new AsyncRequestQueueEq()); } else { Assert.Equal(value1, value2); } } else { Assert.Null(value1); Assert.Null(value2); } checkedAtLeastOneProperty = true; } } if (checkedAtLeastOneProperty) { @checked++; } } private class RenderableEq : EqualityComparer<IRenderable> { /// <summary> /// Determines whether the specified objects are equal. /// </summary> /// <returns> /// true if the specified objects are equal; otherwise, false. /// </returns> /// <param name="x">The first object of type <paramref name="T"/> to compare.</param><param name="y">The second object of type <paramref name="T"/> to compare.</param> public override bool Equals(IRenderable x, IRenderable y) { if (x is null) return y is null; var nullEvent = LogEventInfo.CreateNullEvent(); return x.Render(nullEvent) == y.Render(nullEvent); } /// <summary> /// Returns a hash code for the specified object. /// </summary> /// <returns> /// A hash code for the specified object. /// </returns> /// <param name="obj">The <see cref="T:System.Object"/> for which a hash code is to be returned.</param><exception cref="T:System.ArgumentNullException">The type of <paramref name="obj"/> is a reference type and <paramref name="obj"/> is null.</exception> public override int GetHashCode(IRenderable obj) { return obj.ToString().GetHashCode(); } } private class AsyncRequestQueueEq : EqualityComparer<AsyncRequestQueue> { /// <summary> /// Determines whether the specified objects are equal. /// </summary> /// <returns> /// true if the specified objects are equal; otherwise, false. /// </returns> /// <param name="x">The first object of type <paramref name="T"/> to compare.</param><param name="y">The second object of type <paramref name="T"/> to compare.</param> public override bool Equals(AsyncRequestQueue x, AsyncRequestQueue y) { if (x is null) return y is null; return x.RequestLimit == y.RequestLimit && x.OnOverflow == y.OnOverflow; } /// <summary> /// Returns a hash code for the specified object. /// </summary> /// <returns> /// A hash code for the specified object. /// </returns> /// <param name="obj">The <see cref="T:System.Object"/> for which a hash code is to be returned.</param><exception cref="T:System.ArgumentNullException">The type of <paramref name="obj"/> is a reference type and <paramref name="obj"/> is null.</exception> public override int GetHashCode(AsyncRequestQueue obj) { unchecked { return (obj.RequestLimit * 397) ^ (int)obj.OnOverflow; } } } [Fact] public void InitializeTest() { var target = new MyTarget(); target.Initialize(null); // initialize was called once Assert.Equal(1, target.InitializeCount); Assert.Equal(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void WriteAsyncLogEvent_InitializeThrowsException_LogContinuationCalledWithCorrectExceptions() { // Arrange var target = new ThrowingInitializeTarget(true); Exception retrievedException = null; var logevent = LogEventInfo.CreateNullEvent().WithContinuation(ex => { retrievedException = ex; }); LogManager.ThrowExceptions = false; target.Initialize(new LoggingConfiguration()); LogManager.ThrowExceptions = true; // Act target.WriteAsyncLogEvent(logevent); // Assert Assert.NotNull(retrievedException); var runtimeException = Assert.IsType<NLogRuntimeException>(retrievedException); var innerException = Assert.IsType<TestException>(runtimeException.InnerException); Assert.Equal("Initialize says no", innerException.Message); } [Fact] public void Flush_ThrowsException_LogContinuationCalledWithCorrectExceptions() { // Arrange var target = new ThrowingInitializeTarget(false); Exception retrievedException = null; AsyncContinuation asyncContinuation = ex => { retrievedException = ex; }; target.Initialize(new LoggingConfiguration()); LogManager.ThrowExceptions = false; // Act target.Flush(asyncContinuation); // Assert Assert.NotNull(retrievedException); //note: not wrapped in NLogRuntimeException, not sure if by design. Assert.IsType<TestException>(retrievedException); } [Fact] public void WriteAsyncLogEvent_WriteAsyncLogEventThrowsException_LogContinuationCalledWithCorrectExceptions() { // Arrange var target = new ThrowingInitializeTarget(false); Exception retrievedException = null; var logevent = LogEventInfo.CreateNullEvent().WithContinuation(ex => { retrievedException = ex; }); target.Initialize(new LoggingConfiguration()); LogManager.ThrowExceptions = false; // Act target.WriteAsyncLogEvent(logevent); // Assert Assert.NotNull(retrievedException); //note: not wrapped in NLogRuntimeException, not sure if by design. Assert.IsType<TestException>(retrievedException); Assert.Equal("Write oops", retrievedException.Message); } private class ThrowingInitializeTarget : Target { private readonly bool _throwsOnInit; /// <inheritdoc/> public ThrowingInitializeTarget(bool throwsOnInit) { _throwsOnInit = throwsOnInit; } /// <inheritdoc/> protected override void InitializeTarget() { if (_throwsOnInit) throw new TestException("Initialize says no"); } /// <inheritdoc/> protected override void FlushAsync(AsyncContinuation asyncContinuation) { throw new TestException("No flush"); } /// <inheritdoc/> protected override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { throw new TestException("Write oops"); } } private class TestException : Exception { /// <inheritdoc/> public TestException(string message) : base(message) { } } [Fact] public void InitializeFailedTest() { var target = new MyTarget(); target.ThrowOnInitialize = true; LogManager.ThrowExceptions = true; Assert.Throws<InvalidOperationException>(() => target.Initialize(null)); // after exception in Initialize(), the target becomes non-functional and all Write() operations var exceptions = new List<Exception>(); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.Equal(0, target.WriteCount); Assert.Single(exceptions); Assert.NotNull(exceptions[0]); Assert.Equal("Target " + target + " failed to initialize.", exceptions[0].Message); Assert.Equal("Init error.", exceptions[0].InnerException.Message); } [Fact] public void DoubleInitializeTest() { var target = new MyTarget(); target.Initialize(null); target.Initialize(null); // initialize was called once Assert.Equal(1, target.InitializeCount); Assert.Equal(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void DoubleCloseTest() { var target = new MyTarget(); target.Initialize(null); target.Close(); target.Close(); // initialize and close were called once each Assert.Equal(1, target.InitializeCount); Assert.Equal(1, target.CloseCount); Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void CloseWithoutInitializeTest() { var target = new MyTarget(); target.Close(); // nothing was called Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void WriteWithoutInitializeTest() { var target = new MyTarget(); List<Exception> exceptions = new List<Exception>(); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); target.WriteAsyncLogEvents(new[] { LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), }); // write was not called Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); Assert.Equal(4, exceptions.Count); exceptions.ForEach(Assert.Null); } [Fact] public void WriteOnClosedTargetTest() { var target = new MyTarget(); target.Initialize(null); target.Close(); var exceptions = new List<Exception>(); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); target.WriteAsyncLogEvents( LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.Equal(1, target.InitializeCount); Assert.Equal(1, target.CloseCount); // write was not called Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); // but all callbacks were invoked with null values Assert.Equal(4, exceptions.Count); exceptions.ForEach(Assert.Null); } [Fact] public void FlushTest() { var target = new MyTarget(); List<Exception> exceptions = new List<Exception>(); target.Initialize(null); target.Flush(exceptions.Add); // flush was called Assert.Equal(1, target.FlushCount); Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); Assert.Single(exceptions); exceptions.ForEach(Assert.Null); } [Fact] public void FlushWithoutInitializeTest() { var target = new MyTarget(); List<Exception> exceptions = new List<Exception>(); target.Flush(exceptions.Add); Assert.Single(exceptions); exceptions.ForEach(Assert.Null); // flush was not called Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Theory] [InlineData("Trace")] [InlineData("TRACE")] [InlineData("TraceSystem")] [InlineData("TraceSYSTEM")] [InlineData("Trace--SYSTEM")] public void TargetAliasShouldWork(string typeName) { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString($@" <nlog> <targets> <target name='d' type='{typeName}' /> </targets> </nlog>"); var t = c.FindTargetByName<TraceTarget>("d"); Assert.NotNull(t); } [Fact] public void FlushOnClosedTargetTest() { var target = new MyTarget(); target.Initialize(null); target.Close(); Assert.Equal(1, target.InitializeCount); Assert.Equal(1, target.CloseCount); List<Exception> exceptions = new List<Exception>(); target.Flush(exceptions.Add); Assert.Single(exceptions); exceptions.ForEach(Assert.Null); // flush was not called Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void LockingTest() { var target = new MyTarget(); target.Initialize(null); var mre = new ManualResetEvent(false); Exception backgroundThreadException = null; Thread t = new Thread(() => { try { target.BlockingOperation(500); } catch (Exception ex) { backgroundThreadException = ex; } finally { mre.Set(); } }); target.Initialize(null); t.Start(); Thread.Sleep(50); List<Exception> exceptions = new List<Exception>(); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); target.WriteAsyncLogEvents(new[] { LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), }); target.Flush(exceptions.Add); target.Close(); exceptions.ForEach(Assert.Null); mre.WaitOne(); if (backgroundThreadException != null) { Assert.True(false, backgroundThreadException.ToString()); } } [Fact] public void GivenNullEvents_WhenWriteAsyncLogEvents_ThenNoExceptionAreThrown() { var target = new MyTarget(); try { target.WriteAsyncLogEvents(null); } catch (Exception e) { Assert.True(false, "Exception thrown: " + e); } } [Fact] public void WriteFormattedStringEvent_WithNullArgument() { var target = new MyTarget(); var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(target); }).GetLogger(nameof(WriteFormattedStringEvent_WithNullArgument)); string t = null; logger.Info("Testing null:{0}", t); Assert.Equal(1, target.WriteCount); } public class MyTarget : Target { private int inBlockingOperation; public int InitializeCount { get; set; } public int CloseCount { get; set; } public int FlushCount { get; set; } public int WriteCount { get; set; } public int WriteCount2 { get; set; } public bool ThrowOnInitialize { get; set; } public int WriteCount3 { get; set; } public MyTarget() : base() { } public MyTarget(string name) : this() { Name = name; } protected override void InitializeTarget() { if (ThrowOnInitialize) { throw new InvalidOperationException("Init error."); } Assert.Equal(0, inBlockingOperation); InitializeCount++; base.InitializeTarget(); } protected override void CloseTarget() { Assert.Equal(0, inBlockingOperation); CloseCount++; base.CloseTarget(); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { Assert.Equal(0, inBlockingOperation); FlushCount++; base.FlushAsync(asyncContinuation); } protected override void Write(LogEventInfo logEvent) { Assert.Equal(0, inBlockingOperation); WriteCount++; } protected override void Write(AsyncLogEventInfo logEvent) { Assert.Equal(0, inBlockingOperation); WriteCount2++; base.Write(logEvent); } protected override void Write(IList<AsyncLogEventInfo> logEvents) { Assert.Equal(0, inBlockingOperation); WriteCount3++; base.Write(logEvents); } public void BlockingOperation(int millisecondsTimeout) { lock (SyncRoot) { inBlockingOperation++; Thread.Sleep(millisecondsTimeout); inBlockingOperation--; } } } [Fact] public void WrongMyTargetShouldNotThrowExceptionWhenThrowExceptionsIsFalse() { using (new NoThrowNLogExceptions()) { var logFactory = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(new WrongMyTarget()); }).LogFactory; Assert.Single(logFactory.Configuration.AllTargets); logFactory.GetLogger("WrongMyTargetShouldThrowException").Info("Testing"); } } public class WrongMyTarget : Target { public WrongMyTarget() : base() { } public WrongMyTarget(string name) : this() { Name = name; } /// <summary> /// Initializes the target. Can be used by inheriting classes /// to initialize logging. /// </summary> protected override void InitializeTarget() { //base.InitializeTarget() should be called } } [Fact] public void TypedLayoutTargetTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <extensions> <add type='" + typeof(MyTypedLayoutTarget).AssemblyQualifiedName + @"' /> </extensions> <targets> <target type='MyTypedLayoutTarget' name='myTarget' byteProperty='42' int16Property='43' int32Property='44' int64Property='45000000000' stringProperty='foobar' boolProperty='true' doubleProperty='3.14159' floatProperty='3.24159' enumProperty='Value3' flagsEnumProperty='Value1,Value3' encodingProperty='utf-8' cultureProperty='en-US' typeProperty='System.Int32' uriProperty='https://nlog-project.org' lineEndingModeProperty='default' /> </targets> </nlog>"); var nullEvent = LogEventInfo.CreateNullEvent(); var myTarget = c.FindTargetByName("myTarget") as MyTypedLayoutTarget; Assert.NotNull(myTarget); Assert.Equal((byte)42, myTarget.ByteProperty.FixedValue); Assert.Equal((short)43, myTarget.Int16Property.FixedValue); Assert.Equal(44, myTarget.Int32Property.FixedValue); Assert.Equal(45000000000L, myTarget.Int64Property.FixedValue); Assert.Equal("foobar", myTarget.StringProperty.FixedValue); Assert.True(myTarget.BoolProperty.FixedValue); Assert.Equal(3.14159, myTarget.DoubleProperty.FixedValue); Assert.Equal(3.24159f, myTarget.FloatProperty.FixedValue); Assert.Equal(TargetConfigurationTests.MyEnum.Value3, myTarget.EnumProperty.FixedValue); Assert.Equal(TargetConfigurationTests.MyFlagsEnum.Value1 | TargetConfigurationTests.MyFlagsEnum.Value3, myTarget.FlagsEnumProperty.FixedValue); Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty.FixedValue); Assert.Equal("en-US", myTarget.CultureProperty.FixedValue.Name); Assert.Equal(typeof(int), myTarget.TypeProperty.FixedValue); Assert.Equal(new Uri("https://nlog-project.org"), myTarget.UriProperty.FixedValue); Assert.Equal(LineEndingMode.Default, myTarget.LineEndingModeProperty.FixedValue); } [Fact] public void TypedLayoutTargetAsyncTest() { // Arrange LogFactory logFactory = new LogFactory(); LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <extensions> <add type='" + typeof(MyTypedLayoutTarget).AssemblyQualifiedName + @"' /> </extensions> <variable name='value3' value='Value3' /> <targets async='true'> <target type='MyTypedLayoutTarget' name='myTarget' byteProperty='42' int16Property='43' int32Property='${threadid}' int64Property='${sequenceid}' stringProperty='${appdomain:format=\{1\}}' boolProperty='true' doubleProperty='3.14159' floatProperty='3.24159' enumProperty='${var:value3}' flagsEnumProperty='Value1,Value3' encodingProperty='utf-8' cultureProperty='en-US' typeProperty='System.Int32' uriProperty='https://nlog-project.org' lineEndingModeProperty='default' /> </targets> <rules> <logger minlevel='trace' writeTo='myTarget' /> </rules> </nlog>", logFactory); logFactory.Configuration = c; // Act var logger = logFactory.GetLogger(nameof(TypedLayoutTargetAsyncTest)); var logEvent = new LogEventInfo(LogLevel.Info, null, "Hello"); logger.Log(logEvent); logFactory.Flush(); // Assert Assert.Equal((byte)42, logEvent.Properties["ByteProperty"]); Assert.Equal((short)43, logEvent.Properties["Int16Property"]); Assert.Equal(Thread.CurrentThread.ManagedThreadId, logEvent.Properties["Int32Property"]); Assert.Equal((long)logEvent.SequenceID, logEvent.Properties["Int64Property"]); Assert.Equal(AppDomain.CurrentDomain.FriendlyName, logEvent.Properties["StringProperty"]); Assert.Equal(true, logEvent.Properties["BoolProperty"]); Assert.Equal(3.14159, logEvent.Properties["DoubleProperty"]); Assert.Equal(3.24159f, logEvent.Properties["FloatProperty"]); Assert.Equal(TargetConfigurationTests.MyEnum.Value3, logEvent.Properties["EnumProperty"]); Assert.Equal(TargetConfigurationTests.MyFlagsEnum.Value1 | TargetConfigurationTests.MyFlagsEnum.Value3, logEvent.Properties["FlagsEnumProperty"]); Assert.Equal(Encoding.UTF8, logEvent.Properties["EncodingProperty"]); Assert.Equal(CultureInfo.GetCultureInfo("en-US"), logEvent.Properties["CultureProperty"]); Assert.Equal(typeof(int), logEvent.Properties["TypeProperty"]); Assert.Equal(new Uri("https://nlog-project.org"), logEvent.Properties["UriProperty"]); Assert.Equal(LineEndingMode.Default, logEvent.Properties["LineEndingModeProperty"]); } [Fact] public void Target_LayoutWithLock_Test() { int checkThreadSafe = 1; var logFactory = new LogFactory().Setup() .SetupExtensions(ext => ext.RegisterLayoutRenderer("naked-runner", (evt) => { var orgValue = System.Threading.Interlocked.Exchange(ref checkThreadSafe, 0); if (orgValue == 0) throw new InvalidOperationException("Running naked in the woods"); System.Threading.Thread.Sleep(10); System.Threading.Interlocked.Exchange(ref checkThreadSafe, orgValue); return "Running safely"; })) .LoadConfigurationFromXml(@"<nlog throwExceptions='true'> <targets async='true'> <target name='debug1' type='Memory' layoutWithLock='true' layout='${logger}|${message}|${naked-runner}' /> </targets> <rules> <logger name='*' minLevel='Debug' writeTo='debug1' /> </rules> </nlog>").LogFactory; // Act int expectedLogCount = 100; var manualEvent = new System.Threading.ManualResetEvent(false); Action<Logger> runnerMethod = (logger) => { manualEvent.WaitOne(); for (int i = 0; i < expectedLogCount / 2; ++i) logger.Info("Test {0}", i); }; var logger1 = logFactory.GetLogger("d1"); var thread1 = new System.Threading.Thread((s) => runnerMethod((Logger)s)) { Name = logger1.Name, IsBackground = true }; thread1.Start(logger1); var logger2 = logFactory.GetLogger("d2"); var thread2 = new System.Threading.Thread((s) => runnerMethod((Logger)s)) { Name = logger2.Name, IsBackground = true }; thread2.Start(logger2); manualEvent.Set(); thread1.Join(); thread2.Join(); logFactory.Flush(); // Assert Assert.Equal(expectedLogCount, logFactory.Configuration.AllTargets.OfType<MemoryTarget>().Sum(m => m.Logs.Count)); } [Fact] public void LogEvent_OutOfMemoryException_EarlyAbort() { using (new NoThrowNLogExceptions()) { var logFactory = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(new NoMemoryTarget() { Name = "LowMem" }).WithBuffering(bufferSize: 3); }).LogFactory; var logger = logFactory.GetCurrentClassLogger(); var target = logFactory.Configuration.FindTargetByName<NoMemoryTarget>("LowMem"); logger.Info("Testing1"); logger.Info("Testing2"); #if DEBUG Assert.Throws<OutOfMemoryException>(() => logger.Info("Testing3")); #else logger.Info("Testing3"); // Flushes and writes #endif Assert.Equal(1, target.FailedCount); } } [Fact] public void LogEvent_OutOfMemoryException_AsyncNotCrash() { using (new NoThrowNLogExceptions()) { var logFactory = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(new NoMemoryTarget() { Name = "LowMem" }).WithAsync(); }).LogFactory; var logger = logFactory.GetCurrentClassLogger(); var target = logFactory.Configuration.FindTargetByName<NoMemoryTarget>("LowMem"); logger.Info("Testing1"); logFactory.Flush(); Assert.Equal(1, target.FailedCount); logger.Info("Testing2"); for (int i = 0; i < 5000; ++i) { if (target.WriteCount != 1) break; Thread.Sleep(1); } Assert.Equal(2, target.FailedCount); target.LowMemory = false; logger.Info("Testing3"); for (int i = 0; i < 5000; ++i) { if (target.WriteCount != 2) break; Thread.Sleep(1); } Assert.Equal(2, target.FailedCount); Assert.Equal(3, target.WriteCount); } } [Target("MyTypedLayoutTarget")] public class MyTypedLayoutTarget : Target { public Layout<byte> ByteProperty { get; set; } public Layout<short> Int16Property { get; set; } public Layout<int> Int32Property { get; set; } public Layout<long> Int64Property { get; set; } public Layout<string> StringProperty { get; set; } public Layout<bool> BoolProperty { get; set; } public Layout<double> DoubleProperty { get; set; } public Layout<float> FloatProperty { get; set; } public Layout<TargetConfigurationTests.MyEnum> EnumProperty { get; set; } public Layout<TargetConfigurationTests.MyFlagsEnum> FlagsEnumProperty { get; set; } public Layout<Encoding> EncodingProperty { get; set; } public Layout<CultureInfo> CultureProperty { get; set; } public Layout<Type> TypeProperty { get; set; } public Layout<Uri> UriProperty { get; set; } public Layout<LineEndingMode> LineEndingModeProperty { get; set; } protected override void Write(LogEventInfo logEvent) { logEvent.Properties[nameof(ByteProperty)] = RenderLogEvent(ByteProperty, logEvent); logEvent.Properties[nameof(Int16Property)] = RenderLogEvent(Int16Property, logEvent); logEvent.Properties[nameof(Int32Property)] = RenderLogEvent(Int32Property, logEvent); logEvent.Properties[nameof(Int64Property)] = RenderLogEvent(Int64Property, logEvent); logEvent.Properties[nameof(StringProperty)] = RenderLogEvent(StringProperty, logEvent); logEvent.Properties[nameof(BoolProperty)] = RenderLogEvent(BoolProperty, logEvent); logEvent.Properties[nameof(DoubleProperty)] = RenderLogEvent(DoubleProperty, logEvent); logEvent.Properties[nameof(FloatProperty)] = RenderLogEvent(FloatProperty, logEvent); logEvent.Properties[nameof(EnumProperty)] = RenderLogEvent(EnumProperty, logEvent); logEvent.Properties[nameof(FlagsEnumProperty)] = RenderLogEvent(FlagsEnumProperty, logEvent); logEvent.Properties[nameof(EncodingProperty)] = RenderLogEvent(EncodingProperty, logEvent); logEvent.Properties[nameof(CultureProperty)] = RenderLogEvent(CultureProperty, logEvent); logEvent.Properties[nameof(TypeProperty)] = RenderLogEvent(TypeProperty, logEvent); logEvent.Properties[nameof(UriProperty)] = RenderLogEvent(UriProperty, logEvent); logEvent.Properties[nameof(LineEndingModeProperty)] = RenderLogEvent(LineEndingModeProperty, logEvent); } } [Target("NoMemoryTarget")] public class NoMemoryTarget : Target { public int FailedCount { get; set; } public int WriteCount { get; set; } public bool LowMemory { get; set; } = true; protected override void Write(LogEventInfo logEvent) { ++WriteCount; if (LowMemory) { ++FailedCount; throw new OutOfMemoryException("LogEvent is too big"); } } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Linq; using NLog.Config; using NLog.Internal; using NLog.Targets; using Xunit; namespace NLog.UnitTests.Config { public class ConfigApiTests { [Fact] public void AddTarget_testname() { var config = new LoggingConfiguration(); config.AddTarget("name1", new FileTarget { Name = "File" }); var allTargets = config.AllTargets; Assert.NotNull(allTargets); Assert.Single(allTargets); //maybe confusing, but the name of the target is not changed, only the one of the key. Assert.Equal("File", allTargets.First().Name); Assert.NotNull(config.FindTargetByName<FileTarget>("name1")); config.RemoveTarget("name1"); allTargets = config.AllTargets; Assert.Empty(allTargets); } [Fact] public void AddTarget_WithName_NullNameParam() { var config = new LoggingConfiguration(); var ex = Assert.Throws<ArgumentNullException>(() => config.AddTarget(name: null, target: new FileTarget { Name = "name1" })); Assert.Equal("name", ex.ParamName); } [Fact] public void AddTarget_WithName_EmptyNameParam() { var config = new LoggingConfiguration(); var ex = Assert.Throws<ArgumentException>(() => config.AddTarget(name: "", target: new FileTarget { Name = "name1" })); Assert.Equal("name", ex.ParamName); } [Fact] public void AddTarget_WithName_NullTargetParam() { var config = new LoggingConfiguration(); var ex = Assert.Throws<ArgumentNullException>(() => config.AddTarget(name: "Name1", target: null)); Assert.Equal("target", ex.ParamName); } [Fact] public void AddTarget_TargetOnly_NullParam() { var config = new LoggingConfiguration(); var ex = Assert.Throws<ArgumentNullException>(() => config.AddTarget(target: null)); Assert.Equal("target", ex.ParamName); } [Fact] public void AddTarget_TargetOnly_EmptyName() { var config = new LoggingConfiguration(); var ex = Assert.Throws<ArgumentException>(() => config.AddTarget(target: new FileTarget { Name = "" })); Assert.Equal("target", ex.ParamName); } [Fact] public void AddTarget_testname_param() { var config = new LoggingConfiguration(); config.AddTarget("name1", new FileTarget { Name = "name2" }); var allTargets = config.AllTargets; Assert.NotNull(allTargets); Assert.Single(allTargets); //maybe confusing, but the name of the target is not changed, only the one of the key. Assert.Equal("name2", allTargets.First().Name); Assert.NotNull(config.FindTargetByName<FileTarget>("name1")); } [Fact] public void AddTarget_testname_fromtarget() { var config = new LoggingConfiguration(); config.AddTarget(new FileTarget { Name = "name2" }); var allTargets = config.AllTargets; Assert.NotNull(allTargets); Assert.Single(allTargets); Assert.Equal("name2", allTargets.First().Name); Assert.NotNull(config.FindTargetByName<FileTarget>("name2")); } [Fact] public void AddRule_min_max() { var config = new LoggingConfiguration(); config.AddTarget(new FileTarget { Name = "File" }); config.AddRule(LogLevel.Info, LogLevel.Error, "File", "*a"); Assert.NotNull(config.LoggingRules); Assert.Equal(1, config.LoggingRules.Count); var rule1 = config.LoggingRules.FirstOrDefault(); Assert.NotNull(rule1); Assert.False(rule1.Final); Assert.Equal("*a", rule1.LoggerNamePattern); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Fatal)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Error)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Warn)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Info)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Debug)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Trace)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Off)); } [Fact] public void AddRule_ruleobject() { var config = new LoggingConfiguration(); config.AddTarget(new FileTarget { Name = "File" }); LoggingRule rule = new LoggingRule("testRule") { LoggerNamePattern = "testRulePattern" }; rule.EnableLoggingForLevels(LogLevel.Info, LogLevel.Error); rule.Targets.Add(config.FindTargetByName("File")); rule.Final = true; config.AddRule(rule); Assert.NotNull(config.LoggingRules); Assert.Equal(1, config.LoggingRules.Count); var lastRule = config.LoggingRules.LastOrDefault(); Assert.Same(rule, lastRule); } [Fact] public void AddRule_all() { var config = new LoggingConfiguration(); config.AddTarget(new FileTarget { Name = "File" }); config.AddRuleForAllLevels("File", "*a"); Assert.NotNull(config.LoggingRules); Assert.Equal(1, config.LoggingRules.Count); var rule1 = config.LoggingRules.FirstOrDefault(); Assert.NotNull(rule1); Assert.False(rule1.Final); Assert.Equal("*a", rule1.LoggerNamePattern); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Fatal)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Error)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Warn)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Info)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Debug)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Trace)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Off)); } [Fact] public void AddRule_onelevel() { var config = new LoggingConfiguration(); config.AddTarget(new FileTarget { Name = "File" }); config.AddRuleForOneLevel(LogLevel.Error, "File", "*a"); Assert.NotNull(config.LoggingRules); Assert.Equal(1, config.LoggingRules.Count); var rule1 = config.LoggingRules.FirstOrDefault(); Assert.NotNull(rule1); Assert.False(rule1.Final); Assert.Equal("*a", rule1.LoggerNamePattern); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Fatal)); Assert.True(rule1.IsLoggingEnabledForLevel(LogLevel.Error)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Warn)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Info)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Debug)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Trace)); Assert.False(rule1.IsLoggingEnabledForLevel(LogLevel.Off)); } [Fact] public void AddRule_with_target() { var config = new LoggingConfiguration(); var fileTarget = new FileTarget { Name = "File" }; config.AddRuleForOneLevel(LogLevel.Error, fileTarget, "*a"); Assert.NotNull(config.LoggingRules); Assert.Equal(1, config.LoggingRules.Count); config.AddTarget(new FileTarget { Name = "File" }); var allTargets = config.AllTargets; Assert.NotNull(allTargets); Assert.Single(allTargets); Assert.Equal("File", allTargets.First().Name); Assert.NotNull(config.FindTargetByName<FileTarget>("File")); } [Fact] public void AddRule_missingtarget() { var config = new LoggingConfiguration(); Assert.Throws<NLogConfigurationException>(() => config.AddRuleForOneLevel(LogLevel.Error, "File", "*a")); } [Fact] public void CheckAllTargets() { var config = new LoggingConfiguration(); var fileTarget = new FileTarget { Name = "File", FileName = "file" }; config.AddRuleForOneLevel(LogLevel.Error, fileTarget, "*a"); config.AddTarget(fileTarget); Assert.Single(config.AllTargets); Assert.Equal(fileTarget, config.AllTargets[0]); config.InitializeAll(); Assert.Single(config.AllTargets); Assert.Equal(fileTarget, config.AllTargets[0]); } [Fact] public void LogRuleToStringTest_min() { var target = new FileTarget { Name = "file1" }; var loggingRule = new LoggingRule("*", LogLevel.Error, target); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (:All) levels: [ Error Fatal ] writeTo: [ file1 ]", s); } [Fact] public void LogRuleToStringTest_minAndMax() { var target = new FileTarget { Name = "file1" }; var loggingRule = new LoggingRule("*", LogLevel.Debug, LogLevel.Error, target); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (:All) levels: [ Debug Info Warn Error ] writeTo: [ file1 ]", s); } [Fact] public void LogRuleToStringTest_none() { var target = new FileTarget { Name = "file1" }; var loggingRule = new LoggingRule("*", target); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (:All) levels: [ ] writeTo: [ file1 ]", s); } [Fact] public void LogRuleToStringTest_empty() { var target = new FileTarget { Name = "file1" }; var loggingRule = new LoggingRule("", target); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (:Equals) levels: [ ] writeTo: [ file1 ]", s); } [Fact] public void LogRuleToStringTest_filter() { var target = new FileTarget { Name = "file1" }; var loggingRule = new LoggingRule("namespace.comp1", target); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (namespace.comp1:Equals) levels: [ ] writeTo: [ file1 ]", s); } [Fact] public void LogRuleToStringTest_multiple_targets() { var target = new FileTarget { Name = "file1" }; var target2 = new FileTarget { Name = "file2" }; var loggingRule = new LoggingRule("namespace.comp1", target); loggingRule.Targets.Add(target2); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (namespace.comp1:Equals) levels: [ ] writeTo: [ file1 file2 ]", s); } [Fact] public void LogRuleSetLoggingLevels_enables() { var rule = new LoggingRule(); rule.SetLoggingLevels(LogLevel.Warn, LogLevel.Fatal); Assert.Equal(rule.Levels, new[] { LogLevel.Warn, LogLevel.Error, LogLevel.Fatal }); } [Fact] public void LogRuleSetLoggingLevels_disables() { var rule = new LoggingRule(); rule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); rule.SetLoggingLevels(LogLevel.Warn, LogLevel.Fatal); Assert.Equal(rule.Levels, new[] { LogLevel.Warn, LogLevel.Error, LogLevel.Fatal }); } [Fact] public void LogRuleSetLoggingLevels_off() { var rule = new LoggingRule(); rule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); rule.SetLoggingLevels(LogLevel.Off, LogLevel.Off); Assert.Equal(rule.Levels, ArrayHelper.Empty<LogLevel>()); } [Fact] public void LogRuleDisableLoggingLevels() { var rule = new LoggingRule(); rule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); rule.DisableLoggingForLevels(LogLevel.Warn, LogLevel.Fatal); Assert.Equal(rule.Levels, new[] { LogLevel.Trace, LogLevel.Debug, LogLevel.Info }); } [Fact] public void ConfigLogRuleWithName() { var config = new LoggingConfiguration(); var rule = new LoggingRule("hello"); config.LoggingRules.Add(rule); var ruleLookup = config.FindRuleByName("hello"); Assert.Same(rule, ruleLookup); Assert.True(config.RemoveRuleByName("hello")); ruleLookup = config.FindRuleByName("hello"); Assert.Null(ruleLookup); Assert.False(config.RemoveRuleByName("hello")); } [Fact] public void FindRuleByName_AfterRename_FindNewOneAndDontFindOld() { // Arrange var config = new LoggingConfiguration(); var rule = new LoggingRule("hello"); config.LoggingRules.Add(rule); // Act var foundRule1 = config.FindRuleByName("hello"); foundRule1.RuleName = "world"; var foundRule2 = config.FindRuleByName("hello"); var foundRule3 = config.FindRuleByName("world"); // Assert Assert.Null(foundRule2); Assert.NotNull(foundRule1); Assert.Same(foundRule1, foundRule3); } [Fact] public void LoggerNameMatcher_None() { var matcher = LoggerNameMatcher.Create(null); Assert.Equal("logNamePattern: (:None)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_All() { var matcher = LoggerNameMatcher.Create("*"); Assert.Equal("logNamePattern: (:All)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_Empty() { var matcher = LoggerNameMatcher.Create(""); Assert.Equal("logNamePattern: (:Equals)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_Equals() { var matcher = LoggerNameMatcher.Create("abc"); Assert.Equal("logNamePattern: (abc:Equals)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_StartsWith() { var matcher = LoggerNameMatcher.Create("abc*"); Assert.Equal("logNamePattern: (abc:StartsWith)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_EndsWith() { var matcher = LoggerNameMatcher.Create("*abc"); Assert.Equal("logNamePattern: (abc:EndsWith)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_Contains() { var matcher = LoggerNameMatcher.Create("*abc*"); Assert.Equal("logNamePattern: (abc:Contains)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_MultiplePattern_StarInternal() { var matcher = LoggerNameMatcher.Create("a*bc"); Assert.Equal("logNamePattern: (^a.*bc$:MultiplePattern)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_MultiplePattern_QuestionMark() { var matcher = LoggerNameMatcher.Create("a?bc"); Assert.Equal("logNamePattern: (^a.bc$:MultiplePattern)", matcher.ToString()); } [Fact] public void LoggerNameMatcher_MultiplePattern_EscapedChars() { var matcher = LoggerNameMatcher.Create("a?b.c.foo.bar"); Assert.Equal("logNamePattern: (^a.b\\.c\\.foo\\.bar$:MultiplePattern)", matcher.ToString()); } [Theory] [InlineData(null, false)] [InlineData("", false)] [InlineData("foobar", false)] public void LoggerNameMatcher_Matches_None(string name, bool result) { LoggerNameMatcher_Matches("None", null, name, result); } [Theory] [InlineData(null, false)] [InlineData("", false)] [InlineData("foobar", false)] [InlineData("A", false)] [InlineData("a", true)] public void LoggerNameMatcher_Matches_Equals(string name, bool result) { LoggerNameMatcher_Matches("Equals", "a", name, result); } [Theory] [InlineData(null, false)] [InlineData("", false)] [InlineData("Foo", false)] [InlineData("Foobar", false)] [InlineData("foo", true)] [InlineData("foobar", true)] public void LoggerNameMatcher_Matches_StartsWith(string name, bool result) { LoggerNameMatcher_Matches("StartsWith", "foo*", name, result); } [Theory] [InlineData(null, false)] [InlineData("", false)] [InlineData("Bar", false)] [InlineData("fooBar", false)] [InlineData("bar", true)] [InlineData("foobar", true)] public void LoggerNameMatcher_Matches_EndsWith(string name, bool result) { LoggerNameMatcher_Matches("EndsWith", "*bar", name, result); } [Theory] [InlineData(null, false)] [InlineData("", false)] [InlineData("Bar", false)] [InlineData("fooBar", false)] [InlineData("Barbaz", false)] [InlineData("fooBarbaz", false)] [InlineData("bar", true)] [InlineData("foobar", true)] [InlineData("barbaz", true)] [InlineData("foobarbaz", true)] public void LoggerNameMatcher_Matches_Contains(string name, bool result) { LoggerNameMatcher_Matches("Contains", "*bar*", name, result); } [Theory] [InlineData(null, false)] [InlineData("", false)] [InlineData("Server[123].connection[2].reader", false)] [InlineData("server[123].connection[2].reader", true)] [InlineData("server[123].connection[2].", true)] [InlineData("server[123].connection[2]", false)] [InlineData("server[123].connection[25].reader", false)] [InlineData("server[].connection[2].reader", true)] public void LoggerNameMatcher_Matches_MultiplePattern(string name, bool result) { LoggerNameMatcher_Matches("MultiplePattern", "server[*].connection[?].*", name, result); } [Theory] [InlineData("MultiplePattern", "server[*].connection[??].*", "server[].connection[2].reader", false)] [InlineData("MultiplePattern", "server[*].connection[??].*", "server[].connection[25].reader", true)] [InlineData("MultiplePattern", "server[*].connection[??].*", "server[].connection[254].reader", false)] public void LoggerNameMatcher_Matches(string matcherType, string pattern, string name, bool result) { var matcher = LoggerNameMatcher.Create(pattern); Assert.Contains(":" + matcherType, matcher.ToString()); Assert.Equal(result, matcher.NameMatches(name)); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Conditions { using System; using System.Globalization; using System.Collections.Generic; using NLog.Common; /// <summary> /// Condition relational (<b>==</b>, <b>!=</b>, <b>&lt;</b>, <b>&lt;=</b>, /// <b>&gt;</b> or <b>&gt;=</b>) expression. /// </summary> internal sealed class ConditionRelationalExpression : ConditionExpression { /// <summary> /// Initializes a new instance of the <see cref="ConditionRelationalExpression" /> class. /// </summary> /// <param name="leftExpression">The left expression.</param> /// <param name="rightExpression">The right expression.</param> /// <param name="relationalOperator">The relational operator.</param> public ConditionRelationalExpression(ConditionExpression leftExpression, ConditionExpression rightExpression, ConditionRelationalOperator relationalOperator) { LeftExpression = leftExpression; RightExpression = rightExpression; RelationalOperator = relationalOperator; } /// <summary> /// Gets the left expression. /// </summary> /// <value>The left expression.</value> public ConditionExpression LeftExpression { get; } /// <summary> /// Gets the right expression. /// </summary> /// <value>The right expression.</value> public ConditionExpression RightExpression { get; } /// <summary> /// Gets the relational operator. /// </summary> /// <value>The operator.</value> public ConditionRelationalOperator RelationalOperator { get; } /// <inheritdoc/> public override string ToString() { return $"({LeftExpression} {GetOperatorString()} {RightExpression})"; } /// <inheritdoc/> protected override object EvaluateNode(LogEventInfo context) { object v1 = LeftExpression.Evaluate(context); object v2 = RightExpression.Evaluate(context); return Compare(v1, v2, RelationalOperator) ? BoxedTrue : BoxedFalse; } /// <summary> /// Compares the specified values using specified relational operator. /// </summary> /// <param name="leftValue">The first value.</param> /// <param name="rightValue">The second value.</param> /// <param name="relationalOperator">The relational operator.</param> /// <returns>Result of the given relational operator.</returns> private static bool Compare(object leftValue, object rightValue, ConditionRelationalOperator relationalOperator) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 System.Collections.IComparer comparer = StringComparer.InvariantCulture; #else System.Collections.IComparer comparer = StringComparer.Ordinal; #endif PromoteTypes(ref leftValue, ref rightValue); switch (relationalOperator) { case ConditionRelationalOperator.Equal: return comparer.Compare(leftValue, rightValue) == 0; case ConditionRelationalOperator.NotEqual: return comparer.Compare(leftValue, rightValue) != 0; case ConditionRelationalOperator.Greater: return comparer.Compare(leftValue, rightValue) > 0; case ConditionRelationalOperator.GreaterOrEqual: return comparer.Compare(leftValue, rightValue) >= 0; case ConditionRelationalOperator.LessOrEqual: return comparer.Compare(leftValue, rightValue) <= 0; case ConditionRelationalOperator.Less: return comparer.Compare(leftValue, rightValue) < 0; default: throw new NotSupportedException($"Relational operator {relationalOperator} is not supported."); } } /// <summary> /// Promote values to the type needed for the comparison, e.g. parse a string to int. /// </summary> /// <param name="leftValue"></param> /// <param name="rightValue"></param> private static void PromoteTypes(ref object leftValue, ref object rightValue) { if (ReferenceEquals(leftValue, rightValue) || leftValue is null || rightValue is null) { return; } var leftType = leftValue.GetType(); var rightType = rightValue.GetType(); if (leftType == rightType) { return; } //types are not equal var leftTypeOrder = GetOrder(leftType); var rightTypeOrder = GetOrder(rightType); if (leftTypeOrder < rightTypeOrder) { // first try promote right value with left type if (TryPromoteTypes(ref rightValue, leftType, ref leftValue, rightType)) return; } else { // otherwise try promote leftValue with right type if (TryPromoteTypes(ref leftValue, rightType, ref rightValue, leftType)) return; } throw new ConditionEvaluationException($"Cannot find common type for '{leftType.Name}' and '{rightType.Name}'."); } /// <summary> /// Promotes <paramref name="val"/> to type /// </summary> /// <param name="val"></param> /// <param name="type1"></param> /// <returns>success?</returns> private static bool TryPromoteType(ref object val, Type type1) { try { if (type1 == typeof(DateTime)) { val = Convert.ToDateTime(val, CultureInfo.InvariantCulture); return true; } if (type1 == typeof(double)) { val = Convert.ToDouble(val, CultureInfo.InvariantCulture); return true; } if (type1 == typeof(float)) { val = Convert.ToSingle(val, CultureInfo.InvariantCulture); return true; } if (type1 == typeof(decimal)) { val = Convert.ToDecimal(val, CultureInfo.InvariantCulture); return true; } if (type1 == typeof(long)) { val = Convert.ToInt64(val, CultureInfo.InvariantCulture); return true; } if (type1 == typeof(int)) { val = Convert.ToInt32(val, CultureInfo.InvariantCulture); return true; } if (type1 == typeof(bool)) { val = Convert.ToBoolean(val, CultureInfo.InvariantCulture); return true; } if (type1 == typeof(LogLevel)) { string strval = Convert.ToString(val, CultureInfo.InvariantCulture); val = LogLevel.FromString(strval); return true; } if (type1 == typeof(string)) { val = Convert.ToString(val, CultureInfo.InvariantCulture); InternalLogger.Trace("Using string comparison"); return true; } } catch (Exception ex) { InternalLogger.Debug("conversion of {0} to {1} failed - {2}", val, type1.Name, ex.Message); } return false; } /// <summary> /// Try to promote both values. First try to promote <paramref name="val1"/> to <paramref name="type1"/>, /// when failed, try <paramref name="val2"/> to <paramref name="type2"/>. /// </summary> /// <returns></returns> private static bool TryPromoteTypes(ref object val1, Type type1, ref object val2, Type type2) { return TryPromoteType(ref val1, type1) || TryPromoteType(ref val2, type2); } /// <summary> /// Get the order for the type for comparison. /// </summary> /// <param name="type1"></param> /// <returns>index, 0 to max int. Lower is first</returns> private static int GetOrder(Type type1) { int order; var success = TypePromoteOrder.TryGetValue(type1, out order); if (success) { return order; } //not found, try as last return int.MaxValue; } /// <summary> /// Dictionary from type to index. Lower index should be tested first. /// </summary> private static Dictionary<Type, int> TypePromoteOrder = BuildTypeOrderDictionary(); /// <summary> /// Build the dictionary needed for the order of the types. /// </summary> /// <returns></returns> private static Dictionary<Type, int> BuildTypeOrderDictionary() { var list = new List<Type> { typeof(DateTime), typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(bool), typeof(LogLevel), typeof(string), }; var dict = new Dictionary<Type, int>(list.Count); for (int i = 0; i < list.Count; i++) { dict.Add(list[i], i); } return dict; } /// <summary> /// Get the string representing the current <see cref="ConditionRelationalOperator"/> /// </summary> /// <returns></returns> private string GetOperatorString() { switch (RelationalOperator) { case ConditionRelationalOperator.Equal: return "=="; case ConditionRelationalOperator.NotEqual: return "!="; case ConditionRelationalOperator.Greater: return ">"; case ConditionRelationalOperator.Less: return "<"; case ConditionRelationalOperator.GreaterOrEqual: return ">="; case ConditionRelationalOperator.LessOrEqual: return "<="; default: throw new NotSupportedException($"Relational operator {RelationalOperator} is not supported."); } } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if NET35 || NET40 || NET45 namespace NLog.Internal { using System; using System.Runtime.Serialization; using NLog.Common; [Serializable] internal class ObjectHandleSerializer : ISerializable { [NonSerialized] private readonly object _wrapped; public ObjectHandleSerializer() { } public ObjectHandleSerializer(object wrapped) { _wrapped = wrapped; } protected ObjectHandleSerializer(SerializationInfo info, StreamingContext context) { Type type = null; try { type = (Type)info.GetValue("wrappedtype", typeof(Type)); _wrapped = info.GetValue("wrappedvalue", type); } catch (Exception ex) { _wrapped = string.Empty; // Type cannot be resolved in this AppDomain InternalLogger.Debug(ex, "ObjectHandleSerializer failed to deserialize object: {0}", type); } } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, SerializationFormatter = true)] public void GetObjectData(SerializationInfo info, StreamingContext context) { try { if (_wrapped is ISerializable || _wrapped?.GetType()?.IsSerializable == true) { info.AddValue("wrappedtype", _wrapped.GetType()); info.AddValue("wrappedvalue", _wrapped); } else { info.AddValue("wrappedtype", typeof(string)); string serializedString = string.Empty; try { serializedString = _wrapped?.ToString(); } finally { info.AddValue("wrappedvalue", serializedString ?? string.Empty); } } } catch (Exception ex) { // ToString on random object can throw exception InternalLogger.Debug(ex, "ObjectHandleSerializer failed to serialize object: {0}", _wrapped?.GetType()); } } public object Unwrap() { return _wrapped ?? string.Empty; } } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Globalization; using System.IO; using NLog.Common; namespace NLog.Targets.FileArchiveModes { /// <summary> /// Archives the log-files using a date and sequence style numbering. Archives will be stamped /// with the prior period (Year, Month, Day) datetime. The most recent archive has the highest number (in /// combination with the date). /// /// When the number of archive files exceed <see cref="FileTarget.MaxArchiveFiles"/> the obsolete archives are deleted. /// When the age of archive files exceed <see cref="FileTarget.MaxArchiveDays"/> the obsolete archives are deleted. /// </summary> internal sealed class FileArchiveModeDateAndSequence : FileArchiveModeBase { private readonly string _archiveDateFormat; public FileArchiveModeDateAndSequence(string archiveDateFormat, bool archiveCleanupEnabled) :base(archiveCleanupEnabled) { _archiveDateFormat = archiveDateFormat; } public override bool AttemptCleanupOnInitializeFile(string archiveFilePath, int maxArchiveFiles, int maxArchiveDays) { return false; // For historic reasons, then cleanup of sequence archives are not done on startup } protected override DateAndSequenceArchive GenerateArchiveFileInfo(FileInfo archiveFile, FileNameTemplate fileTemplate) { //Get the archive file name or empty string if it's null string archiveFileNameWithoutPath = Path.GetFileName(archiveFile.FullName) ?? string.Empty; if (!TryParseDateAndSequence(archiveFileNameWithoutPath, _archiveDateFormat, fileTemplate, out var date, out var sequence)) { return null; } date = DateTime.SpecifyKind(date, NLog.Time.TimeSource.Current.Time.Kind); return new DateAndSequenceArchive(archiveFile.FullName, date, _archiveDateFormat, sequence); } public override DateAndSequenceArchive GenerateArchiveFileName(string archiveFilePath, DateTime archiveDate, List<DateAndSequenceArchive> existingArchiveFiles) { int nextSequenceNumber = 0; FileNameTemplate archiveFileNameTemplate = GenerateFileNameTemplate(archiveFilePath); foreach (var existingFile in existingArchiveFiles) if (existingFile.HasSameFormattedDate(archiveDate)) nextSequenceNumber = Math.Max(nextSequenceNumber, existingFile.Sequence + 1); int minSequenceLength = archiveFileNameTemplate.EndAt - archiveFileNameTemplate.BeginAt - 2; string paddedSequence = nextSequenceNumber.ToString().PadLeft(minSequenceLength, '0'); string archiveFileNameWithoutPath = archiveFileNameTemplate.ReplacePattern("*").Replace("*", $"{archiveDate.ToString(_archiveDateFormat)}.{paddedSequence}"); string dirName = Path.GetDirectoryName(archiveFilePath); archiveFilePath = Path.Combine(dirName, archiveFileNameWithoutPath); archiveFilePath = Path.GetFullPath(archiveFilePath); // Rebuild to fix non-standard path-format return new DateAndSequenceArchive(archiveFilePath, archiveDate, _archiveDateFormat, nextSequenceNumber); } /// <summary> /// Parse filename with date and sequence pattern /// </summary> /// <param name="archiveFileNameWithoutPath"></param> /// <param name="dateFormat">dateformat for archive</param> /// <param name="fileTemplate"></param> /// <param name="date">the found pattern. When failed, then default</param> /// <param name="sequence">the found pattern. When failed, then default</param> /// <returns></returns> private static bool TryParseDateAndSequence(string archiveFileNameWithoutPath, string dateFormat, FileNameTemplate fileTemplate, out DateTime date, out int sequence) { int trailerLength = fileTemplate.Template.Length - fileTemplate.EndAt; int dateAndSequenceIndex = fileTemplate.BeginAt; int dateAndSequenceLength = archiveFileNameWithoutPath.Length - trailerLength - dateAndSequenceIndex; if (dateAndSequenceLength < 0) { date = default(DateTime); sequence = 0; return false; } string dateAndSequence = archiveFileNameWithoutPath.Substring(dateAndSequenceIndex, dateAndSequenceLength); int sequenceIndex = dateAndSequence.LastIndexOf('.') + 1; string sequencePart = dateAndSequence.Substring(sequenceIndex); if (!int.TryParse(sequencePart, NumberStyles.None, CultureInfo.CurrentCulture, out sequence)) { date = default(DateTime); return false; } var dateAndSequenceLength2 = dateAndSequence.Length - sequencePart.Length - 1; if (dateAndSequenceLength2 < 0) { date = default(DateTime); return false; } string datePart = dateAndSequence.Substring(0, dateAndSequenceLength2); if (!DateTime.TryParseExact(datePart, dateFormat, CultureInfo.CurrentCulture, DateTimeStyles.None, out date)) { return false; } InternalLogger.Trace("FileTarget: parsed date '{0}' from file-template '{1}'", datePart, fileTemplate.Template); return true; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Conditions { /// <summary> /// Condition <b>and</b> expression. /// </summary> internal sealed class ConditionAndExpression : ConditionExpression { /// <summary> /// Initializes a new instance of the <see cref="ConditionAndExpression" /> class. /// </summary> /// <param name="left">Left hand side of the AND expression.</param> /// <param name="right">Right hand side of the AND expression.</param> public ConditionAndExpression(ConditionExpression left, ConditionExpression right) { Left = left; Right = right; } /// <summary> /// Gets the left hand side of the AND expression. /// </summary> public ConditionExpression Left { get; } /// <summary> /// Gets the right hand side of the AND expression. /// </summary> public ConditionExpression Right { get; } /// <summary> /// Returns a string representation of this expression. /// </summary> /// <returns>A concatenated '(Left) and (Right)' string.</returns> public override string ToString() { return $"({Left} and {Right})"; } /// <summary> /// Evaluates the expression by evaluating <see cref="Left"/> and <see cref="Right"/> recursively. /// </summary> /// <param name="context">Evaluation context.</param> /// <returns>The value of the conjunction operator.</returns> protected override object EvaluateNode(LogEventInfo context) { var bval1 = (bool)Left.Evaluate(context); if (!bval1) { return BoxedFalse; } var bval2 = (bool)Right.Evaluate(context); if (!bval2) { return BoxedFalse; } return BoxedTrue; } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using NLog.Common; using NLog.Internal; [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] internal class AssemblyExtensionLoader : IAssemblyExtensionLoader { [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming - Allow extension loading from config", "IL2072")] public void LoadTypeFromName(ConfigurationItemFactory factory, string typeName, string itemNamePrefix) { var configType = PropertyTypeConverter.ConvertToType(typeName, true); factory.RegisterType(configType, itemNamePrefix); } public void LoadAssemblyFromName(ConfigurationItemFactory factory, string assemblyName, string itemNamePrefix) { if (SkipAlreadyLoadedAssembly(factory, assemblyName, itemNamePrefix)) { InternalLogger.Debug("Skipped already loaded assembly name: {0}", assemblyName); return; } InternalLogger.Info("Loading assembly name: {0}{1}", assemblyName, string.IsNullOrEmpty(itemNamePrefix) ? "" : $" (Prefix={itemNamePrefix})"); Assembly extensionAssembly = LoadAssemblyFromName(assemblyName); InternalLogger.LogAssemblyVersion(extensionAssembly); factory.RegisterItemsFromAssembly(extensionAssembly, itemNamePrefix); InternalLogger.Debug("Loading assembly name: {0} succeeded!", assemblyName); } private static bool SkipAlreadyLoadedAssembly(ConfigurationItemFactory factory, string assemblyName, string itemNamePrefix) { try { var loadedAssemblies = ResolveLoadedAssemblyTypes(factory); if (loadedAssemblies.Count > 1) { foreach (var assembly in loadedAssemblies) { if (string.Equals(assembly.Key.GetName()?.Name, assemblyName, StringComparison.OrdinalIgnoreCase)) { if (IsNLogItemTypeAlreadyRegistered(factory, assembly.Value, itemNamePrefix)) { return true; } } } } } catch (Exception ex) { if (ex.MustBeRethrown()) throw; InternalLogger.Warn(ex, "Failed checking loading assembly name: {0}", assemblyName); } return false; } private static Dictionary<Assembly, Type> ResolveLoadedAssemblyTypes(ConfigurationItemFactory factory) { var loadedAssemblies = new Dictionary<Assembly, Type>(); foreach (var itemType in factory.ItemTypes) { var assembly = itemType.GetAssembly(); if (assembly is null) continue; if (loadedAssemblies.TryGetValue(assembly, out var firstItemType)) { if (firstItemType is null && IsNLogConfigurationItemType(itemType)) { loadedAssemblies[assembly] = itemType; } } else { loadedAssemblies.Add(assembly, IsNLogConfigurationItemType(itemType) ? itemType : null); } } return loadedAssemblies; } private static bool IsNLogConfigurationItemType(Type itemType) { if (itemType is null) { return false; } else if (typeof(Layouts.Layout).IsAssignableFrom(itemType)) { var nameAttribute = itemType.GetFirstCustomAttribute<Layouts.LayoutAttribute>(); return !string.IsNullOrEmpty(nameAttribute?.Name); } else if (typeof(LayoutRenderers.LayoutRenderer).IsAssignableFrom(itemType)) { var nameAttribute = itemType.GetFirstCustomAttribute<LayoutRenderers.LayoutRendererAttribute>(); return !string.IsNullOrEmpty(nameAttribute?.Name); } else if (typeof(Targets.Target).IsAssignableFrom(itemType)) { var nameAttribute = itemType.GetFirstCustomAttribute<Targets.TargetAttribute>(); return !string.IsNullOrEmpty(nameAttribute?.Name); } else if (typeof(NLog.Filters.Filter).IsAssignableFrom(itemType)) { var nameAttribute = itemType.GetFirstCustomAttribute<Filters.FilterAttribute>(); return !string.IsNullOrEmpty(nameAttribute?.Name); } else { return false; } } private static bool IsNLogItemTypeAlreadyRegistered(ConfigurationItemFactory factory, Type itemType, string itemNamePrefix) { if (itemType is null) { return false; } else if (IsNLogItemTypeAlreadyRegistered<IFactory<Layouts.Layout>, Layouts.Layout, Layouts.LayoutAttribute>(factory.LayoutFactory, itemType, itemNamePrefix)) { return true; } else if (IsNLogItemTypeAlreadyRegistered<IFactory<LayoutRenderers.LayoutRenderer>, LayoutRenderers.LayoutRenderer, LayoutRenderers.LayoutRendererAttribute>(factory.LayoutRendererFactory, itemType, itemNamePrefix)) { return true; } else if (IsNLogItemTypeAlreadyRegistered<IFactory<Targets.Target>, Targets.Target, Targets.TargetAttribute>(factory.TargetFactory, itemType, itemNamePrefix)) { return true; } else if (IsNLogItemTypeAlreadyRegistered<IFactory<Filters.Filter>, Filters.Filter, Filters.FilterAttribute>(factory.FilterFactory, itemType, itemNamePrefix)) { return true; } return false; } private static bool IsNLogItemTypeAlreadyRegistered<TFactory, TBaseType, TAttribute>(TFactory factory, Type itemType, string itemNamePrefix) where TAttribute : NameBaseAttribute where TFactory : IFactory<TBaseType> where TBaseType : class { if (typeof(TBaseType).IsAssignableFrom(itemType)) { var nameAttribute = itemType.GetFirstCustomAttribute<TAttribute>(); if (!string.IsNullOrEmpty(nameAttribute?.Name)) { var typeAlias = string.IsNullOrEmpty(itemNamePrefix) ? nameAttribute.Name : itemNamePrefix + nameAttribute.Name; return factory.TryCreateInstance(typeAlias, out var _); } } return false; } public void LoadAssemblyFromPath(ConfigurationItemFactory factory, string assemblyFileName, string baseDirectory, string itemNamePrefix) { RegisterAssemblyFromPath(factory, assemblyFileName, baseDirectory, itemNamePrefix); } private static Assembly RegisterAssemblyFromPath(ConfigurationItemFactory factory, string assemblyFileName, string baseDirectory = null, string itemNamePrefix = null) { InternalLogger.Info("Loading assembly file: {0}{1}", assemblyFileName, string.IsNullOrEmpty(itemNamePrefix) ? "" : $" (Prefix={itemNamePrefix})"); var extensionAssembly = LoadAssemblyFromPath(assemblyFileName, baseDirectory); if (extensionAssembly is null) return null; InternalLogger.LogAssemblyVersion(extensionAssembly); factory.RegisterItemsFromAssembly(extensionAssembly, itemNamePrefix); InternalLogger.Debug("Loading assembly file: {0} succeeded!", assemblyFileName); return extensionAssembly; } public void ScanForAutoLoadExtensions(ConfigurationItemFactory factory) { #if !NETSTANDARD1_3 try { var nlogAssembly = typeof(LogFactory).GetAssembly(); var assemblyLocation = string.Empty; var extensionDlls = ArrayHelper.Empty<string>(); var fileLocations = GetAutoLoadingFileLocations(); foreach (var fileLocation in fileLocations) { if (string.IsNullOrEmpty(fileLocation.Key)) continue; if (string.IsNullOrEmpty(assemblyLocation)) assemblyLocation = fileLocation.Key; extensionDlls = GetNLogExtensionFiles(fileLocation.Key); if (extensionDlls.Length > 0) { assemblyLocation = fileLocation.Key; break; } } InternalLogger.Debug("Start auto loading, location: {0}", assemblyLocation); var alreadyRegistered = LoadNLogExtensionAssemblies(factory, nlogAssembly, extensionDlls); RegisterAppDomainAssemblies(factory, nlogAssembly, alreadyRegistered); } catch (System.Security.SecurityException ex) { InternalLogger.Warn(ex, "Seems that we do not have permission"); if (ex.MustBeRethrown()) { throw; } } catch (UnauthorizedAccessException ex) { InternalLogger.Warn(ex, "Seems that we do not have permission"); if (ex.MustBeRethrown()) { throw; } } InternalLogger.Debug("Auto loading done"); #else // Nothing to do for Sonar Cube #endif } #if !NETSTANDARD1_3 private static HashSet<string> LoadNLogExtensionAssemblies(ConfigurationItemFactory factory, Assembly nlogAssembly, string[] extensionDlls) { HashSet<string> alreadyRegistered = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { nlogAssembly.FullName }; foreach (var extensionDll in extensionDlls) { try { var extensionAssembly = RegisterAssemblyFromPath(factory, extensionDll); if (extensionAssembly != null) alreadyRegistered.Add(extensionAssembly.FullName); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Warn(ex, "Auto loading assembly file: {0} failed! Skipping this file.", extensionDll); if (ex.MustBeRethrown()) { throw; } } } return alreadyRegistered; } private static void RegisterAppDomainAssemblies(ConfigurationItemFactory factory, Assembly nlogAssembly, HashSet<string> alreadyRegistered) { alreadyRegistered.Add(nlogAssembly.FullName); #if !NETSTANDARD1_5 var allAssemblies = LogFactory.DefaultAppEnvironment.GetAppDomainRuntimeAssemblies(); #else var allAssemblies = new [] { nlogAssembly }; #endif foreach (var assembly in allAssemblies) { if (assembly.FullName.StartsWith("NLog.", StringComparison.OrdinalIgnoreCase) && !alreadyRegistered.Contains(assembly.FullName)) { factory.RegisterItemsFromAssembly(assembly); } if (IncludeAsHiddenAssembly(assembly.FullName)) { LogManager.AddHiddenAssembly(assembly); } } } private static bool IncludeAsHiddenAssembly(string assemblyFullName) { if (assemblyFullName.StartsWith("NLog.Extensions.Logging,", StringComparison.OrdinalIgnoreCase)) return true; if (assemblyFullName.StartsWith("NLog.Web,", StringComparison.OrdinalIgnoreCase)) return true; if (assemblyFullName.StartsWith("NLog.Web.AspNetCore,", StringComparison.OrdinalIgnoreCase)) return true; if (assemblyFullName.StartsWith("Microsoft.Extensions.Logging,", StringComparison.OrdinalIgnoreCase)) return true; if (assemblyFullName.StartsWith("Microsoft.Extensions.Logging.Abstractions,", StringComparison.OrdinalIgnoreCase)) return true; if (assemblyFullName.StartsWith("Microsoft.Extensions.Logging.Filter,", StringComparison.OrdinalIgnoreCase)) return true; if (assemblyFullName.StartsWith("Microsoft.Logging,", StringComparison.OrdinalIgnoreCase)) return true; return false; } internal static IEnumerable<KeyValuePair<string, string>> GetAutoLoadingFileLocations() { var nlogAssembly = typeof(LogFactory).GetAssembly(); var nlogAssemblyLocation = PathHelpers.TrimDirectorySeparators(AssemblyHelpers.GetAssemblyFileLocation(nlogAssembly)); InternalLogger.Debug("Auto loading based on NLog-Assembly found location: {0}", nlogAssemblyLocation); if (!string.IsNullOrEmpty(nlogAssemblyLocation)) yield return new KeyValuePair<string, string>(nlogAssemblyLocation, nameof(nlogAssemblyLocation)); var entryAssemblyLocation = PathHelpers.TrimDirectorySeparators(LogFactory.DefaultAppEnvironment.EntryAssemblyLocation); InternalLogger.Debug("Auto loading based on GetEntryAssembly-Assembly found location: {0}", entryAssemblyLocation); if (!string.IsNullOrEmpty(entryAssemblyLocation) && !string.Equals(entryAssemblyLocation, nlogAssemblyLocation, StringComparison.OrdinalIgnoreCase)) yield return new KeyValuePair<string, string>(entryAssemblyLocation, nameof(entryAssemblyLocation)); var baseDirectory = PathHelpers.TrimDirectorySeparators(LogFactory.DefaultAppEnvironment.AppDomainBaseDirectory); InternalLogger.Debug("Auto loading based on AppDomain-BaseDirectory found location: {0}", baseDirectory); if (!string.IsNullOrEmpty(baseDirectory) && !string.Equals(baseDirectory, nlogAssemblyLocation, StringComparison.OrdinalIgnoreCase)) yield return new KeyValuePair<string, string>(baseDirectory, nameof(baseDirectory)); } private static string[] GetNLogExtensionFiles(string assemblyLocation) { try { InternalLogger.Debug("Search for auto loading files in location: {0}", assemblyLocation); if (string.IsNullOrEmpty(assemblyLocation)) { return ArrayHelper.Empty<string>(); } var extensionDlls = System.IO.Directory.GetFiles(assemblyLocation, "NLog*.dll") .Select(System.IO.Path.GetFileName) .Where(x => !x.Equals("NLog.dll", StringComparison.OrdinalIgnoreCase)) .Where(x => !x.Equals("NLog.UnitTests.dll", StringComparison.OrdinalIgnoreCase)) .Select(x => System.IO.Path.Combine(assemblyLocation, x)); return extensionDlls.ToArray(); } catch (System.IO.DirectoryNotFoundException ex) { InternalLogger.Warn(ex, "Skipping auto loading location because assembly directory does not exist: {0}", assemblyLocation); if (ex.MustBeRethrown()) { throw; } return ArrayHelper.Empty<string>(); } catch (System.Security.SecurityException ex) { InternalLogger.Warn(ex, "Skipping auto loading location because access not allowed to assembly directory: {0}", assemblyLocation); if (ex.MustBeRethrown()) { throw; } return ArrayHelper.Empty<string>(); } catch (UnauthorizedAccessException ex) { InternalLogger.Warn(ex, "Skipping auto loading location because access not allowed to assembly directory: {0}", assemblyLocation); if (ex.MustBeRethrown()) { throw; } return ArrayHelper.Empty<string>(); } } #endif /// <summary> /// Load from url /// </summary> /// <param name="assemblyFileName">file or path, including .dll</param> /// <param name="baseDirectory">basepath, optional</param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming - Allow extension loading from config", "IL2026")] [Obsolete("Instead use RegisterType<T>, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] private static Assembly LoadAssemblyFromPath(string assemblyFileName, string baseDirectory = null) { #if NETSTANDARD1_3 return null; #else string fullFileName = assemblyFileName; if (!string.IsNullOrEmpty(baseDirectory)) { fullFileName = System.IO.Path.Combine(baseDirectory, assemblyFileName); InternalLogger.Debug("Loading assembly file: {0}", fullFileName); } #if NETSTANDARD1_5 try { var assemblyName = System.Runtime.Loader.AssemblyLoadContext.GetAssemblyName(fullFileName); return Assembly.Load(assemblyName); } catch (Exception ex) { // this doesn't usually work InternalLogger.Warn(ex, "Fallback to AssemblyLoadContext.Default.LoadFromAssemblyPath for file: {0}", fullFileName); return System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(fullFileName); } #else Assembly asm = Assembly.LoadFrom(fullFileName); return asm; #endif #endif } /// <summary> /// Load from url /// </summary> private static Assembly LoadAssemblyFromName(string assemblyName) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 try { Assembly assembly = Assembly.Load(assemblyName); return assembly; } catch (System.IO.FileNotFoundException) { var name = new AssemblyName(assemblyName); InternalLogger.Trace("Try find '{0}' in current domain", assemblyName); var loadedAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(domainAssembly => IsAssemblyMatch(name, domainAssembly.GetName())); if (loadedAssembly != null) { InternalLogger.Trace("Found '{0}' in current domain", assemblyName); return loadedAssembly; } InternalLogger.Trace("Haven't found' '{0}' in current domain", assemblyName); throw; } #else var name = new AssemblyName(assemblyName); return Assembly.Load(name); #endif } #if !NETSTANDARD1_3 && !NETSTANDARD1_5 private static bool IsAssemblyMatch(AssemblyName expected, AssemblyName actual) { if (expected is null || actual is null) return false; if (expected.Name != actual.Name) return false; if (expected.Version != null && expected.Version != actual.Version) return false; if (expected.CultureInfo != null && expected.CultureInfo.Name != actual.CultureInfo.Name) return false; var expectedKeyToken = expected.GetPublicKeyToken(); var correctToken = expectedKeyToken is null || expectedKeyToken.SequenceEqual(actual.GetPublicKeyToken()); return correctToken; } #endif } internal interface IAssemblyExtensionLoader { void ScanForAutoLoadExtensions(ConfigurationItemFactory factory); void LoadAssemblyFromPath(ConfigurationItemFactory factory, string assemblyFileName, string baseDirectory, string itemNamePrefix); void LoadAssemblyFromName(ConfigurationItemFactory factory, string assemblyName, string itemNamePrefix); void LoadTypeFromName(ConfigurationItemFactory factory, string typeName, string itemNamePrefix); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class RepeatingTargetWrapperTests : NLogTestBase { [Fact] public void RepeatingTargetWrapperTest1() { var target = new MyTarget(); var wrapper = new RepeatingTargetWrapper() { WrappedTarget = target, RepeatCount = 3, }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), }; wrapper.WriteAsyncLogEvents(events); // make sure all events went through and were replicated 3 times Assert.Equal(9, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[0].LogEvent, target.Events[1]); Assert.Same(events[0].LogEvent, target.Events[2]); Assert.Same(events[1].LogEvent, target.Events[3]); Assert.Same(events[1].LogEvent, target.Events[4]); Assert.Same(events[1].LogEvent, target.Events[5]); Assert.Same(events[2].LogEvent, target.Events[6]); Assert.Same(events[2].LogEvent, target.Events[7]); Assert.Same(events[2].LogEvent, target.Events[8]); Assert.Equal(events.Length, exceptions.Count); } [Fact] public void RepeatingTargetWrapperTest2() { using (new NoThrowNLogExceptions()) { var target = new MyTarget(); target.ThrowExceptions = true; var wrapper = new RepeatingTargetWrapper() { WrappedTarget = target, RepeatCount = 3, }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), }; wrapper.WriteAsyncLogEvents(events); // make sure all events went through but were registered only once // since repeating target wrapper will not repeat in case of exception. Assert.Equal(3, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Equal(events.Length, exceptions.Count); foreach (var exception in exceptions) { Assert.NotNull(exception); Assert.Equal("Some exception has occurred.", exception.Message); } } } public class MyTarget : Target { public MyTarget() { Events = new List<LogEventInfo>(); } public MyTarget(string name) : this() { Name = name; } public List<LogEventInfo> Events { get; set; } public bool ThrowExceptions { get; set; } protected override void Write(LogEventInfo logEvent) { Events.Add(logEvent); if (ThrowExceptions) { throw new ApplicationException("Some exception has occurred."); } } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using NLog.Common; using NLog.Internal; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class SplitGroupTargetTests : NLogTestBase { [Fact] public void NoTargets_SplitGroupTarget_IsWorking() { SplitGroupTarget_Exercise(ArrayHelper.Empty<MyTarget>()); } [Fact] public void SingleTarget_SplitGroupTarget_IsWorking() { SplitGroupTarget_Exercise(new []{ new MyTarget() }); } [Fact] public void MultipleTargets_SplitGroupTarget_IsWorking() { SplitGroupTarget_Exercise(new[] { new MyTarget(), new MyTarget(), new MyTarget() }); } [Fact] public void FirstTargetFails_SplitGroupTarget_WritesToAll() { using (new NoThrowNLogExceptions()) { int logEventFailCount = 2; var failingTarget = new MyTarget() { FailCounter = logEventFailCount }; SplitGroupTarget_Exercise(new[] { failingTarget, new MyTarget(), new MyTarget() }, logEventFailCount); } } [Fact] public void AsyncOutOfOrder_SplitGroupTarget_IsWorking() { var targets = Enumerable.Range(0, 3).Select(i => new AsyncTargetWrapper(i.ToString(), new MyTarget()) { TimeToSleepBetweenBatches = i * 10 }).ToArray(); targets.ToList().ForEach(t => t.WrappedTarget.Initialize(null)); Func<Target, MyTarget> lookupTarget = t => (MyTarget)((AsyncTargetWrapper)t).WrappedTarget; SplitGroupTarget_Exercise(targets, 0, lookupTarget); } private static void SplitGroupTarget_Exercise(Target[] targets, int logEventFailCount = 0, Func<Target, MyTarget> lookupTarget = null) { // Arrange var wrapper = new SplitGroupTarget(targets); foreach (var target in targets) target.Initialize(null); wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); var flushComplete = new ManualResetEvent(false); lookupTarget = lookupTarget ?? new Func<Target, MyTarget>(t => (MyTarget)t); const int LogEventBatchSize = 2; const int LogEventWriteCount = LogEventBatchSize + 2; // Act wrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Info, "", null, 1).WithContinuation(exceptions.Add)); wrapper.WriteAsyncLogEvents(new[] { LogEventInfo.Create(LogLevel.Info, "", null, 2).WithContinuation(exceptions.Add) }); wrapper.WriteAsyncLogEvents(Enumerable.Range(3, LogEventBatchSize).Select(i => LogEventInfo.Create(LogLevel.Info, "", null, i).WithContinuation(exceptions.Add)).ToArray()); wrapper.Flush(ex => { exceptions.Add(ex); flushComplete.Set(); }); flushComplete.WaitOne(5000); // Assert Assert.Equal(LogEventWriteCount + 1, exceptions.Count); // +1 because of flush Assert.Equal(LogEventWriteCount + 1 - logEventFailCount, exceptions.Count(ex => ex is null)); foreach (var target in targets) { var myTarget = lookupTarget(target); Assert.Equal(LogEventWriteCount, myTarget.WrittenEvents.Count); Assert.Equal(1, myTarget.FlushCount); Assert.Equal(myTarget.WrittenEvents, myTarget.WrittenEvents.OrderBy(l => l.FormattedMessage).ToList()); } } [Fact] public void SplitGroupToStringTest() { var myTarget1 = new MyTarget(); var myTarget2 = new FileTarget("file1"); var myTarget3 = new ConsoleTarget("Console2"); var wrapper = new SplitGroupTarget() { Targets = { myTarget1, myTarget2, myTarget3 }, }; Assert.Equal("SplitGroup[MyTarget([unnamed]), FileTarget(Name=file1), ConsoleTarget(Name=Console2)]", wrapper.ToString()); } public class MyTarget : Target { public MyTarget() { WrittenEvents = new List<LogEventInfo>(); } public MyTarget(string name) : this() { Name = name; } public int FlushCount { get; set; } public int WriteCount { get; set; } public int FailCounter { get; set; } public List<LogEventInfo> WrittenEvents { get; } protected override void Write(LogEventInfo logEvent) { Assert.True(FlushCount <= WriteCount); lock (WrittenEvents) { WriteCount++; WrittenEvents.Add(logEvent); } if (FailCounter > 0) { FailCounter--; throw new ApplicationException("Some failure."); } } protected override void FlushAsync(AsyncContinuation asyncContinuation) { FlushCount++; asyncContinuation(null); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LayoutRenderers { using System.Collections.Generic; using Xunit; public class ScopeNestedTests : NLogTestBase { [Fact] public void ScopeNestedTest() { // Arrange ScopeContext.Clear(); var logFactory = new LogFactory(); logFactory.Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${scopenested} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); var logger = logFactory.GetCurrentClassLogger(); var target = logFactory.Configuration.FindTargetByName<NLog.Targets.DebugTarget>("debug"); // Act using (logger.PushScopeNested("ala")) { using (logger.PushScopeNested("ma")) { logger.Debug("b"); } } // Assert Assert.Equal("ala ma b", target.LastMessage); } [Fact] public void ScopeNestedTopTwoTest() { // Arrange ScopeContext.Clear(); var logFactory = new LogFactory(); logFactory.Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${scopenested:topframes=2} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); var logger = logFactory.GetCurrentClassLogger(); var target = logFactory.Configuration.FindTargetByName<NLog.Targets.DebugTarget>("debug"); // Act using (logger.PushScopeNested("ala")) { using (logger.PushScopeNested("ma")) { using (logger.PushScopeNested("kota")) { logger.Debug("c"); } } } // Assert Assert.Equal("ma kota c", target.LastMessage); } [Fact] public void ScopeNestedTopOneTest() { // Arrange ScopeContext.Clear(); var logFactory = new LogFactory(); logFactory.Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${scopenested:topframes=1} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); var logger = logFactory.GetCurrentClassLogger(); var target = logFactory.Configuration.FindTargetByName<NLog.Targets.DebugTarget>("debug"); // Act using (logger.PushScopeNested("ala")) { using (logger.PushScopeNested("ma")) { using (logger.PushScopeNested("kota")) { logger.Debug("c"); } } } // Assert Assert.Equal("kota c", target.LastMessage); } [Fact] public void ScopeNestedBottomTwoTest() { // Arrange ScopeContext.Clear(); var logFactory = new LogFactory(); logFactory.Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${scopenested:bottomframes=2} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); var logger = logFactory.GetCurrentClassLogger(); var target = logFactory.Configuration.FindTargetByName<NLog.Targets.DebugTarget>("debug"); // Act using (logger.PushScopeNested("ala")) { using (logger.PushScopeNested("ma")) { using (logger.PushScopeNested("kota")) { logger.Debug("c"); } } } // Assert Assert.Equal("ala ma c", target.LastMessage); } [Fact] public void ScopeNestedSeparatorTest() { // Arrange ScopeContext.Clear(); var logFactory = new LogFactory(); logFactory.Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${scopenested:separator=\:} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); var logger = logFactory.GetCurrentClassLogger(); var target = logFactory.Configuration.FindTargetByName<NLog.Targets.DebugTarget>("debug"); // Act using (logger.PushScopeNested("ala")) { using (logger.PushScopeNested("ma")) { using (logger.PushScopeNested("kota")) { logger.Debug("c"); } } } // Assert Assert.Equal("ala:ma:kota c", target.LastMessage); } [Fact] public void ScopeNestedSinglePropertyTest() { // Arrange ScopeContext.Clear(); var logFactory = new LogFactory(); logFactory.Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${scopenested:format=@}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); var logger = logFactory.GetCurrentClassLogger(); var target = logFactory.Configuration.FindTargetByName<NLog.Targets.DebugTarget>("debug"); // Act using (logger.PushScopeNested(new[] { new KeyValuePair<string, object>("Hello", "World") })) { logger.Debug("c"); } // Assert Assert.Equal("[ { \"Hello\": \"World\" } ]", target.LastMessage); } [Fact] public void ScopeNestedTwoPropertiesTest() { // Arrange ScopeContext.Clear(); var logFactory = new LogFactory(); logFactory.Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${scopenested:format=@}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); var logger = logFactory.GetCurrentClassLogger(); var target = logFactory.Configuration.FindTargetByName<NLog.Targets.DebugTarget>("debug"); // Act using (logger.PushScopeNested(new Dictionary<string, object>() { { "Hello", 42 }, { "Unlucky", 13 } })) { logger.Debug("c"); } // Assert Assert.Equal("[ { \"Hello\": 42, \"Unlucky\": 13 } ]", target.LastMessage); } [Fact] public void ScopeNestedTwoPropertiesNewlineTest() { // Arrange ScopeContext.Clear(); var logFactory = new LogFactory(); logFactory.Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${scopenested:format=@:separator=\n}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); var logger = logFactory.GetCurrentClassLogger(); var target = logFactory.Configuration.FindTargetByName<NLog.Targets.DebugTarget>("debug"); // Act using (logger.PushScopeNested(new Dictionary<string, object>() { { "Hello", 42 }, { "Unlucky", 13 } })) { logger.Debug("c"); } // Assert Assert.Equal(string.Format("[{0}{{{0}\"Hello\": 42,{0}\"Unlucky\": 13{0}}}{0}]", "\n"), target.LastMessage); } [Fact] public void ScopeNestedBeginScopeProperties() { // Arrange ScopeContext.Clear(); var logFactory = new LogFactory(); logFactory.Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${scopenested}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); var logger = logFactory.GetCurrentClassLogger(); var target = logFactory.Configuration.FindTargetByName<NLog.Targets.DebugTarget>("debug"); // Act var scopeProperties = new Dictionary<string, object>() { { "Hello", 42 }, { "Unlucky", 13 } }; using (ScopeContext.PushNestedState(scopeProperties)) { logger.Debug("c"); } // Assert Assert.Equal(scopeProperties.ToString(), target.LastMessage); // Avoid enumerating properties, since available from ScopeContext-Properties } [Fact] public void ScopeNestedIndentTest() { // Arrange ScopeContext.Clear(); var logFactory = new LogFactory(); logFactory.Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${scopeindent:_}${scopenested} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); var logger = logFactory.GetCurrentClassLogger(); var target = logFactory.Configuration.FindTargetByName<NLog.Targets.DebugTarget>("debug"); // Act using (logger.PushScopeNested("ala")) { using (logger.PushScopeNested("ma")) { using (logger.PushScopeNested("kota")) { logger.Debug("c"); } } } // Assert Assert.Equal("___ala ma kota c", target.LastMessage); } #if !NET35 && !NET40 && !NET45 [Fact] public void ScopeNestedTimingTest() { // Arrange ScopeContext.Clear(); var logFactory = new LogFactory(); logFactory.Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${ndlc}|${scopetiming}|${scopetiming:CurrentScope=false:StartTime=true:Format=yyyy-MM-dd HH\:mm\:ss}|${scopetiming:CurrentScope=false:StartTime=false:Format=fff}|${scopetiming:CurrentScope=true:StartTime=true:Format=HH\:mm\:ss.fff}|${scopetiming:CurrentScope=true:StartTime=false:Format=fffffff}|${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); var logger = logFactory.GetCurrentClassLogger(); var target = logFactory.Configuration.FindTargetByName<NLog.Targets.DebugTarget>("debug"); logger.Debug("0"); string messageNoScope = target.LastMessage; string messageFirstScope; string messageFirstScopeSleep; string messageFirstScopeExit; string messageSecondScope; string messageSecondScopeSleep; Assert.Equal("||||||0", messageNoScope); using (logger.PushScopeNested("ala")) { logger.Debug("a"); messageFirstScope = target.LastMessage; System.Threading.Thread.Sleep(10); logger.Debug("b"); messageFirstScopeSleep = target.LastMessage; using (logger.PushScopeNested("ma")) { logger.Debug("a"); messageSecondScope = target.LastMessage; System.Threading.Thread.Sleep(10); logger.Debug("b"); messageSecondScopeSleep = target.LastMessage; } logger.Debug("c"); messageFirstScopeExit = target.LastMessage; } // Assert var measurements = messageFirstScope.Split(new[] { '|' }, System.StringSplitOptions.RemoveEmptyEntries); Assert.Equal(7, measurements.Length); Assert.Equal("ala", measurements[0]); Assert.InRange(double.Parse(measurements[1]), 0, 999); Assert.InRange(int.Parse(measurements[3]), 0, 999); Assert.InRange(int.Parse(measurements[5]), 0, 9999999); Assert.Equal("a", measurements[measurements.Length - 1]); measurements = messageFirstScopeSleep.Split(new[] { '|' }, System.StringSplitOptions.RemoveEmptyEntries); Assert.Equal(7, measurements.Length); Assert.Equal("ala", measurements[0]); Assert.InRange(double.Parse(measurements[1], System.Globalization.CultureInfo.InvariantCulture), 10, 999); Assert.InRange(int.Parse(measurements[3]), 10, 999); Assert.InRange(int.Parse(measurements[5]), 100000, 9999999); Assert.Equal("b", measurements[measurements.Length - 1]); measurements = messageSecondScope.Split(new[] { '|' }, System.StringSplitOptions.RemoveEmptyEntries); Assert.Equal(7, measurements.Length); Assert.Equal("ala ma", measurements[0]); Assert.InRange(double.Parse(measurements[1], System.Globalization.CultureInfo.InvariantCulture), 10, 999); Assert.InRange(int.Parse(measurements[3]), 10, 999); Assert.InRange(int.Parse(measurements[5]), 0, 9999999); Assert.Equal("a", measurements[measurements.Length - 1]); measurements = messageSecondScopeSleep.Split(new[] { '|' }, System.StringSplitOptions.RemoveEmptyEntries); Assert.Equal(7, measurements.Length); Assert.Equal("ala ma", measurements[0]); Assert.InRange(double.Parse(measurements[1], System.Globalization.CultureInfo.InvariantCulture), 20, 999); Assert.InRange(int.Parse(measurements[3]), 20, 999); Assert.InRange(int.Parse(measurements[5]), 100000, 9999999); Assert.Equal("b", measurements[measurements.Length - 1]); measurements = messageFirstScopeExit.Split(new[] { '|' }, System.StringSplitOptions.RemoveEmptyEntries); Assert.Equal(7, measurements.Length); Assert.Equal("ala", measurements[0]); Assert.InRange(double.Parse(measurements[1], System.Globalization.CultureInfo.InvariantCulture), 20, 999); Assert.InRange(int.Parse(measurements[3]), 20, 999); Assert.InRange(int.Parse(measurements[5]), 200000, 9999999); Assert.Equal("c", measurements[measurements.Length - 1]); } #endif } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 namespace NLog.Targets { using System; using System.Text; using System.Collections.Generic; using System.ComponentModel; using System.IO; using NLog.Common; using NLog.Config; /// <summary> /// Writes log messages to the console with customizable coloring. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/ColoredConsole-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/ColoredConsole-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/ColoredConsole/NLog.config" /> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/ColoredConsole/Simple/Example.cs" /> /// </example> [Target("ColoredConsole")] public sealed class ColoredConsoleTarget : TargetWithLayoutHeaderAndFooter { /// <summary> /// Should logging being paused/stopped because of the race condition bug in Console.Writeline? /// </summary> /// <remarks> /// Console.Out.Writeline / Console.Error.Writeline could throw 'IndexOutOfRangeException', which is a bug. /// See https://stackoverflow.com/questions/33915790/console-out-and-console-error-race-condition-error-in-a-windows-service-written /// and https://connect.microsoft.com/VisualStudio/feedback/details/2057284/console-out-probable-i-o-race-condition-issue-in-multi-threaded-windows-service /// /// Full error: /// Error during session close: System.IndexOutOfRangeException: Probable I/ O race condition detected while copying memory. /// The I/ O package is not thread safe by default. In multi-threaded applications, /// a stream must be accessed in a thread-safe way, such as a thread - safe wrapper returned by TextReader's or /// TextWriter's Synchronized methods.This also applies to classes like StreamWriter and StreamReader. /// /// </remarks> private bool _pauseLogging; private bool _disableColors; private IColoredConsolePrinter _consolePrinter; /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> public ColoredConsoleTarget() { _consolePrinter = CreateConsolePrinter(EnableAnsiOutput); } /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code> /// </remarks> /// <param name="name">Name of the target.</param> public ColoredConsoleTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets a value indicating whether the error stream (stderr) should be used instead of the output stream (stdout). /// </summary> /// <docgen category='Console Options' order='10' /> [Obsolete("Replaced by StdErr to align with ConsoleTarget. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool ErrorStream { get => StdErr; set => StdErr = value; } /// <summary> /// Gets or sets a value indicating whether to send the log messages to the standard error instead of the standard output. /// </summary> /// <docgen category='Console Options' order='10' /> public bool StdErr { get; set; } /// <summary> /// Gets or sets a value indicating whether to use default row highlighting rules. /// </summary> /// <remarks> /// The default rules are: /// <table> /// <tr> /// <th>Condition</th> /// <th>Foreground Color</th> /// <th>Background Color</th> /// </tr> /// <tr> /// <td>level == LogLevel.Fatal</td> /// <td>Red</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Error</td> /// <td>Yellow</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Warn</td> /// <td>Magenta</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Info</td> /// <td>White</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Debug</td> /// <td>Gray</td> /// <td>NoChange</td> /// </tr> /// <tr> /// <td>level == LogLevel.Trace</td> /// <td>DarkGray</td> /// <td>NoChange</td> /// </tr> /// </table> /// </remarks> /// <docgen category='Highlighting Rules' order='9' /> public bool UseDefaultRowHighlightingRules { get; set; } = true; /// <summary> /// The encoding for writing messages to the <see cref="Console"/>. /// </summary> /// <remarks>Has side effect</remarks> /// <docgen category='Console Options' order='10' /> public Encoding Encoding { get => ConsoleTargetHelper.GetConsoleOutputEncoding(_encoding, IsInitialized, _pauseLogging); set { if (ConsoleTargetHelper.SetConsoleOutputEncoding(value, IsInitialized, _pauseLogging)) _encoding = value; } } private Encoding _encoding; /// <summary> /// Gets or sets a value indicating whether to auto-check if the console is available. /// - Disables console writing if Environment.UserInteractive = False (Windows Service) /// - Disables console writing if Console Standard Input is not available (Non-Console-App) /// </summary> /// <docgen category='Console Options' order='10' /> public bool DetectConsoleAvailable { get; set; } /// <summary> /// Gets or sets a value indicating whether to auto-check if the console has been redirected to file /// - Disables coloring logic when System.Console.IsOutputRedirected = true /// </summary> /// <docgen category='Console Options' order='11' /> public bool DetectOutputRedirected { get; set; } /// <summary> /// Gets or sets a value indicating whether to auto-flush after <see cref="Console.WriteLine()"/> /// </summary> /// <remarks> /// Normally not required as standard Console.Out will have <see cref="StreamWriter.AutoFlush"/> = true, but not when pipe to file /// </remarks> /// <docgen category='Console Options' order='11' /> public bool AutoFlush { get; set; } /// <summary> /// Enables output using ANSI Color Codes /// </summary> /// <docgen category='Console Options' order='10' /> public bool EnableAnsiOutput { get; set; } /// <summary> /// Gets the row highlighting rules. /// </summary> /// <docgen category='Highlighting Rules' order='10' /> [ArrayParameter(typeof(ConsoleRowHighlightingRule), "highlight-row")] public IList<ConsoleRowHighlightingRule> RowHighlightingRules { get; } = new List<ConsoleRowHighlightingRule>(); /// <summary> /// Gets the word highlighting rules. /// </summary> /// <docgen category='Highlighting Rules' order='11' /> [ArrayParameter(typeof(ConsoleWordHighlightingRule), "highlight-word")] public IList<ConsoleWordHighlightingRule> WordHighlightingRules { get; } = new List<ConsoleWordHighlightingRule>(); /// <inheritdoc/> protected override void InitializeTarget() { _pauseLogging = false; _disableColors = false; if (DetectConsoleAvailable) { string reason; _pauseLogging = !ConsoleTargetHelper.IsConsoleAvailable(out reason); if (_pauseLogging) { InternalLogger.Info("{0}: Console detected as turned off. Disable DetectConsoleAvailable to skip detection. Reason: {1}", this, reason); } } if (_encoding != null) ConsoleTargetHelper.SetConsoleOutputEncoding(_encoding, true, _pauseLogging); #if !NET35 && !NET40 if (DetectOutputRedirected) { try { _disableColors = StdErr ? Console.IsErrorRedirected : Console.IsOutputRedirected; if (_disableColors) { InternalLogger.Info("{0}: Console output is redirected so no colors. Disable DetectOutputRedirected to skip detection.", this); if (!AutoFlush && GetOutput() is StreamWriter streamWriter && !streamWriter.AutoFlush) { AutoFlush = true; } } } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed checking if Console Output Redirected.", this); } } #endif base.InitializeTarget(); if (Header != null) { LogEventInfo lei = LogEventInfo.CreateNullEvent(); WriteToOutput(lei, RenderLogEvent(Header, lei)); } _consolePrinter = CreateConsolePrinter(EnableAnsiOutput); } private static IColoredConsolePrinter CreateConsolePrinter(bool enableAnsiOutput) { if (!enableAnsiOutput) return new ColoredConsoleSystemPrinter(); else return new ColoredConsoleAnsiPrinter(); } /// <inheritdoc/> protected override void CloseTarget() { if (Footer != null) { LogEventInfo lei = LogEventInfo.CreateNullEvent(); WriteToOutput(lei, RenderLogEvent(Footer, lei)); } ExplicitConsoleFlush(); base.CloseTarget(); } /// <inheritdoc/> protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { ExplicitConsoleFlush(); base.FlushAsync(asyncContinuation); } catch (Exception ex) { asyncContinuation(ex); } } private void ExplicitConsoleFlush() { if (!_pauseLogging && !AutoFlush) { var output = GetOutput(); output.Flush(); } } /// <inheritdoc/> protected override void Write(LogEventInfo logEvent) { if (_pauseLogging) { //check early for performance (See also DetectConsoleAvailable) return; } WriteToOutput(logEvent, RenderLogEvent(Layout, logEvent)); } private void WriteToOutput(LogEventInfo logEvent, string message) { try { WriteToOutputWithColor(logEvent, message ?? string.Empty); } catch (Exception ex) when (ex is OverflowException || ex is IndexOutOfRangeException || ex is ArgumentOutOfRangeException) { // This is a bug and will therefore stop the logging. For docs, see the PauseLogging property. _pauseLogging = true; InternalLogger.Warn(ex, "{0}: {1} has been thrown and this is probably due to a race condition." + "Logging to the console will be paused. Enable by reloading the config or re-initialize the targets", this, ex.GetType()); } } private void WriteToOutputWithColor(LogEventInfo logEvent, string message) { string colorMessage = message; ConsoleColor? newForegroundColor = null; ConsoleColor? newBackgroundColor = null; if (!_disableColors) { var matchingRule = GetMatchingRowHighlightingRule(logEvent); if (WordHighlightingRules.Count > 0) { colorMessage = GenerateColorEscapeSequences(logEvent, message); } newForegroundColor = matchingRule.ForegroundColor != ConsoleOutputColor.NoChange ? (ConsoleColor)matchingRule.ForegroundColor : default(ConsoleColor?); newBackgroundColor = matchingRule.BackgroundColor != ConsoleOutputColor.NoChange ? (ConsoleColor)matchingRule.BackgroundColor : default(ConsoleColor?); } var consoleStream = GetOutput(); if (ReferenceEquals(colorMessage, message) && !newForegroundColor.HasValue && !newBackgroundColor.HasValue) { ConsoleTargetHelper.WriteLineThreadSafe(consoleStream, message, AutoFlush); } else { bool wordHighlighting = !ReferenceEquals(colorMessage, message); if (!wordHighlighting && message.IndexOf('\n') >= 0) { wordHighlighting = true; // Newlines requires additional handling when doing colors colorMessage = EscapeColorCodes(message); } WriteToOutputWithPrinter(consoleStream, colorMessage, newForegroundColor, newBackgroundColor, wordHighlighting); } } private void WriteToOutputWithPrinter(TextWriter consoleStream, string colorMessage, ConsoleColor? newForegroundColor, ConsoleColor? newBackgroundColor, bool wordHighlighting) { using (var targetBuilder = ReusableLayoutBuilder.Allocate()) { TextWriter consoleWriter = _consolePrinter.AcquireTextWriter(consoleStream, targetBuilder.Result); ConsoleColor? oldForegroundColor = null; ConsoleColor? oldBackgroundColor = null; try { if (wordHighlighting) { oldForegroundColor = _consolePrinter.ChangeForegroundColor(consoleWriter, newForegroundColor); oldBackgroundColor = _consolePrinter.ChangeBackgroundColor(consoleWriter, newBackgroundColor); var rowForegroundColor = newForegroundColor ?? oldForegroundColor; var rowBackgroundColor = newBackgroundColor ?? oldBackgroundColor; ColorizeEscapeSequences(_consolePrinter, consoleWriter, colorMessage, oldForegroundColor, oldBackgroundColor, rowForegroundColor, rowBackgroundColor); _consolePrinter.WriteLine(consoleWriter, string.Empty); } else { if (newForegroundColor.HasValue) { oldForegroundColor = _consolePrinter.ChangeForegroundColor(consoleWriter, newForegroundColor.Value); if (oldForegroundColor == newForegroundColor) oldForegroundColor = null; // No color restore is needed } if (newBackgroundColor.HasValue) { oldBackgroundColor = _consolePrinter.ChangeBackgroundColor(consoleWriter, newBackgroundColor.Value); if (oldBackgroundColor == newBackgroundColor) oldBackgroundColor = null; // No color restore is needed } _consolePrinter.WriteLine(consoleWriter, colorMessage); } } finally { _consolePrinter.ReleaseTextWriter(consoleWriter, consoleStream, oldForegroundColor, oldBackgroundColor, AutoFlush); } } } private ConsoleRowHighlightingRule GetMatchingRowHighlightingRule(LogEventInfo logEvent) { var matchingRule = GetMatchingRowHighlightingRule(RowHighlightingRules, logEvent); if (matchingRule is null && UseDefaultRowHighlightingRules) { matchingRule = GetMatchingRowHighlightingRule(_consolePrinter.DefaultConsoleRowHighlightingRules, logEvent); } return matchingRule ?? ConsoleRowHighlightingRule.Default; } private ConsoleRowHighlightingRule GetMatchingRowHighlightingRule(IList<ConsoleRowHighlightingRule> rules, LogEventInfo logEvent) { for (int i = 0; i < rules.Count; ++i) { var rule = rules[i]; if (rule.CheckCondition(logEvent)) return rule; } return null; } private string GenerateColorEscapeSequences(LogEventInfo logEvent, string message) { if (string.IsNullOrEmpty(message)) return message; message = EscapeColorCodes(message); using (var targetBuilder = ReusableLayoutBuilder.Allocate()) { StringBuilder sb = targetBuilder.Result; for (int i = 0; i < WordHighlightingRules.Count; ++i) { var hl = WordHighlightingRules[i]; var matches = hl.Matches(logEvent, message); if (matches is null || matches.Count == 0) continue; if (sb != null) sb.Length = 0; int previousIndex = 0; foreach (System.Text.RegularExpressions.Match match in matches) { sb = sb ?? new StringBuilder(message.Length + 5); sb.Append(message, previousIndex, match.Index - previousIndex); sb.Append('\a'); sb.Append((char)((int)hl.ForegroundColor + 'A')); sb.Append((char)((int)hl.BackgroundColor + 'A')); sb.Append(match.Value); sb.Append('\a'); sb.Append('X'); previousIndex = match.Index + match.Length; } if (sb?.Length > 0) { sb.Append(message, previousIndex, message.Length - previousIndex); message = sb.ToString(); } } } return message; } private static string EscapeColorCodes(string message) { if (message.IndexOf('\a') >= 0) message = message.Replace("\a", "\a\a"); return message; } private static void ColorizeEscapeSequences( IColoredConsolePrinter consolePrinter, TextWriter consoleWriter, string message, ConsoleColor? defaultForegroundColor, ConsoleColor? defaultBackgroundColor, ConsoleColor? rowForegroundColor, ConsoleColor? rowBackgroundColor) { var colorStack = new Stack<KeyValuePair<ConsoleColor?, ConsoleColor?>>(); colorStack.Push(new KeyValuePair<ConsoleColor?, ConsoleColor?>(rowForegroundColor, rowBackgroundColor)); int p0 = 0; while (p0 < message.Length) { int p1 = p0; while (p1 < message.Length && message[p1] >= 32) { p1++; } // text if (p1 != p0) { consolePrinter.WriteSubString(consoleWriter, message, p0, p1); } if (p1 >= message.Length) { p0 = p1; break; } // control characters char c1 = message[p1]; if (c1 == '\r' || c1 == '\n') { // Newline control characters var currentColorConfig = colorStack.Peek(); var resetForegroundColor = currentColorConfig.Key != defaultForegroundColor ? defaultForegroundColor : null; var resetBackgroundColor = currentColorConfig.Value != defaultBackgroundColor ? defaultBackgroundColor : null; consolePrinter.ResetDefaultColors(consoleWriter, resetForegroundColor, resetBackgroundColor); if (p1 + 1 < message.Length && message[p1 + 1] == '\n') { consolePrinter.WriteSubString(consoleWriter, message, p1, p1 + 2); p0 = p1 + 2; } else { consolePrinter.WriteChar(consoleWriter, c1); p0 = p1 + 1; } consolePrinter.ChangeForegroundColor(consoleWriter, currentColorConfig.Key, defaultForegroundColor); consolePrinter.ChangeBackgroundColor(consoleWriter, currentColorConfig.Value, defaultBackgroundColor); continue; } if (c1 != '\a' || p1 + 1 >= message.Length) { // Other control characters consolePrinter.WriteChar(consoleWriter, c1); p0 = p1 + 1; continue; } // coloring control characters char c2 = message[p1 + 1]; if (c2 == '\a') { consolePrinter.WriteChar(consoleWriter, '\a'); p0 = p1 + 2; continue; } if (c2 == 'X') { var oldColorConfig = colorStack.Pop(); var newColorConfig = colorStack.Peek(); if (newColorConfig.Key != oldColorConfig.Key || newColorConfig.Value != oldColorConfig.Value) { if ((oldColorConfig.Key.HasValue && !newColorConfig.Key.HasValue) || (oldColorConfig.Value.HasValue && !newColorConfig.Value.HasValue)) { consolePrinter.ResetDefaultColors(consoleWriter, defaultForegroundColor, defaultBackgroundColor); } consolePrinter.ChangeForegroundColor(consoleWriter, newColorConfig.Key, oldColorConfig.Key); consolePrinter.ChangeBackgroundColor(consoleWriter, newColorConfig.Value, oldColorConfig.Value); } p0 = p1 + 2; continue; } var currentForegroundColor = colorStack.Peek().Key; var currentBackgroundColor = colorStack.Peek().Value; var foreground = (ConsoleOutputColor)(c2 - 'A'); var background = (ConsoleOutputColor)(message[p1 + 2] - 'A'); if (foreground != ConsoleOutputColor.NoChange) { currentForegroundColor = (ConsoleColor)foreground; consolePrinter.ChangeForegroundColor(consoleWriter, currentForegroundColor); } if (background != ConsoleOutputColor.NoChange) { currentBackgroundColor = (ConsoleColor)background; consolePrinter.ChangeBackgroundColor(consoleWriter, currentBackgroundColor); } colorStack.Push(new KeyValuePair<ConsoleColor?, ConsoleColor?>(currentForegroundColor, currentBackgroundColor)); p0 = p1 + 3; } if (p0 < message.Length) { consolePrinter.WriteSubString(consoleWriter, message, p0, message.Length); } } private TextWriter GetOutput() { return StdErr ? Console.Error : Console.Out; } } } #endif<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.ComponentModel; using System.Diagnostics; #if !NET40 && !NET35 using System.Threading.Tasks; #endif using JetBrains.Annotations; using NLog.Internal; /// <summary> /// Extensions for NLog <see cref="ILogger"/>. /// </summary> [CLSCompliant(false)] public static class ILoggerExtensions { /// <summary> /// Starts building a log event with the specified <see cref="LogLevel"/>. /// </summary> /// <param name="logger">The logger to write the log event to.</param> /// <param name="logLevel">The log level. When not</param> /// <returns><see cref="LogEventBuilder"/> for chaining calls.</returns> public static LogEventBuilder ForLogEvent([NotNull] this ILogger logger, LogLevel logLevel = null) { return logLevel is null ? new LogEventBuilder(logger) : new LogEventBuilder(logger, logLevel); } /// <summary> /// Starts building a log event at the <c>Trace</c> level. /// </summary> /// <param name="logger">The logger to write the log event to.</param> /// <returns><see cref="LogEventBuilder"/> for chaining calls.</returns> public static LogEventBuilder ForTraceEvent([NotNull] this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Trace); } /// <summary> /// Starts building a log event at the <c>Debug</c> level. /// </summary> /// <param name="logger">The logger to write the log event to.</param> /// <returns><see cref="LogEventBuilder"/> for chaining calls.</returns> public static LogEventBuilder ForDebugEvent([NotNull] this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Debug); } /// <summary> /// Starts building a log event at the <c>Info</c> level. /// </summary> /// <param name="logger">The logger to write the log event to.</param> /// <returns><see cref="LogEventBuilder"/> for chaining calls.</returns> public static LogEventBuilder ForInfoEvent([NotNull] this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Info); } /// <summary> /// Starts building a log event at the <c>Warn</c> level. /// </summary> /// <param name="logger">The logger to write the log event to.</param> /// <returns><see cref="LogEventBuilder"/> for chaining calls.</returns> public static LogEventBuilder ForWarnEvent([NotNull] this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Warn); } /// <summary> /// Starts building a log event at the <c>Error</c> level. /// </summary> /// <param name="logger">The logger to write the log event to.</param> /// <returns><see cref="LogEventBuilder"/> for chaining calls.</returns> public static LogEventBuilder ForErrorEvent([NotNull] this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Error); } /// <summary> /// Starts building a log event at the <c>Fatal</c> level. /// </summary> /// <param name="logger">The logger to write the log event to.</param> /// <returns><see cref="LogEventBuilder"/> for chaining calls.</returns> public static LogEventBuilder ForFatalEvent([NotNull] this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Fatal); } /// <summary> /// Starts building a log event at the <c>Exception</c> level. /// </summary> /// <param name="logger">The logger to write the log event to.</param> /// <param name="exception">The exception information of the logging event.</param> /// <param name="logLevel">The <see cref="LogLevel"/> for the log event. Defaults to <see cref="LogLevel.Error"/> when not specified.</param> /// <returns><see cref="LogEventBuilder"/> for chaining calls.</returns> public static LogEventBuilder ForExceptionEvent([NotNull] this ILogger logger, Exception exception, LogLevel logLevel = null) { return ForLogEvent(logger, logLevel ?? LogLevel.Error).Exception(exception); } #region ConditionalDebug /// <overloads> /// Writes the diagnostic message at the <c>Debug</c> level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="value">The value to be written.</param> [Conditional("DEBUG")] public static void ConditionalDebug<T>([NotNull] this ILogger logger, T value) { logger.Debug(value); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> [Conditional("DEBUG")] public static void ConditionalDebug<T>([NotNull] this ILogger logger, IFormatProvider formatProvider, T value) { logger.Debug(formatProvider, value); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> [Conditional("DEBUG")] public static void ConditionalDebug([NotNull] this ILogger logger, LogMessageGenerator messageFunc) { logger.Debug(messageFunc); } /// <summary> /// Writes the diagnostic message and exception at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug([NotNull] this ILogger logger, Exception exception, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { logger.Debug(exception, message, args); } /// <summary> /// Writes the diagnostic message and exception at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug([NotNull] this ILogger logger, Exception exception, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { logger.Debug(exception, formatProvider, message, args); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">Log message.</param> [Conditional("DEBUG")] public static void ConditionalDebug([NotNull] this ILogger logger, [Localizable(false)] string message) { logger.Debug(message, default(object[])); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug([NotNull] this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { logger.Debug(message, args); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug([NotNull] this ILogger logger, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { logger.Debug(formatProvider, message, args); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug<TArgument>([NotNull] this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument argument) { if (logger.IsDebugEnabled) { logger.Debug(message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug<TArgument1, TArgument2>([NotNull] this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2) { if (logger.IsDebugEnabled) { logger.Debug(message, new object[] { argument1, argument2 }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug<TArgument1, TArgument2, TArgument3>([NotNull] this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3) { if (logger.IsDebugEnabled) { logger.Debug(message, new object[] { argument1, argument2, argument3 }); } } #endregion #region ConditionalTrace /// <overloads> /// Writes the diagnostic message at the <c>Debug</c> level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="value">The value to be written.</param> [Conditional("DEBUG")] public static void ConditionalTrace<T>([NotNull] this ILogger logger, T value) { logger.Trace(value); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> [Conditional("DEBUG")] public static void ConditionalTrace<T>([NotNull] this ILogger logger, IFormatProvider formatProvider, T value) { logger.Trace(formatProvider, value); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> [Conditional("DEBUG")] public static void ConditionalTrace([NotNull] this ILogger logger, LogMessageGenerator messageFunc) { logger.Trace(messageFunc); } /// <summary> /// Writes the diagnostic message and exception at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace([NotNull] this ILogger logger, Exception exception, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { logger.Trace(exception, message, args); } /// <summary> /// Writes the diagnostic message and exception at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace([NotNull] this ILogger logger, Exception exception, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { logger.Trace(exception, formatProvider, message, args); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">Log message.</param> [Conditional("DEBUG")] public static void ConditionalTrace([NotNull] this ILogger logger, [Localizable(false)] string message) { logger.Trace(message, default(object[])); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace([NotNull] this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { logger.Trace(message, args); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace([NotNull] this ILogger logger, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { logger.Trace(formatProvider, message, args); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace<TArgument>([NotNull] this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument argument) { if (logger.IsTraceEnabled) { logger.Trace(message, new object[] { argument }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace<TArgument1, TArgument2>([NotNull] this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2) { if (logger.IsTraceEnabled) { logger.Trace(message, new object[] { argument1, argument2 }); } } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace<TArgument1, TArgument2, TArgument3>([NotNull] this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3) { if (logger.IsTraceEnabled) { logger.Trace(message, new object[] { argument1, argument2, argument3 }); } } #endregion /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="level">The log level.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> public static void Log([NotNull] this ILogger logger, LogLevel level, Exception exception, LogMessageGenerator messageFunc) { if (logger.IsEnabled(level)) { logger.Log(level, exception, messageFunc(), null); } } /// <summary> /// Writes the diagnostic message and exception at the <c>Trace</c> level. /// </summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> public static void Trace([NotNull] this ILogger logger, Exception exception, LogMessageGenerator messageFunc) { if (logger.IsTraceEnabled) { Guard.ThrowIfNull(messageFunc); logger.Trace(exception, messageFunc()); } } /// <summary> /// Writes the diagnostic message and exception at the <c>Debug</c> level. /// </summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> public static void Debug([NotNull] this ILogger logger, Exception exception, LogMessageGenerator messageFunc) { if (logger.IsDebugEnabled) { Guard.ThrowIfNull(messageFunc); logger.Debug(exception, messageFunc()); } } /// <summary> /// Writes the diagnostic message and exception at the <c>Info</c> level. /// </summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> public static void Info([NotNull] this ILogger logger, Exception exception, LogMessageGenerator messageFunc) { if (logger.IsInfoEnabled) { Guard.ThrowIfNull(messageFunc); logger.Info(exception, messageFunc()); } } /// <summary> /// Writes the diagnostic message and exception at the <c>Warn</c> level. /// </summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> public static void Warn([NotNull] this ILogger logger, Exception exception, LogMessageGenerator messageFunc) { if (logger.IsWarnEnabled) { Guard.ThrowIfNull(messageFunc); logger.Warn(exception, messageFunc()); } } /// <summary> /// Writes the diagnostic message and exception at the <c>Error</c> level. /// </summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> public static void Error([NotNull] this ILogger logger, Exception exception, LogMessageGenerator messageFunc) { if (logger.IsErrorEnabled) { Guard.ThrowIfNull(messageFunc); logger.Error(exception, messageFunc()); } } /// <summary> /// Writes the diagnostic message and exception at the <c>Fatal</c> level. /// </summary> /// <param name="logger">A logger implementation that will handle the message.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> public static void Fatal([NotNull] this ILogger logger, Exception exception, LogMessageGenerator messageFunc) { if (logger.IsFatalEnabled) { Guard.ThrowIfNull(messageFunc); logger.Fatal(exception, messageFunc()); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using JetBrains.Annotations; using NLog.Internal; namespace NLog { /// <summary> /// A fluent builder for logging events to NLog. /// </summary> [CLSCompliant(false)] public struct LogEventBuilder { private readonly ILogger _logger; private readonly LogEventInfo _logEvent; /// <summary> /// Initializes a new instance of the <see cref="LogEventBuilder"/> class. /// </summary> /// <param name="logger">The <see cref="NLog.Logger"/> to send the log event.</param> public LogEventBuilder([NotNull] ILogger logger) { _logger = Guard.ThrowIfNull(logger); _logEvent = new LogEventInfo() { LoggerName = _logger.Name }; } /// <summary> /// Initializes a new instance of the <see cref="LogEventBuilder"/> class. /// </summary> /// <param name="logger">The <see cref="NLog.Logger"/> to send the log event.</param> /// <param name="logLevel">The log level. LogEvent is only created when <see cref="LogLevel"/> is enabled for <paramref name="logger"/></param> public LogEventBuilder([NotNull] ILogger logger, [NotNull] LogLevel logLevel) { _logger = Guard.ThrowIfNull(logger); Guard.ThrowIfNull(logLevel); if (logger.IsEnabled(logLevel)) { _logEvent = new LogEventInfo() { LoggerName = _logger.Name, Level = logLevel }; } else { _logEvent = null; } } /// <summary> /// The logger to write the log event to /// </summary> [NotNull] public ILogger Logger => _logger; /// <summary> /// Logging event that will be written /// </summary> [CanBeNull] public LogEventInfo LogEvent => _logEvent is null ? null : ResolveLogEvent(_logEvent); /// <summary> /// Sets a per-event context property on the logging event. /// </summary> /// <param name="propertyName">The name of the context property.</param> /// <param name="propertyValue">The value of the context property.</param> public LogEventBuilder Property<T>([NotNull] string propertyName, T propertyValue) { Guard.ThrowIfNull(propertyName); if (_logEvent is null) return this; _logEvent.Properties[propertyName] = propertyValue; return this; } /// <summary> /// Sets multiple per-event context properties on the logging event. /// </summary> /// <param name="properties">The properties to set.</param> public LogEventBuilder Properties([NotNull] IEnumerable<KeyValuePair<string, object>> properties) { Guard.ThrowIfNull(properties); if (_logEvent is null) return this; foreach (var property in properties) _logEvent.Properties[property.Key] = property.Value; return this; } /// <summary> /// Sets the <paramref name="exception"/> information of the logging event. /// </summary> /// <param name="exception">The exception information of the logging event.</param> public LogEventBuilder Exception(Exception exception) { if (_logEvent != null) { _logEvent.Exception = exception; } return this; } /// <summary> /// Sets the timestamp of the logging event. /// </summary> /// <param name="timeStamp">The timestamp of the logging event.</param> public LogEventBuilder TimeStamp(DateTime timeStamp) { if (_logEvent != null) { _logEvent.TimeStamp = timeStamp; } return this; } /// <summary> /// Sets the log message on the logging event. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> public LogEventBuilder Message([Localizable(false)] string message) { if (_logEvent != null) { _logEvent.Parameters = null; _logEvent.Message = message; } return this; } /// <summary> /// Sets the log message and parameters for formatting for the logging event. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] public LogEventBuilder Message<TArgument>([Localizable(false)][StructuredMessageTemplate] string message, TArgument argument) { if (_logEvent != null) { _logEvent.Message = message; _logEvent.Parameters = new object[] { argument }; } return this; } /// <summary> /// Sets the log message and parameters for formatting on the logging event. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] public LogEventBuilder Message<TArgument1, TArgument2>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2) { if (_logEvent != null) { _logEvent.Message = message; _logEvent.Parameters = new object[] { argument1, argument2 }; } return this; } /// <summary> /// Sets the log message and parameters for formatting on the logging event. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] public LogEventBuilder Message<TArgument1, TArgument2, TArgument3>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3) { if (_logEvent != null) { _logEvent.Message = message; _logEvent.Parameters = new object[] { argument1, argument2, argument3 }; } return this; } /// <summary> /// Sets the log message and parameters for formatting on the logging event. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] public LogEventBuilder Message([Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { if (_logEvent != null) { _logEvent.Message = message; _logEvent.Parameters = args; } return this; } /// <summary> /// Sets the log message and parameters for formatting on the logging event. /// </summary> /// <param name="formatProvider">An object that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] public LogEventBuilder Message(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { if (_logEvent != null) { _logEvent.FormatProvider = formatProvider; _logEvent.Message = message; _logEvent.Parameters = args; } return this; } /// <summary> /// Writes the log event to the underlying logger. /// </summary> /// <param name="callerClassName">The class of the caller to the method. This is captured by the NLog engine when necessary</param> /// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param> /// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param> /// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param> #if !NET35 public LogEventBuilder Callsite(string callerClassName = null, [CallerMemberName]string callerMemberName = null, [CallerFilePath]string callerFilePath = null, [CallerLineNumber]int callerLineNumber = 0) #else public LogEventBuilder Callsite(string callerClassName = null, string callerMemberName = null, string callerFilePath = null, int callerLineNumber = 0) #endif { if (_logEvent != null) { _logEvent.SetCallerInfo(callerClassName, callerMemberName, callerFilePath, callerLineNumber); } return this; } /// <summary> /// Writes the log event to the underlying logger. /// </summary> /// <param name="logLevel">The log level. Optional but when assigned to <see cref="LogLevel.Off"/> then it will discard the LogEvent.</param> /// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param> /// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param> /// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param> #if !NET35 public void Log(LogLevel logLevel = null, [CallerMemberName]string callerMemberName = null, [CallerFilePath]string callerFilePath = null, [CallerLineNumber]int callerLineNumber = 0) #else public void Log(LogLevel logLevel = null, string callerMemberName = null, string callerFilePath = null, int callerLineNumber = 0) #endif { if (_logEvent != null) { var logEvent = ResolveLogEvent(_logEvent, logLevel); if (logEvent.CallSiteInformation is null && _logger.IsEnabled(logEvent.Level)) { _logEvent.SetCallerInfo(null, callerMemberName, callerFilePath, callerLineNumber); } _logger.Log(logEvent); } } /// <summary> /// Writes the log event to the underlying logger. /// </summary> /// <param name="wrapperType">Type of custom Logger wrapper.</param> #if !NET35 public void Log(Type wrapperType) #else public void Log(Type wrapperType) #endif { if (_logEvent != null) { var logEvent = ResolveLogEvent(_logEvent); _logger.Log(wrapperType, logEvent); } } private LogEventInfo ResolveLogEvent(LogEventInfo logEvent, LogLevel logLevel = null) { if (logLevel is null) { if (logEvent.Level is null) logEvent.Level = logEvent.Exception != null ? LogLevel.Error : LogLevel.Info; } else { logEvent.Level = logLevel; } if (logEvent.Message is null && logEvent.Exception != null && _logger.IsEnabled(logEvent.Level)) { logEvent.FormatProvider = NLog.Internal.ExceptionMessageFormatProvider.Instance; logEvent.Message = "{0}"; logEvent.Parameters = new object[] { logEvent.Exception }; } return logEvent; } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.IO; using System.Reflection; using System.Threading; using NLog.Common; using NLog.Internal; using Xunit; namespace NLog.UnitTests.Internal { public class ExceptionHelperTests : NLogTestBase { [Theory] #if !NETSTANDARD1_5 [InlineData(typeof(StackOverflowException), true)] [InlineData(typeof(ThreadAbortException), true)] #endif [InlineData(typeof(NLogConfigurationException), false)] [InlineData(typeof(Exception), false)] [InlineData(typeof(ArgumentException), false)] #if !DEBUG [InlineData(typeof(NullReferenceException), false)] #endif [InlineData(typeof(OutOfMemoryException), true)] public void TestMustBeRethrowImmediately(Type t, bool result) { var ex = CreateException(t); Assert.Equal(result, ex.MustBeRethrownImmediately()); } [Theory] #if !NETSTANDARD1_5 [InlineData(typeof(StackOverflowException), true, false, false)] [InlineData(typeof(StackOverflowException), true, true, false)] [InlineData(typeof(ThreadAbortException), true, false, false)] [InlineData(typeof(ThreadAbortException), true, true, false)] #endif [InlineData(typeof(NLogConfigurationException), true, true, true)] [InlineData(typeof(NLogConfigurationException), false, true, false)] [InlineData(typeof(NLogConfigurationException), true, true, null)] [InlineData(typeof(NLogConfigurationException), true, false, true)] [InlineData(typeof(NLogConfigurationException), false, false, false)] [InlineData(typeof(NLogConfigurationException), false, false, null)] [InlineData(typeof(Exception), false, false, false)] [InlineData(typeof(Exception), false, false, true)] [InlineData(typeof(Exception), false, false, null)] [InlineData(typeof(Exception), true, true, false)] [InlineData(typeof(Exception), true, true, true)] [InlineData(typeof(Exception), true, true, null)] [InlineData(typeof(ArgumentException), false, false, false)] [InlineData(typeof(ArgumentException), false, false, true)] [InlineData(typeof(ArgumentException), false, false, null)] [InlineData(typeof(ArgumentException), true, true, false)] [InlineData(typeof(ArgumentException), true, true, true)] [InlineData(typeof(ArgumentException), true, true, null)] #if !DEBUG [InlineData(typeof(NullReferenceException), false, false, false)] [InlineData(typeof(NullReferenceException), true, true, false)] #endif [InlineData(typeof(OutOfMemoryException), true, false, false)] [InlineData(typeof(OutOfMemoryException), true, true, false)] public void MustBeRethrown(Type exceptionType, bool result, bool throwExceptions, bool? throwConfigException) { LogManager.ThrowExceptions = throwExceptions; LogManager.ThrowConfigExceptions = throwConfigException; var ex = CreateException(exceptionType); Assert.Equal(result, ex.MustBeRethrown()); } [Theory] [InlineData("Error has been raised.", typeof(ArgumentException), false, "Error")] [InlineData("Error has been raised.", typeof(ArgumentException), true, "Warn")] [InlineData("Error has been raised.", typeof(NLogConfigurationException), false, "Error")] [InlineData("Error has been raised.", typeof(NLogConfigurationException), true, "Warn")] [InlineData("", typeof(ArgumentException), true, "Warn")] [InlineData("", typeof(NLogConfigurationException), true, "Warn")] public void MustBeRethrown_ShouldLog_exception_and_only_once(string text, Type exceptionType, bool logFirst, string levelText) { using (new InternalLoggerScope()) { var level = LogLevel.FromString(levelText); InternalLogger.LogLevel = LogLevel.Trace; var stringWriter = new StringWriter(); InternalLogger.LogWriter = stringWriter; InternalLogger.IncludeTimestamp = false; var ex1 = CreateException(exceptionType); //exception should be once const string prefix = " Exception: "; string expected = levelText + " " + text + prefix + ex1 + Environment.NewLine; // Named (based on LogLevel) public methods. if (logFirst) InternalLogger.Log(ex1, level, text); ex1.MustBeRethrown(); stringWriter.Flush(); var actual = stringWriter.ToString(); Assert.Equal(expected, actual); } } private static Exception CreateException(Type exceptionType) { return exceptionType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Default | BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null).Invoke(null) as Exception; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.IO; using System.Linq; using NLog.Targets; using Xunit; public class ColoredConsoleTargetTests : NLogTestBase { [Fact] public void RowHighLightNewLineTest() { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; AssertOutput(target, "Before\a\nAfter\a", new string[] { "Before", "After" }); } [Theory] [InlineData(true)] [InlineData(false)] public void WordHighlightingTextTest(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = "at", CompileRegex = compileRegex }); AssertOutput(target, "The Cat Sat At The Bar\t\n.\a", new string[] { "The C", "at", " S", "at", " At The Bar", "." }); } [Fact] public void WordHighlightingTextCondition() { var highlightLogger = "SpecialLogger"; var target = new ColoredConsoleTarget { Layout = "${logger}${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = "at", Condition = string.Concat("logger=='", highlightLogger, "'"), }); AssertOutput(target, "The Cat Sat At The Bar.", new string[] { "The C", "at", " S", "at", " At The Bar." }, loggerName: highlightLogger); AssertOutput(target, "The Cat Sat At The Bar", new string[] { "The Cat Sat At The Bar" }, loggerName: "DefaultLogger"); } [Theory] [InlineData(true)] [InlineData(false)] public void WordHighlightingTextIgnoreCase(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = "at", IgnoreCase = true, CompileRegex = compileRegex }); AssertOutput(target, "The Cat Sat At The Bar.", new string[] { "The C", "at", " S", "at", " ", "At", " The Bar." }); } [Theory] [InlineData(true)] [InlineData(false)] public void WordHighlightingTextWholeWords(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = "at", WholeWords = true, CompileRegex = compileRegex }); AssertOutput(target, "The cat sat at the bar.", new string[] { "The cat sat ", "at", " the bar." }); } [Theory] [InlineData(true)] [InlineData(false)] public void WordHighlightingRegex(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Regex = "\\wat", CompileRegex = compileRegex }); AssertOutput(target, "The cat sat at the bar.", new string[] { "The ", "cat", " ", "sat", " at the bar." }); } [Fact] public void ColoredConsoleAnsi_OverlappingWordHighlight_VerificationTest() { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}", EnableAnsiOutput = true }; target.UseDefaultRowHighlightingRules = false; target.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "big warning", ForegroundColor = ConsoleOutputColor.DarkRed, BackgroundColor = ConsoleOutputColor.NoChange }); target.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "warn", ForegroundColor = ConsoleOutputColor.DarkMagenta, BackgroundColor = ConsoleOutputColor.NoChange }); target.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "a", ForegroundColor = ConsoleOutputColor.DarkGreen, BackgroundColor = ConsoleOutputColor.NoChange }); AssertOutput(target, "The big warning message", new string[] { "The \x1B[31mbig \x1B[35mw\x1B[32ma\x1B[35mrn\x1B[31ming\x1B[0m mess\x1B[32ma\x1B[0mge\x1B[0m" }); } [Fact] public void ColoredConsoleAnsi_RepeatedWordHighlight_VerificationTest() { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}", EnableAnsiOutput = true }; target.UseDefaultRowHighlightingRules = false; target.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "big big", ForegroundColor = ConsoleOutputColor.DarkRed, BackgroundColor = ConsoleOutputColor.NoChange }); AssertOutput(target, "The big big big big warning message", new string[] { "The \x1B[31mbig big\x1B[0m \x1B[31mbig big\x1B[0m warning message\x1B[0m" }); } [Theory] [InlineData("The big warning message", "\x1B[42mThe big warning message\x1B[0m")] [InlineData("The big\r\nwarning message", "\x1B[42mThe big\x1B[0m\r\n\x1B[42mwarning message\x1B[0m")] public void ColoredConsoleAnsi_RowColor_VerificationTest(string inputText, string expectedResult) { var target = new ColoredConsoleTarget { Layout = "${message}", EnableAnsiOutput = true }; target.UseDefaultRowHighlightingRules = false; target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule() { BackgroundColor = ConsoleOutputColor.DarkGreen }); AssertOutput(target, inputText, new string[] { expectedResult }, string.Empty); } [Fact] public void ColoredConsoleAnsi_RowColorWithWordHighlight_VerificationTest() { var target = new ColoredConsoleTarget { Layout = "${message}", EnableAnsiOutput = true }; target.UseDefaultRowHighlightingRules = false; target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule() { BackgroundColor = ConsoleOutputColor.Green }); target.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "big big", ForegroundColor = ConsoleOutputColor.DarkRed, BackgroundColor = ConsoleOutputColor.NoChange }); AssertOutput(target, "The big big big big warning message", new string[] { "\x1B[102mThe \x1B[31mbig big\x1B[0m\x1B[102m \x1B[31mbig big\x1B[0m\x1B[102m warning message\x1B[0m" }, string.Empty); } /// <summary> /// With or without CompileRegex, CompileRegex is never null, even if not used when CompileRegex=false. (needed for backwards-compatibility) /// </summary> /// <param name="compileRegex"></param> [Theory] [InlineData(true)] [InlineData(false)] public void CompiledRegexPropertyNotNull(bool compileRegex) { var rule = new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Regex = "\\wat", CompileRegex = compileRegex }; Assert.NotNull(rule.CompiledRegex); } [Theory] [InlineData(true)] [InlineData(false)] public void DonRemoveIfRegexIsEmpty(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = null, IgnoreCase = true, CompileRegex = compileRegex }); AssertOutput(target, "The Cat Sat At The Bar.", new string[] { "The Cat Sat At The Bar." }); } [Fact] public void ColortedConsoleAutoFlushOnWrite() { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}", AutoFlush = true }; AssertOutput(target, "The Cat Sat At The Bar.", new string[] { "The Cat Sat At The Bar." }); } #if !MONO [Fact] public void ColoredConsoleRaceCondtionIgnoreTest() { var configXml = @" <nlog throwExceptions='true'> <targets> <target name='console' type='coloredConsole' layout='${message}' /> <target name='console2' type='coloredConsole' layout='${message}' /> <target name='console3' type='coloredConsole' layout='${message}' /> </targets> <rules> <logger name='*' minlevel='Trace' writeTo='console,console2,console3' /> </rules> </nlog>"; var success = ConsoleTargetTests.ConsoleRaceCondtionIgnoreInnerTest(configXml); Assert.True(success); } #endif #if !NET35 && !NET40 [Fact] public void ColoredConsoleDetectOutputRedirectedTest() { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}", DetectOutputRedirected = true }; AssertOutput(target, "The Cat Sat At The Bar.", new string[] { "The Cat Sat At The Bar." }); } #endif private static void AssertOutput(Target target, string message, string[] expectedParts, string loggerName = "Logger ") { var consoleOutWriter = new PartsWriter(); TextWriter oldConsoleOutWriter = Console.Out; Console.SetOut(consoleOutWriter); try { var exceptions = new List<Exception>(); target.Initialize(null); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, loggerName.Trim(), message).WithContinuation(exceptions.Add)); target.Close(); Assert.Single(exceptions); Assert.True(exceptions.TrueForAll(e => e is null)); } finally { Console.SetOut(oldConsoleOutWriter); } var expected = Enumerable.Repeat(loggerName + expectedParts[0], 1).Concat(expectedParts.Skip(1)); Assert.Equal(expected, consoleOutWriter.Values); Assert.True(consoleOutWriter.SingleWriteLine); Assert.True(consoleOutWriter.SingleFlush); } private class PartsWriter : StringWriter { public PartsWriter() { Values = new List<string>(); } public List<string> Values { get; private set; } public bool SingleWriteLine { get; private set; } public bool SingleFlush { get; private set; } public override void Write(string value) { Values.Add(value); } public override void Flush() { if (SingleFlush) { throw new InvalidOperationException("Single Flush only"); } SingleFlush = true; base.Flush(); } public override void WriteLine(string value) { if (SingleWriteLine) { Values.Clear(); throw new InvalidOperationException("Single WriteLine only"); } SingleWriteLine = true; if (!string.IsNullOrEmpty(value)) Values.Add(value); } public override void WriteLine() { if (SingleWriteLine) { Values.Clear(); throw new InvalidOperationException("Single WriteLine only"); } SingleWriteLine = true; } } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Conditions { using System; using System.Collections.Generic; using System.Text; using NLog.Internal; internal sealed class ConditionMethodExpression : ConditionExpression { private readonly IEvaluateMethod _method; public string MethodName { get; } /// <summary> /// Gets the method parameters /// </summary> public IList<ConditionExpression> MethodParameters { get; } private ConditionMethodExpression(string methodName, IList<ConditionExpression> methodParameters, IEvaluateMethod method) { MethodName = Guard.ThrowIfNull(methodName); _method = Guard.ThrowIfNull(method); MethodParameters = Guard.ThrowIfNull(methodParameters); } /// <inheritdoc /> protected override object EvaluateNode(LogEventInfo context) { return _method.EvaluateNode(context); } /// <inheritdoc/> public override string ToString() { var sb = new StringBuilder(); sb.Append(MethodName); sb.Append('('); string separator = string.Empty; foreach (var expr in MethodParameters) { sb.Append(separator); sb.Append(expr); separator = ", "; } sb.Append(')'); return sb.ToString(); } public static ConditionMethodExpression CreateMethodNoParameters(string conditionMethodName, Func<LogEventInfo, object> method) { return new ConditionMethodExpression(conditionMethodName, ArrayHelper.Empty<ConditionExpression>(), new EvaluateMethodNoParameters(method)); } public static ConditionMethodExpression CreateMethodOneParameter(string conditionMethodName, Func<LogEventInfo, object, object> method, IList<ConditionExpression> methodParameters) { var methodParameter = methodParameters[0]; return new ConditionMethodExpression(conditionMethodName, methodParameters, new EvaluateMethodOneParameter(method, (logEvent) => methodParameter.Evaluate(logEvent))); } public static ConditionMethodExpression CreateMethodTwoParameters(string conditionMethodName, Func<LogEventInfo, object, object, object> method, IList<ConditionExpression> methodParameters) { var methodParameterArg1 = methodParameters[0]; var methodParameterArg2 = methodParameters[1]; return new ConditionMethodExpression(conditionMethodName, methodParameters, new EvaluateMethodTwoParameters(method, (logEvent) => methodParameterArg1.Evaluate(logEvent), (logEvent) => methodParameterArg2.Evaluate(logEvent))); } public static ConditionMethodExpression CreateMethodThreeParameters(string conditionMethodName, Func<LogEventInfo, object, object, object, object> method, IList<ConditionExpression> methodParameters) { var methodParameterArg1 = methodParameters[0]; var methodParameterArg2 = methodParameters[1]; var methodParameterArg3 = methodParameters[2]; return new ConditionMethodExpression(conditionMethodName, methodParameters, new EvaluateMethodThreeParameters(method, (logEvent) => methodParameterArg1.Evaluate(logEvent), (logEvent) => methodParameterArg2.Evaluate(logEvent), (logEvent) => methodParameterArg3.Evaluate(logEvent))); } public static ConditionMethodExpression CreateMethodManyParameters(string conditionMethodName, Func<object[], object> method, IList<ConditionExpression> methodParameters, bool includeLogEvent) { return new ConditionMethodExpression(conditionMethodName, methodParameters, new EvaluateMethodManyParameters(method, methodParameters, includeLogEvent)); } private interface IEvaluateMethod { object EvaluateNode(LogEventInfo logEvent); } private sealed class EvaluateMethodNoParameters : IEvaluateMethod { private readonly Func<LogEventInfo, object> _method; public EvaluateMethodNoParameters(Func<LogEventInfo, object> method) { _method = Guard.ThrowIfNull(method); } public object EvaluateNode(LogEventInfo logEvent) { return _method(logEvent); } } private sealed class EvaluateMethodOneParameter : IEvaluateMethod { private readonly Func<LogEventInfo, object, object> _method; private readonly Func<LogEventInfo, object> _methodParameter; public EvaluateMethodOneParameter(Func<LogEventInfo, object, object> method, Func<LogEventInfo, object> methodParameter) { _method = Guard.ThrowIfNull(method); _methodParameter = Guard.ThrowIfNull(methodParameter); } public object EvaluateNode(LogEventInfo logEvent) { var inputParameter = _methodParameter(logEvent); return _method(logEvent, inputParameter); } } private sealed class EvaluateMethodTwoParameters : IEvaluateMethod { private readonly Func<LogEventInfo, object, object, object> _method; private readonly Func<LogEventInfo, object> _methodParameterArg1; private readonly Func<LogEventInfo, object> _methodParameterArg2; public EvaluateMethodTwoParameters(Func<LogEventInfo, object, object, object> method, Func<LogEventInfo, object> methodParameterArg1, Func<LogEventInfo, object> methodParameterArg2) { _method = Guard.ThrowIfNull(method); _methodParameterArg1 = Guard.ThrowIfNull(methodParameterArg1); _methodParameterArg2 = Guard.ThrowIfNull(methodParameterArg2); } public object EvaluateNode(LogEventInfo logEvent) { var inputParameter1 = _methodParameterArg1(logEvent); var inputParameter2 = _methodParameterArg2(logEvent); return _method(logEvent, inputParameter1, inputParameter2); } } private sealed class EvaluateMethodThreeParameters : IEvaluateMethod { private readonly Func<LogEventInfo, object, object, object, object> _method; private readonly Func<LogEventInfo, object> _methodParameterArg1; private readonly Func<LogEventInfo, object> _methodParameterArg2; private readonly Func<LogEventInfo, object> _methodParameterArg3; public EvaluateMethodThreeParameters(Func<LogEventInfo, object, object, object, object> method, Func<LogEventInfo, object> methodParameterArg1, Func<LogEventInfo, object> methodParameterArg2, Func<LogEventInfo, object> methodParameterArg3) { _method = Guard.ThrowIfNull(method); _methodParameterArg1 = Guard.ThrowIfNull(methodParameterArg1); _methodParameterArg2 = Guard.ThrowIfNull(methodParameterArg2); _methodParameterArg3 = Guard.ThrowIfNull(methodParameterArg3); } public object EvaluateNode(LogEventInfo logEvent) { var inputParameter1 = _methodParameterArg1(logEvent); var inputParameter2 = _methodParameterArg2(logEvent); var inputParameter3 = _methodParameterArg3(logEvent); return _method(logEvent, inputParameter1, inputParameter2, inputParameter3); } } private sealed class EvaluateMethodManyParameters : IEvaluateMethod { private readonly Func<object[], object> _method; private readonly IList<ConditionExpression> _methodParameters; private readonly bool _includeLogEvent; public EvaluateMethodManyParameters(Func<object[], object> method, IList<ConditionExpression> inputParameters, bool includeLogEvent) { _method = Guard.ThrowIfNull(method); _methodParameters = Guard.ThrowIfNull(inputParameters); _includeLogEvent = includeLogEvent; } public object EvaluateNode(LogEventInfo logEvent) { var parameterIndex = _includeLogEvent ? 1 : 0; var inputParameters = new object[_methodParameters.Count + parameterIndex]; if (_includeLogEvent) inputParameters[0] = logEvent; for (int i = 0; i < _methodParameters.Count; ++i) { var inputParameter = _methodParameters[i].Evaluate(logEvent); inputParameters[parameterIndex++] = inputParameter; } return _method.Invoke(inputParameters); } } } } <file_sep>See also [releases](https://github.com/NLog/NLog/releases) and [milestones](https://github.com/NLog/NLog/milestones). Date format: (year/month/day) ## Change Log ### Version 5.2.3 (2023/08/05) **Improvements** - [#5308](https://github.com/NLog/NLog/pull/5308) AutoFlushTargetWrapper - Explicit flush should also await when FlushOnConditionOnly (#5308) (@snakefoot) - [#5301](https://github.com/NLog/NLog/pull/5301) Target precalculate should only perform single IsInitialized check (#5301) (@snakefoot) - [#5300](https://github.com/NLog/NLog/pull/5300) Target precalculate should only consider relevant layouts (#5300) (@snakefoot) - [#5296](https://github.com/NLog/NLog/pull/5296) Target precalculate should handle duplicate layouts (#5296) (@snakefoot) - [#5299](https://github.com/NLog/NLog/pull/5299) MessageLayoutRenderer - Skip Flatten when simple AggregateException (#5299) (@snakefoot) - [#5298](https://github.com/NLog/NLog/pull/5298) ConfigurationItemFactory - Improve obsolete message for obsoleted factory-properties (#5298) (@snakefoot) - [#5291](https://github.com/NLog/NLog/pull/5291) Report NLog version on initial configuration assignment (#5291) (@snakefoot) - [#5290](https://github.com/NLog/NLog/pull/5290) PropertyHelper - SetPropertyFromString allow empty string for nullable-value (#5290) (@snakefoot) - [#5289](https://github.com/NLog/NLog/pull/5289) Check RequiredParameter should also validate nullable types (#5289) (@snakefoot) - [#5287](https://github.com/NLog/NLog/pull/5287) FileTarget - FilePathLayout with fixed-filename can translate to absolute path (#5287) (@snakefoot) - [#5279](https://github.com/NLog/NLog/pull/5279) FileTarget - Cleanup FileSystemWatcher correctly when ArchiveFilePatternToWatch changes (#5279) (@lavige777) - [#5281](https://github.com/NLog/NLog/pull/5281) Refactor ConditionBasedFilter when-filter to use ternary operator (#5281) (@jokoyoski) ### Version 5.2.2 (2023/07/04) **Improvements** - [#5276](https://github.com/NLog/NLog/pull/5276) ConfigurationItemFactory - Fix NullReferenceException when skipping already loaded assembly (#5276) (@snakefoot) ### Version 5.2.1 (2023/07/01) **Improvements** - [#5191](https://github.com/NLog/NLog/pull/5248) WrapperTarget - Derive Name from wrappedTarget (#5248) (@snakefoot) - [#5249](https://github.com/NLog/NLog/pull/5249) Updated obsolete warning for ConfigurationReloaded-event (#5249) (@snakefoot) - [#5251](https://github.com/NLog/NLog/pull/5251) ConfigurationItemFactory - Notify when using reflection to resolve type (#5251) (@snakefoot) - [#5253](https://github.com/NLog/NLog/pull/5253) LoggingConfigurationParser - Create list items without using reflection (#5253) (@snakefoot) - [#5254](https://github.com/NLog/NLog/pull/5254) ConfigurationItemFactory - Include ConditionExpression in registration (#5254) (@snakefoot) - [#5255](https://github.com/NLog/NLog/pull/5255) LogFactory - Obsoleted GetLogger should not throw exceptions when invalid logger-type (#5255) (@snakefoot) - [#5257](https://github.com/NLog/NLog/pull/5257) ConfigurationItemFactory - Skip assembly-loading should also check prefix-option (#5257) (@snakefoot) - [#5263](https://github.com/NLog/NLog/pull/5263) ConfigurationItemFactory - Logging assembly-prefix when loading assembly (#5263) (@snakefoot) - [#5266](https://github.com/NLog/NLog/pull/5266) ILogger - Remove irrelevant StructuredMessageTemplateAttribute (#5266) (@saltukkos) - [#5267](https://github.com/NLog/NLog/pull/5267) ILogger - Updated obsolete warning for ErrorException-method and friends (#5267) (@snakefoot) - [#5269](https://github.com/NLog/NLog/pull/5269) LoggingConfigurationParser - TryGetEnumValue should throw when invalid string-value (#5269) (@snakefoot) - [#5268](https://github.com/NLog/NLog/pull/5268) ConfigurationItemFactory - Include ConditionMethods in registration (#5268) (@snakefoot) - [#5273](https://github.com/NLog/NLog/pull/5273) TargetWithContext - Fix InternalLogger output about Object reflection needed (#5273) (@snakefoot) ### Version 5.2 (2023/05/30) **Improvements** - [#5191](https://github.com/NLog/NLog/pull/5191) ConfigurationItemFactory annotated for trimming and obsoleted CreateInstance-delegate (#5191) (@snakefoot) - [#5216](https://github.com/NLog/NLog/pull/5216) Refactor - Apply ThrowIfNull and ThrowIfNullOrEmpty (#5216) (@nih0n) ### Version 5.1.5 (2023/05/25) **Improvements** - [#5229](https://github.com/NLog/NLog/pull/5229) TargetWithContext - Fixed ScopeContext capture when multiple wrappers (#5229) (@snakefoot) - [#5227](https://github.com/NLog/NLog/pull/5227) DefaultJsonSerializer - Cache length when validating json encoding (#5227) (@snakefoot) - [#5220](https://github.com/NLog/NLog/pull/5220) FileTarget - Suppress exceptions from retrieving FileInfo.CreationTimeUtc (#5220) (@snakefoot) - [#5219](https://github.com/NLog/NLog/pull/5219) LoggingConfigurationParser - Handle adding Target without name (#5219) (@snakefoot) - [#5215](https://github.com/NLog/NLog/pull/5215) Log4jXmlEvent - Fixed removal of invalid XML chars (#5215) (@snakefoot) - [#5210](https://github.com/NLog/NLog/pull/5210) LoggingConfiguration - Expand NLog config variables for Logging Rules WriteTo (#5210) (@snakefoot) ### Version 5.1.4 (2023/04/29) **Improvements** - [#5207](https://github.com/NLog/NLog/pull/5207) FileTarget - Recover from file-deleted when same archive-folder (#5207) (@snakefoot) - [#5201](https://github.com/NLog/NLog/pull/5201) NLog.xsd schema with support for variables section (#5201) (@michaelplavnik) - [#5200](https://github.com/NLog/NLog/pull/5200) JsonLayout - Added IndentJson for pretty format (#5200) (@nih0n) - [#5197](https://github.com/NLog/NLog/pull/5197) Log4jXmlEvent - Fix dummy-Namespace when using IncludeScopeProperties (#5197) (@snakefoot) - [#5195](https://github.com/NLog/NLog/pull/5195) ConfigurationItemFactory - Handle concurrent registration with single lock (#5195) (@snakefoot) - [#5193](https://github.com/NLog/NLog/pull/5193) AsyncTaskTarget - Include task exception on completed event (#5193) (@snakefoot) - [#5186](https://github.com/NLog/NLog/pull/5186) ScopeContext - Uniform initial small array sizes (#5186) (@snakefoot) ### Version 5.1.3 (2023/03/28) **Improvements** - [#5174](https://github.com/NLog/NLog/pull/5174) LoggingRule - FinalMinLevel with Layout support (#5174) (@Aaronmsv) - [#5177](https://github.com/NLog/NLog/pull/5177) MailTarget - Added support for email message headers (#5177) (@snakefoot) - [#5175](https://github.com/NLog/NLog/pull/5175) ScopeContext - Replace rescursive lookup with enumeration (#5175) (@snakefoot) - [#5168](https://github.com/NLog/NLog/pull/5168) MethodCallTarget - Compile Method Invoke as Expression Trees (#5168) (@snakefoot) - [#5165](https://github.com/NLog/NLog/pull/5165) PaddingLayoutRendererWrapper - Avoid using Insert for reusable StringBuilder (#5165) (@snakefoot) - [#5159](https://github.com/NLog/NLog/pull/5159) Json serializer with ISpanFormattable support for decimal + double (#5168) (@snakefoot) ### Version 5.1.2 (2023/02/17) **Improvements** - [#5157](https://github.com/NLog/NLog/pull/5157) FileTarget - Archive Dynamic FileName ordering ignore case (#5157) (@snakefoot) - [#5150](https://github.com/NLog/NLog/pull/5150) EventLogTarget - EventId with LogEvent Property Lookup by default (#5150) (@snakefoot) - [#5148](https://github.com/NLog/NLog/pull/5148) ReplaceLayoutRendererWrapper - SearchFor is required, and ReplaceWith optional (#5148) (@snakefoot) - [#5146](https://github.com/NLog/NLog/pull/5146) SpecialFolderLayoutRenderer - Fallback for Windows Nano (#5146) (@snakefoot) - [#5144](https://github.com/NLog/NLog/pull/5144) NetworkTarget emit LogEventDropped event on NetworkError (#5144) (@ShadowDancer) - [#5141](https://github.com/NLog/NLog/pull/5141) AsyncTaskTarget - Dynamic wait time after TaskTimeoutSeconds has expired (#5141) (@snakefoot) - [#5140](https://github.com/NLog/NLog/pull/5140) ConfigurationItemFactory - Handle concurrent registration with single lock (#5140) (@snakefoot) ### Version 5.1.1 (2022/12/29) **Improvements** - [#5134](https://github.com/NLog/NLog/pull/5134) XmlLayout - Added Layout-option to XmlElement to match XmlAttribute (#5134) (@snakefoot) - [#5126](https://github.com/NLog/NLog/pull/5126) JsonLayout - Avoid NullReferenceException when JsonAttribute has no Layout (#5126) (@snakefoot) - [#5122](https://github.com/NLog/NLog/pull/5122) ConfigurationItemFactory - Handle concurrent registration of extensions (#5122) (@snakefoot) - [#5121](https://github.com/NLog/NLog/pull/5121) LogEventInfo with custom MessageFormatter now generates FormattedMessage upfront (#5121) (@snakefoot) - [#5118](https://github.com/NLog/NLog/pull/5118) AsyncTargetWrapper - Reduce overhead when scheduling instant background writer thread (#5118) (@snakefoot) - [#5115](https://github.com/NLog/NLog/pull/5115) ConfigurationItemFactory - Faster scan of NLog types with filter on IsPublic / IsClass (#5115) (@snakefoot) ### Version 5.1.0 (2022/11/27) **Improvements** - [#5102](https://github.com/NLog/NLog/pull/5102) MessageTemplates ValueFormatter with support for ISpanFormattable (#5102) (@snakefoot) - [#5101](https://github.com/NLog/NLog/pull/5101) Add LogEventDropped handler to the NetworkTarget (#5101) (@ShadowDancer) - [#5108](https://github.com/NLog/NLog/pull/5108) Improving InternalLogger output when adding NLog targets to configuration (#5108) (@snakefoot) - [#5110](https://github.com/NLog/NLog/pull/5110) ObjectPathRendererWrapper - Added public method TryGetPropertyValue (#5110) (@snakefoot) ### Version 5.0.5 (2022/10/26) **Improvements** - [#5092](https://github.com/NLog/NLog/pull/5092) InternalLogger - LogFile expand filepath variables (#5092) (@RyanGaudion) - [#5090](https://github.com/NLog/NLog/pull/5090) ReplaceNewLines - Support Replacement with newlines (#5090) (@Orace) - [#5086](https://github.com/NLog/NLog/pull/5086) ScopeIndent LayoutRenderer (#5086) (@snakefoot) - [#5085](https://github.com/NLog/NLog/pull/5085) Introduced TriLetter as LevelFormat (Trc, Dbg, Inf, Wrn, Err, Ftl) (#5085) (@snakefoot) - [#5078](https://github.com/NLog/NLog/pull/5078) LogFactory.Setup - Added support for RegisterLayout and validate NLog types (#5078) (@snakefoot) - [#5076](https://github.com/NLog/NLog/pull/5076) AutoFlushTargetWrapper - Fix race-condition that makes unit-tests unstable (#5076) (@snakefoot) - [#5073](https://github.com/NLog/NLog/pull/5073) Include error-message from inner-exception when layout contains unknown layoutrenderer (#5073) (@snakefoot) - [#5065](https://github.com/NLog/NLog/pull/5065) ObjectReflectionCache - Skip serializing System.Net.IPAddress (#5065) (@snakefoot) - [#5060](https://github.com/NLog/NLog/pull/5060) ObjectReflectionCache - Skip reflection of delegate-objects (#5060) (@snakefoot) - [#5057](https://github.com/NLog/NLog/pull/5057) OnException + OnHasProperties - Added Else-option (#5057) (@snakefoot) - [#5056](https://github.com/NLog/NLog/pull/5056) LogEventBuilder - Added Log(Type wrapperType) for custom Logger wrapper (#5056) (@snakefoot) ### Version 5.0.4 (2022/09/01) **Fixes** - [#5051](https://github.com/NLog/NLog/pull/5051) Fixed embedded resource with ILLink.Descriptors.xml to avoid IL2007 (#5051) (@snakefoot) ### Version 5.0.3 (2022/09/01) **Improvements** - [#5034](https://github.com/NLog/NLog/pull/5034) Added embedded resource with ILLink.Descriptors.xml to skip AOT (#5034) (@snakefoot) - [#5035](https://github.com/NLog/NLog/pull/5035) Layout Typed that can handle LogEventInfo is null (#5035) (@snakefoot) - [#5036](https://github.com/NLog/NLog/pull/5036) JsonLayout - Fix output for Attributes with IncludeEmptyValue=false and Encode=false (#5036) (@snakefoot) ### Version 5.0.2 (2022/08/12) **Improvements** - [#5019](https://github.com/NLog/NLog/pull/5019) Layout Typed validates fixed values upfront at config initialization, instead of when logging (#5019) (@snakefoot) - [#5026](https://github.com/NLog/NLog/pull/5026) Removed obsolete dependency Microsoft.Extensions.PlatformAbstractions (#5026) (@snakefoot) - [#5016](https://github.com/NLog/NLog/pull/5016) WebServiceTarget - Verifies Url as RequiredParameter (#5016) (@snakefoot) - [#5014](https://github.com/NLog/NLog/pull/5014) WebServiceTarget - Improve InternalLogging when Url is invalid (#5014) (@snakefoot) - [#5010](https://github.com/NLog/NLog/pull/5010) GlobalDiagnosticsContext - Implicit caching of value lookup (#5010) (@snakefoot) - [#5004](https://github.com/NLog/NLog/pull/5004) EventLogTarget - Bump default MaxMessageLength to 30000 to match limit in Win2008 (#5004) (@snakefoot) - [#4995](https://github.com/NLog/NLog/pull/4995) Support UniversalTime = false when NLog time-source is UTC (#4995) (@snakefoot) - [#4987](https://github.com/NLog/NLog/pull/4987) ConfigurationItemFactory - Include original type-alias when CreateInstance fails (#4987) (@snakefoot) - [#4981](https://github.com/NLog/NLog/pull/4981) AssemblyVersionLayoutRenderer - Support override of Default value (#4981) (@snakefoot) - [#4976](https://github.com/NLog/NLog/pull/4976) LoggingConfiguration - AddRule with overload for LoggingRule object (#4976) (@tvogel-nid) ### Version 5.0.1 (2022/06/12) **Improvements** - [#4938](https://github.com/NLog/NLog/pull/4938) LoggingConfigurationParser should alert when LoggingRule filters are bad (#4938) (@snakefoot) - [#4940](https://github.com/NLog/NLog/pull/4940) CompoundLayout with layout from config variable (#4940) (@snakefoot) - [#4944](https://github.com/NLog/NLog/pull/4944) Mark Target LayoutWithLock as obsolete, since only temporary workaround (#4944) (@snakefoot) - [#4950](https://github.com/NLog/NLog/pull/4950) FileTarget - First acquire file-handle to compress before creating zip-file (#4950) (@snakefoot) - [#4953](https://github.com/NLog/NLog/pull/4953) FileTarget - Zip compression should not truncate when zip-file already exists (#4953) (@snakefoot) - [#4965](https://github.com/NLog/NLog/pull/4965) Max StackTraceUsage should be computed using bitwise OR (#4965) (@martinzding) - [#4963](https://github.com/NLog/NLog/pull/4963) Improved source-code documentation by fixing spelling errors (#4963) (@KurnakovMaksim) ### Version 5.0.0 (2022/05/16) See [List of major changes in NLog 5.0](https://nlog-project.org/2021/08/25/nlog-5-0-preview1-ready.html). **Improvements** - [#4922](https://github.com/NLog/NLog/pull/4922) NetworkTarget - Dual Mode IPv4 mapped addresses over IPv6 (#4922) (@snakefoot) - [#4895](https://github.com/NLog/NLog/pull/4895) LogManager.Setup().LoadConfigurationFromAssemblyResource() can load config from embedded resource (#4895) (@snakefoot) - [#4893](https://github.com/NLog/NLog/pull/4893) NetworkTarget - Reduce memory allocations in UdpNetworkSender (#4893) (@snakefoot) - [#4891](https://github.com/NLog/NLog/pull/4891) + [#4924](https://github.com/NLog/NLog/pull/4924) Log4JXmlEventLayoutRenderer - IncludeEventProperties default = true (#4891 + #4924) (@snakefoot) - [#4887](https://github.com/NLog/NLog/pull/4887) NetworkTarget - Support Compress = GZip for UDP with GELF to GrayLog (#4887) (@snakefoot) - [#4882](https://github.com/NLog/NLog/pull/4882) Updated dependencies for NetStandard1.x to fix warnings (#4882) (@snakefoot) - [#4877](https://github.com/NLog/NLog/pull/4877) CounterLayoutRenderer - Support 64 bit integer and raw value (#4877) (@snakefoot) - [#4867](https://github.com/NLog/NLog/pull/4867) WindowsIdentityLayoutRenderer - Dispose WindowsIdentity after use (#4867) (@snakefoot) - [#4863](https://github.com/NLog/NLog/pull/4863) + [#4868](https://github.com/NLog/NLog/pull/4868) Support SpecialFolder UserApplicationDataDir for internalLogFile when parsing nlog.config (#4863 + #4868) (@snakefoot) - [#4859](https://github.com/NLog/NLog/pull/4859) RetryingTargetWrapper - Changed RetryCount and RetryDelay to typed Layout (#4859) (@snakefoot) - [#4858](https://github.com/NLog/NLog/pull/4858) BufferingTargetWrapper - Changed BufferSize + FlushTimeout to typed Layout (#4858) (@snakefoot) - [#4857](https://github.com/NLog/NLog/pull/4857) LimitingTargetWrapper - Changed MessageLimit + Interval to typed Layout (#4857) (@snakefoot) - [#4838](https://github.com/NLog/NLog/pull/4838) Added various null checks to improve code quality (#4838) (@KurnakovMaksim) - [#4835](https://github.com/NLog/NLog/pull/4835) Fixed missing initialization of layout-parameters for ConditionMethodExpression (#4835) (@snakefoot) - [#4824](https://github.com/NLog/NLog/pull/4824) LogFactory - Avoid checking candidate NLog-config files for every Logger created (#4824) (@snakefoot) - [#4823](https://github.com/NLog/NLog/pull/4823) Improve InternalLogger output when testing candidate config file locations (#4823) (@snakefoot) - [#4819](https://github.com/NLog/NLog/pull/4819) Improve loading of AppName.exe.nlog with .NET6 single file publish (#4819) (@snakefoot) - [#4812](https://github.com/NLog/NLog/pull/4812) Translate ConditionParseException into NLogConfigurationException (#4812) (@snakefoot) - [#4809](https://github.com/NLog/NLog/pull/4809) NLogConfigurationException - Improve styling of error-message when failing to assign property (#4809) (@snakefoot) - [#4808](https://github.com/NLog/NLog/pull/4808) NLogRuntimeException constructor with string.Format marked obsolete (#4808) (@snakefoot) - [#4807](https://github.com/NLog/NLog/pull/4807) NLogConfigurationException constructor with string.Format marked obsolete (#4807) (@snakefoot) - [#4789](https://github.com/NLog/NLog/pull/4789) FallbackGroupTarget - Improve InternalLogger output when no more fallback (#4789) (@snakefoot) - [#4788](https://github.com/NLog/NLog/pull/4788) NetworkTarget - Report to InternalLogger at Debug-level when discarding huge LogEvents (#4788) (@snakefoot) - [#4787](https://github.com/NLog/NLog/pull/4787) Added extra JetBrains Annotations with StructuredMessageTemplateAttribute (#4787) (@snakefoot) - [#4785](https://github.com/NLog/NLog/pull/4785) Improve InternalLogger output for unnamed nested wrapper targets (#4785) (@snakefoot) - [#4784](https://github.com/NLog/NLog/pull/4784) Improve InternalLogger output for named nested wrapper targets (#4784) (@snakefoot) - [#4777](https://github.com/NLog/NLog/pull/4777) DatabaseTarget - Removed alias DB to avoid promoting acronyms (#4777) (@snakefoot) - [#4776](https://github.com/NLog/NLog/pull/4776) LoggingRule - Allow FinalMinLevel to override previous rules (#4776) (@snakefoot) - [#4775](https://github.com/NLog/NLog/pull/4775) InternalLogger IncludeTimestamp = true by default to restore original behavior (#4775) (@snakefoot) - [#4773](https://github.com/NLog/NLog/pull/4773) Fix xml-docs and replaced broken link config.html with wiki-link (#4773) (@snakefoot) - [#4772](https://github.com/NLog/NLog/pull/4772) Improve InternalLogger output when queue OnOverflow (#4772) (@snakefoot) - [#4770](https://github.com/NLog/NLog/pull/4770) LogFactory DefaultCultureInfo-setter should also update active config (#4770) (@snakefoot) ### Version 5.0-RC2 (2022/01/19) **Features** - [#4761](https://github.com/NLog/NLog/pull/4761) LogFactory fluent Setup with AddCallSiteHiddenAssembly (#4761) (@snakefoot) - [#4757](https://github.com/NLog/NLog/pull/4757) Updated JetBrains Annotations with StructuredMessageTemplateAttribute (#4757) (@snakefoot) - [#4754](https://github.com/NLog/NLog/pull/4754) JsonArrayLayout - Render LogEvent in Json-Array format (#4754) (@snakefoot) - [#4613](https://github.com/NLog/NLog/pull/4613) Added LogFactory.ReconfigureExistingLoggers with purgeObsoleteLoggers option (#4613) (@sjafarianm) - [#4711](https://github.com/NLog/NLog/pull/4711) Added WithProperties-method for Logger-class (#4711) (@simoneserra93) **Improvements** - [#4730](https://github.com/NLog/NLog/pull/4730) MemoryTarget - Updated to implement TargetWithLayoutHeaderAndFooter (#4730) (@snakefoot) - [#4730](https://github.com/NLog/NLog/pull/4730) TraceTarget - Updated to implement TargetWithLayoutHeaderAndFooter (#4730) (@snakefoot) - [#4717](https://github.com/NLog/NLog/pull/4717) DatabaseTarget - Improved parsing of DbType (#4717) (@Orace) ### Version 5.0-RC1 (2021/12/20) **Features** - [#4662](https://github.com/NLog/NLog/pull/4662) LogFactory Setup fluent with SetupLogFactory for general options (#4662) (@snakefoot) - [#4648](https://github.com/NLog/NLog/pull/4648) LogFactory fluent Setup with FilterDynamicIgnore + FilterDynamicLog (#4648) (@snakefoot) - [#4642](https://github.com/NLog/NLog/pull/4642) TargetWithContext - Added support for ExcludeProperties (#4642) (@snakefoot) **Improvements** - [#4656](https://github.com/NLog/NLog/pull/4656) FallbackGroupTarget - Added support for EnableBatchWrite (#4656) (@snakefoot) - [#4655](https://github.com/NLog/NLog/pull/4655) JsonLayout - ExcludeProperties should also handle IncludeScopeProperties (#4655) (@snakefoot) - [#4645](https://github.com/NLog/NLog/pull/4645) TargetWithContext - IncludeEmptyValue false by default (#4645) (@snakefoot) - [#4646](https://github.com/NLog/NLog/pull/4646) PropertiesDictionary - Generate unique message-template-names on duplicate keys (#4646) (@snakefoot) - [#4661](https://github.com/NLog/NLog/pull/4661) LoggingRule - Fix XML documentation (#4661) (@GitHubPang) - [#4671](https://github.com/NLog/NLog/pull/4671) Fixed RegisterObjectTransformation to handle conversion to simple values (#4671) (@snakefoot) - [#4669](https://github.com/NLog/NLog/pull/4669) LogLevel - Replaced IConvertible with IFormattable for better Json output (#4669) (@snakefoot) - [#4676](https://github.com/NLog/NLog/pull/4676) NLog.Wcf - Updated nuget dependencies to System.ServiceModel ver. 4.4.4 (#4676) (@snakefoot) - [#4675](https://github.com/NLog/NLog/pull/4675) FileTarget - Improve fallback logic when running on Linux without File BirthTIme (#4675) (@snakefoot) - [#4680](https://github.com/NLog/NLog/pull/4680) FileTarget - Better handling of relative paths with FileSystemWatcher (#4680) (@snakefoot) - [#4689](https://github.com/NLog/NLog/pull/4689) Renamed AppSettingLayoutRenderer2 to AppSettingLayoutRenderer after removing NLog.Extended (#4689) (@snakefoot) - [#4563](https://github.com/NLog/NLog/pull/4563) Added alias ToUpper and ToLower as alternative to UpperCase and LowerCase (#4563) (@snakefoot) - [#4695](https://github.com/NLog/NLog/pull/4695) Ignore dash (-) when parsing layouts, layoutrenderers and targets (#4695) (@304NotModified) - [#4713](https://github.com/NLog/NLog/pull/4713) Logger SetProperty marked as obsolete, instead use WithProperty or the unsafe Properties-property (#4713) (@snakefoot) - [#4714](https://github.com/NLog/NLog/pull/4714) Hide obsolete methods from intellisense (#4714) (@snakefoot) **Performance** - [#4672](https://github.com/NLog/NLog/pull/4672) PaddingLayoutRendererWrapper - Pad operation with reduced string allocation (#4672) (@snakefoot) - [#4698](https://github.com/NLog/NLog/pull/4698) FileTarget - Use Environment.TickCount to trigger File.Exists checks (#4698) (@snakefoot) - [#4699](https://github.com/NLog/NLog/pull/4699) AsyncTargetWrapper - Fix performance for OverflowAction Block on NetCore (#4699) (@snakefoot) - [#4705](https://github.com/NLog/NLog/pull/4705) LogEventInfo - Faster clone of messageTemplateParameters by caching Count (#4705) (@snakefoot) ### Version 5.0-Preview 3 (2021/10/26) **Fixes** - [#4627](https://github.com/NLog/NLog/pull/4627) PropertiesDictionary - Fixed threading issue in EventProperties (#4627) (@snakefoot) **Features** - [#4598](https://github.com/NLog/NLog/pull/4598) LogFactory fluent Setup with WriteToTrace + WriteToDebug (#4598) (@snakefoot) - [#4628](https://github.com/NLog/NLog/pull/4628) LogEventInfo constructor with eventProperties as IReadOnlyList (#4628) (@snakefoot) - [#4633](https://github.com/NLog/NLog/pull/4633) ${event-properties} now ignore case when doing property lookup (#4633) (@snakefoot) **Improvements** - [#4623](https://github.com/NLog/NLog/pull/4623) FileTarget - KeepFileOpen = true by default to avoid loosing file handle (#4623) (@snakefoot) - [#4624](https://github.com/NLog/NLog/pull/4624) FileTarget - Only enable FileSystemWatcher when ConcurrentWrites = true (#4624) (@snakefoot) - [#4634](https://github.com/NLog/NLog/pull/4634) FileTarget - Attempt to write footer, before closing file appender (#4634) (@snakefoot) - [#4632](https://github.com/NLog/NLog/pull/4632) JsonSerializeOptions - Marked Format + FormatProvider + QuoteKeys as obsolete (#4632) (@snakefoot) - [#4622](https://github.com/NLog/NLog/pull/4622) Handle OutOfMemoryException instead of crashing the application (#4622) (@snakefoot) - [#4605](https://github.com/NLog/NLog/pull/4605) Removed DefaultValue-attribute as it is only used for docs-generator (#4605) (@snakefoot) - [#4606](https://github.com/NLog/NLog/pull/4606) Removed Advanced-attribute as it has no meaning (#4606) (@snakefoot) ### Version 5.0-Preview 2 (2021/10/02) **Fixes** - [#4533](https://github.com/NLog/NLog/pull/4533) Fixed validation of nlog-element when using include-files (#4533) (@snakefoot) - [#4555](https://github.com/NLog/NLog/pull/4555) Fixed validation of nlog-element when nested within configuration-element (#4555) (@snakefoot) **Features** - [#4542](https://github.com/NLog/NLog/pull/4542) NetworkTarget - Added OnQueueOverflow with default Discard (#4542) (@snakefoot) **Improvements** - [#4544](https://github.com/NLog/NLog/pull/4544) ScopeContext - Renamed IncludeScopeNestedStates to IncludeScopeNested for consistency (#4544) (@snakefoot) - [#4545](https://github.com/NLog/NLog/pull/4545) ScopeContext - Renamed PushScopeState to PushScopeNested for consistency (#4545) (@snakefoot) - [#4556](https://github.com/NLog/NLog/pull/4556) NetworkTarget - Explicit assigning LineEnding activates NewLine automatically (#4556) (@snakefoot) - [#4549](https://github.com/NLog/NLog/pull/4549) NetworkTarget - UdpNetworkSender changed to QueuedNetworkSender with correct message split (#4549) (@snakefoot) - [#4542](https://github.com/NLog/NLog/pull/4542) NetworkTarget - Changed OnConnectionOverflow to discard by default (#4542) (@snakefoot) - [#4564](https://github.com/NLog/NLog/pull/4564) Fixed LayoutParser so Typed Layout works for LayoutRenderer (#4564) (@snakefoot) - [#4580](https://github.com/NLog/NLog/pull/4580) LayoutRenderer and Layout are now always threadsafe by default (#4580) (@snakefoot) - [#4586](https://github.com/NLog/NLog/pull/4586) ScopeTiming - No Format specified renders TimeSpan.TotalMilliseconds (#4586) (@snakefoot) - [#4583](https://github.com/NLog/NLog/pull/4583) ExceptionLayoutRenderer - Separator with basic layout support (#4583) (@snakefoot) - [#4588](https://github.com/NLog/NLog/pull/4588) StackTraceLayoutRenderer - Separator with basic layout support (#4588) (@snakefoot) - [#4589](https://github.com/NLog/NLog/pull/4589) ScopeNestedLayoutRenderer - Separator with basic layout support (#4589) (@snakefoot) ### Version 5.0-Preview 1 (2021/08/25) See NLog 5 release post: https://nlog-project.org/2021/08/25/nlog-5-0-preview1-ready.html - [Breaking Changes](https://github.com/NLog/NLog/pulls?q=is%3Apr+label%3A%22breaking%20change%22+is%3Amerged+milestone:%225.0%20%28new%29%22) - [Breaking Behavior Changes](https://github.com/NLog/NLog/pulls?q=is%3Apr+label%3A%22breaking%20behavior%20change%22+is%3Amerged+milestone:%225.0%20%28new%29%22) - [Features](https://github.com/NLog/NLog/pulls?q=is%3Apr+label%3A%22Feature%22+is%3Amerged+milestone:%225.0%20%28new%29%22) - [Improvements](https://github.com/NLog/NLog/pulls?q=is%3Apr+label%3A%22Enhancement%22+is%3Amerged+milestone:%225.0%20%28new%29%22) - [Performance](https://github.com/NLog/NLog/pulls?q=is%3Apr+label%3A%22Performance%22+is%3Amerged+milestone:%225.0%20%28new%29%22) ### Version 4.7.15 (2022/03/26) **Improvements** - [#4836](https://github.com/NLog/NLog/pull/4836) Fixed missing initialization of layout-parameters for ConditionMethodExpression (#4836) (@snakefoot) - [#4821](https://github.com/NLog/NLog/pull/4821) LogEventInfo - Optimize copy messageTemplateParameters by caching Count (#4821) (@snakefoot) - [#4820](https://github.com/NLog/NLog/pull/4820) Improve loading of AppName.exe.nlog with .NET6 single file publish (#4820) (@snakefoot) - [#4806](https://github.com/NLog/NLog/pull/4806) NLogConfigurationException - Skip string.Format when no args (#4806) (@snakefoot) ### Version 4.7.14 (2022/02/22) **Improvements** - [#4799](https://github.com/NLog/NLog/pull/4799) Added IncludeEventProperties + IncludeScopeProperties to improve transition (#4799) (@snakefoot) - [#4786](https://github.com/NLog/NLog/pull/4786) Refactored code to remove false positives from code analysis (#4786) (@snakefoot) ### Version 4.7.13 (2021/12/05) **Fixes** - [#4700](https://github.com/NLog/NLog/pull/4700) AsyncTargetWrapper - Fix performance for OverflowAction Block on NetCore (#4700) (@snakefoot) - [#4644](https://github.com/NLog/NLog/pull/4644) AsyncTargetWrapper - Swallow OutOfMemoryException instead of crashing (#4644) (@snakefoot) **Improvements** - [#4649](https://github.com/NLog/NLog/pull/4649) Fix broken XML doc comment (#4649) (@GitHubPang) ### Version 4.7.12 (2021/10/24) **Fixes** - [#4627](https://github.com/NLog/NLog/pull/4627) PropertiesDictionary - Fixed threading issue in EventProperties (#4627) (@snakefoot) - [#4631](https://github.com/NLog/NLog/pull/4631) FileTarget - Failing to CleanupInitializedFiles should not stop logging (#4631) (@snakefoot) **Features** - [#4629](https://github.com/NLog/NLog/pull/4629) LogEventInfo constructor with eventProperties as IReadOnlyList (#4629) (@snakefoot) ### Version 4.7.11 (2021/08/18) **Fixes** - [#4519](https://github.com/NLog/NLog/pull/4519) JsonSerializer - Fix CultureNotFoundException with Globalization Invariant Mode (#4519) (@snakefoot) **Features** - [#4475](https://github.com/NLog/NLog/pull/4475) WebServiceTarget - Added support for assigning UserAgent-Header (#4475) (@snakefoot) ### Version 4.7.10 (2021/05/14) **Fixes** - [#4401](https://github.com/NLog/NLog/pull/4401) JsonSerializer - Fixed bug when handling custom IConvertible returning TypeCode.Empty (#4401) (@snakefoot) **Improvements** - [#4391](https://github.com/NLog/NLog/pull/4391) Support TargetDefaultParameters and TargetDefaultWrapper (#4391) (@snakefoot) - [#4403](https://github.com/NLog/NLog/pull/4403) JsonLayout - Apply EscapeForwardSlash for LogEventInfo.Properties (#4403) (@snakefoot) - [#4393](https://github.com/NLog/NLog/pull/4393) NLog.Config package: Updated hyperlink (#4393) (@snakefoot) ### Version 4.7.9 (2021/03/24) **Fixes** - [#4349](https://github.com/NLog/NLog/pull/4349) Fixed TrimDirectorySeparators to not use the root-path on Linux (#4349) (@snakefoot) - [#4353](https://github.com/NLog/NLog/pull/4353) Fixed FileTarget archive cleanup within same folder at startup (#4353) (@snakefoot) - [#4352](https://github.com/NLog/NLog/pull/4352) Fixed FileTarget archive cleanup when using short filename (#4352) (@snakefoot) **Improvements** - [#4326](https://github.com/NLog/NLog/pull/4326) Make it possible to extend the FuncLayoutRenderer (#4326) (@304NotModified) - [#4369](https://github.com/NLog/NLog/pull/4369) + [#4375](https://github.com/NLog/NLog/pull/4375) LoggingConfigurationParser - Recognize LoggingRule.FilterDefaultAction (#4369 + #4375) (@snakefoot) **Performance** - [#4337](https://github.com/NLog/NLog/pull/4337) JsonLayout - Avoid constant string-escape of JsonAttribute Name-property (#4337) (@snakefoot) ### Version 4.7.8 (2021/02/25) **Fixes** - [#4316](https://github.com/NLog/NLog/pull/4316) Fix TrimDirectorySeparators to handle root-path on Windows and Linux to load Nlog.config from root-path (#4316) (@snakefoot) **Improvements** - [#4273](https://github.com/NLog/NLog/pull/4273) Handle Breaking change with string.IndexOf(string) in .NET 5 (#4273) (@snakefoot) - [#4301](https://github.com/NLog/NLog/pull/4301) Update docs, remove ArrayList in docs (#4301) (@304NotModified) ### Version 4.7.7 (2021/01/20) **Fixes** - [#4229](https://github.com/NLog/NLog/pull/4229) Skip lookup MainModule.FileName on Android platform to avoid crash (#4229) (@snakefoot) - [#4202](https://github.com/NLog/NLog/pull/4202) JsonLayout - Generate correct json for keys that contain quote (#4202) (@virgilp) - [#4245](https://github.com/NLog/NLog/pull/4245) JsonLayout - Unwind after invalid property value to avoid invalid Json (#4245) (@snakefoot) **Improvements** - [#4222](https://github.com/NLog/NLog/pull/4222) Better handling of low memory (#4222) (@snakefoot) - [#4221](https://github.com/NLog/NLog/pull/4221) JsonLayout - Added new ExcludeEmptyProperties to skip GDC/MDC/MLDC properties with null or empty values (#4221) (@pruiz) **Performance** - [#4207](https://github.com/NLog/NLog/pull/4207) Skip allocation of SingleCallContinuation when ThrowExceptions = false (#4207) (@snakefoot) ### Version 4.7.6 (2020/12/06) **Fixes** - [#4142](https://github.com/NLog/NLog/pull/4142) JsonSerializer - Ensure invariant formatting of DateTimeOffset (#4142) (@snakefoot) - [#4172](https://github.com/NLog/NLog/pull/4172) AsyncTaskTarget - Flush when buffer is full should not block forever (#4172) (@snakefoot) - [#4182](https://github.com/NLog/NLog/pull/4182) Failing to lookup ProcessName because of Access Denied should fallback to Win32-API (#4182) (@snakefoot) **Features** - [#4153](https://github.com/NLog/NLog/pull/4153) ExceptionLayoutRenderer - Added FlattenException option (#4153) (@snakefoot) **Improvements** - [#4141](https://github.com/NLog/NLog/pull/4141) NetworkTarget - Improve handling of synchronous exceptions from UdpClient.SendAsync (#4141) (@snakefoot) - [#4176](https://github.com/NLog/NLog/pull/4176) AsyncTaskTarget - Include TaskScheduler in ContinueWith (#4176) (@snakefoot) - [#4190](https://github.com/NLog/NLog/pull/4190) Improving debugger-display for Logger.Properties and LogEventInfo.Properties (@snakefoot) **Performance** - [#4132](https://github.com/NLog/NLog/pull/4132) Improve thread concurrency when using wrapper cached=true (#4132) (@snakefoot) - [#4171](https://github.com/NLog/NLog/pull/4171) ConditionLayoutExpression - Skip allocating StringBuilder for every condition check (#4171) (@snakefoot) ### Version 4.7.5 (2020/09/27) **Fixes** - [#4106](https://github.com/NLog/NLog/pull/4106) FileTarget - New current file should write start header, when archive operation is performed on previous file (#4106) (@snakefoot) **Improvements** - [#4102](https://github.com/NLog/NLog/pull/4102) LoggingConfiguration - ValidateConfig should only throw when enabled (#4102) (@snakefoot) - [#4114](https://github.com/NLog/NLog/pull/4114) Fix VerificationException Operation could destabilize the runtime (#4114) (@snakefoot) **Performance** - [#4115](https://github.com/NLog/NLog/pull/4115) Removed EmptyDefaultDictionary from MappedDiagnosticsContext (#4115) (@snakefoot) **Other** - [#4109](https://github.com/NLog/NLog/pull/4109) Fix root .editorconfig to use end_of_line = CRLF. Remove local .editorconfig (#4109) (@snakefoot) - [#4097](https://github.com/NLog/NLog/pull/4097) Improve docs (#4097) (@304NotModified) ### Version 4.7.4 (2020/08/22) **Features** - [#4076](https://github.com/NLog/NLog/pull/4076) DatabaseTarget - Added AllowDbNull for easier support for nullable parameters (#4076) (@snakefoot) **Fixes** - [#4069](https://github.com/NLog/NLog/pull/4069) Fluent LogBuilder should suppress exception on invalid callerFilePath (#4069) (@snakefoot) **Improvements** - [#4073](https://github.com/NLog/NLog/pull/4073) FileTarget - Extra validation of the LogEvent-timestamp before checking time to archive (#4073) (@snakefoot) - [#4068](https://github.com/NLog/NLog/pull/4068) FileTarget - Improve diagnostic logging to see reason for archiving (@snakefoot) ### Version 4.7.3 (2020/07/31) **Features** - [#4017](https://github.com/NLog/NLog/pull/4017) Allow to change the RuleName of a LoggingRule (#4017) (@304NotModified) - [#3974](https://github.com/NLog/NLog/pull/3974) logging of AggregrateException.Data to prevent it from losing it after Flatten call (#3974) (@chaos0307) **Fixes** - [#4011](https://github.com/NLog/NLog/pull/4011) LocalIpAddressLayoutRenderer - IsDnsEligible and PrefixOrigin throws PlatformNotSupportedException on Linux (#4011) (@snakefoot) **Improvements** - [#4057](https://github.com/NLog/NLog/pull/4057) ObjectReflectionCache - Reduce noise from properties that throws exceptions like Stream.ReadTimeout (#4057) (@snakefoot) - [#4053](https://github.com/NLog/NLog/pull/4053) MessageTemplates - Changed Literal.Skip to be Int32 to support message templates longer than short.MaxValue (#4053) (@snakefoot) - [#4043](https://github.com/NLog/NLog/pull/4043) ObjectReflectionCache - Skip reflection for Stream objects (#4043) (@snakefoot) - [#3999](https://github.com/NLog/NLog/pull/3999) LogFactory Shutdown is public so it can be used from NLogLoggerProvider (#3999) (@snakefoot) - [#3972](https://github.com/NLog/NLog/pull/3972) Editor config with File header template (#3972) (@304NotModified) **Performance** - [#4058](https://github.com/NLog/NLog/pull/4058) FileTarget - Skip delegate capture in GetFileCreationTimeSource. Fallback only necessary when appender has been closed. (#4058) (@snakefoot) - [#4021](https://github.com/NLog/NLog/pull/4021) ObjectReflectionCache - Reduce initial memory allocation until needed (#4021) (@snakefoot) - [#3977](https://github.com/NLog/NLog/pull/3977) FilteringTargetWrapper - Remove delegate allocation (#3977) (@snakefoot) ### Version 4.7.2 (2020/05/18) **Fixes** - [#3969](https://github.com/NLog/NLog/pull/3969) FileTarget - ArchiveOldFileOnStartup not working together with ArchiveAboveSize (@snakefoot) **Improvements** - [#3962](https://github.com/NLog/NLog/pull/3962) XSD: Added Enabled attribute for <logger> (@304NotModified) ### Version 4.7.1 (2020/05/15) **Features** - [#3871](https://github.com/NLog/NLog/pull/3871) LogManager.Setup().LoadConfigurationFromFile("NLog.config") added to fluent setup (@snakefoot + @304NotModified) - [#3909](https://github.com/NLog/NLog/pull/3909) LogManager.Setup().GetCurrentClassLogger() added to fluent setup (@snakefoot + @304NotModified) - [#3861](https://github.com/NLog/NLog/pull/3861) LogManager.Setup().SetupInternalLogger(s => s.AddLogSubscription()) added to fluent setup (@snakefoot + @304NotModified) - [#3891](https://github.com/NLog/NLog/pull/3891) ColoredConsoleTarget - Added Condition option to control when to do word-highlight (@snakefoot) - [#3915](https://github.com/NLog/NLog/pull/3915) Added new option CaptureStackTrace to ${stacktrace} and ${callsite} to skip implicit capture by Logger (@snakefoot) - [#3940](https://github.com/NLog/NLog/pull/3940) Exception-LayoutRenderer with new option BaseException for rendering innermost exception (@snakefoot) **Improvements** - [#3857](https://github.com/NLog/NLog/pull/3857) FileTarget - Batch write to filestream in max chunksize of 100 times BufferSize (@snakefoot) - [#3867](https://github.com/NLog/NLog/pull/3867) InternalLogger include whether NLog comes from GlobalAssemblyCache when logging NLog version (@snakefoot) - [#3862](https://github.com/NLog/NLog/pull/3862) InternalLogger LogToFile now support ${processdir} to improve support for single-file-publish (@snakefoot) - [#3877](https://github.com/NLog/NLog/pull/3877) Added ${processdir} that matches ${basedir:processDir=true} for consistency with InternalLogger (@snakefoot) - [#3881](https://github.com/NLog/NLog/pull/3881) Object property reflection now support IReadOnlyDictionary as expando object (@snakefoot) - [#3884](https://github.com/NLog/NLog/pull/3884) InternalLogger include more details like FilePath when loading NLog.config file (@snakefoot) - [#3895](https://github.com/NLog/NLog/pull/3895) Added support for Nullable when doing conversion of property types (@304NotModified) - [#3896](https://github.com/NLog/NLog/pull/3896) InternalLogger Warnings when skipping unrecognized LayoutRenderer options (@snakefoot) - [#3901](https://github.com/NLog/NLog/pull/3901) MappedDiagnosticsLogicalContext - SetScoped with IReadOnlyList also for Xamarin (@snakefoot) - [#3904](https://github.com/NLog/NLog/pull/3904) Object property reflection automatically performs ToString for System.Reflection.Module (@snakefoot) - [#3921](https://github.com/NLog/NLog/pull/3921) Improve ${basedir:fixtempdir=true} to work better on Linux when TMPDIR not set (@snakefoot) - [#3928](https://github.com/NLog/NLog/pull/3928) NetworkTarget respect MaxQueueSize for http- / https-protocol (@snakefoot) - [#3930](https://github.com/NLog/NLog/pull/3930) LogFactory.LoadConfiguration() reports searched paths when throwing FileNotFoundException (@304NotModified) - [#3949](https://github.com/NLog/NLog/pull/3949) ReplaceNewLines-LayoutRenderer will also remove windows newlines on the Linux platform (@Silvenga) **Fixes** - [#3868](https://github.com/NLog/NLog/pull/3868) SplitGroup Target Wrapper should not skip remaining targets when single target fails (@snakefoot) - [#3918](https://github.com/NLog/NLog/pull/3918) ColoredConsoleTarget - Fix bug in handling of newlines without word-highlight (@snakefoot) - [#3941](https://github.com/NLog/NLog/pull/3941) ${processid} will no longer fail because unable to lookup ${processdir} on Mono Android (@snakefoot) **Performance** - [#3855](https://github.com/NLog/NLog/pull/3855) FileTarget - Skip checking file-length when only using ArchiveEvery (@snakefoot) - [#3898](https://github.com/NLog/NLog/pull/3898) ObjectGraphScanner performs caching of property reflection for NLog config items (@snakefoot) - [#3894](https://github.com/NLog/NLog/pull/3894) Condition expressions now handles operator like '==' without memory boxing (@snakefoot) - [#3903](https://github.com/NLog/NLog/pull/3903) ObjectGraphScanner should only check for layout-attributes on Layouts and LayoutRenderers (@snakefoot) - [#3902](https://github.com/NLog/NLog/pull/3902) MessageTemplate parsing of properties skips unnecessary array allocation (@snakefoot) ### Version 4.7 (2020/03/20) **Features** - [#3686](https://github.com/NLog/NLog/pull/3686) + [#3740](https://github.com/NLog/NLog/pull/3740) LogManager.Setup() allows fluent configuration of LogFactory options (@snakefoot + @304NotModified) - [#3610](https://github.com/NLog/NLog/pull/3610) LogManager.Setup().SetupSerialization(s => s.RegisterObjectTransformation(...)) for overriding default property reflection (@snakefoot + @304NotModified + @Giorgi + @mmurrell) - [#3787](https://github.com/NLog/NLog/pull/3787) LogManager.Setup().SetupExtensions(s => s.RegisterConditionMethod(...)) can use lambda methods and not just static methods (@snakefoot) - [#3713](https://github.com/NLog/NLog/pull/3713) ${level:format=FullName} will expand Info + Warn to their full name (@snakefoot) - [#3714](https://github.com/NLog/NLog/pull/3714) + [#3734](https://github.com/NLog/NLog/pull/3734) FileTarget - Supports MaxArchiveDays for cleanup of old files based on their age (@snakefoot) - [#3737](https://github.com/NLog/NLog/pull/3737) + [#3769](https://github.com/NLog/NLog/pull/3769) Layout.FromMethod to create Layout directly from a lambda method (@snakefoot) - [#3771](https://github.com/NLog/NLog/pull/3771) Layout.FromString to create Layout directly from string along with optional parser validation (@snakefoot) - [#3793](https://github.com/NLog/NLog/pull/3793) ${dir-separator} for rendering platform specific directory path separator (@304NotModified) - [#3755](https://github.com/NLog/NLog/pull/3755) FileTarget - Supports ArchiveOldFileOnStartupAboveSize for cleanup of existing file when above size (@Sam13) - [#3796](https://github.com/NLog/NLog/pull/3796) + [#3823](https://github.com/NLog/NLog/pull/3823) InternalLogger - Added LogMessageReceived event (@304NotModified + @snakefoot) - [#3829](https://github.com/NLog/NLog/pull/3829) DatabaseTarget - Assign connection properties like SqlConnection.AccessToken (@304NotModified + @snakefoot) - [#3839](https://github.com/NLog/NLog/pull/3839) DatabaseTarget - Assign command properties like SqlCommand.CommandTimeout (@snakefoot) - [#3833](https://github.com/NLog/NLog/pull/3833) ${onHasProperties} for only rendering when logevent includes properties from structured logging (@snakefoot) **Improvements** - [#3521](https://github.com/NLog/NLog/pull/3521) XmlLoggingConfiguration - Marked legacy constructors with ignoreErrors parameter as obsolete (@snakefoot) - [#3689](https://github.com/NLog/NLog/pull/3689) LoggingConfiguration - Perform checking of unused targets during initialization for better validation (@snakefoot) - [#3704](https://github.com/NLog/NLog/pull/3704) EventLogTarget - Improve diagnostics logging when using dynamic EventLog source (@snakefoot) - [#3706](https://github.com/NLog/NLog/pull/3706) ${longdate} now also supports raw value for use as DatabaseTarget parameter with DbType (@snakefoot) - [#3728](https://github.com/NLog/NLog/pull/3728) SourceLink for GitHub for easy debugging into the NLog source code (@304NotModified) - [#3743](https://github.com/NLog/NLog/pull/3743) JsonLayout - EscapeForwardSlash now automatically applies to sub-attributes (@snakefoot) - [#3742](https://github.com/NLog/NLog/pull/3742) TraceTarget - Introduced EnableTraceFail=false to avoid Environment.FailFast (@snakefoot) - [#3750](https://github.com/NLog/NLog/pull/3750) ExceptionLayoutRenderer - Improved error message when Format-token parsing fails (@snakefoot) - [#3747](https://github.com/NLog/NLog/pull/3747) AutoFlushWrapper - Set AutoFlush=false for AsyncTaskTarget by default (@snakefoot) - [#3754](https://github.com/NLog/NLog/pull/3754) LocalIpAddressLayoutRenderer - Higher priority to network-addresses that has valid gateway adddress (@snakefoot) - [#3762](https://github.com/NLog/NLog/pull/3762) LogFactory - Flush reports to InternalLogger what targets produces timeouts (@snakefoot) **Fixes** - [#3758](https://github.com/NLog/NLog/pull/3758) LogFactory - Fix deadlock issue with AutoReload (@snakefoot) - [#3766](https://github.com/NLog/NLog/pull/3766) JsonLayout - Fixed ThreadAgnostic to correctly capture context when using nested JsonLayout (@snakefoot) - [#3700](https://github.com/NLog/NLog/pull/3700) ExceptionLayoutRenderer - Fixed so Format option HResult also works for NetCore (@snakefoot) - [#3761](https://github.com/NLog/NLog/pull/3761) + [#3784](https://github.com/NLog/NLog/pull/3784) Log4JXml Layout will render NDLC + NDC scopes in correct order (@adanek + @304NotModified) - [#3821](https://github.com/NLog/NLog/pull/3821) Logger - Added exception handler for CallSite capture for platform that fails to capture StackTrace (@snakefoot) - [#3835](https://github.com/NLog/NLog/pull/3835) StringSplitter - Fixed quote handling when reading elements for config list-properties (@snakefoot) - [#3828](https://github.com/NLog/NLog/pull/3828) Utilities: fix ConversionHelpers.TryParseEnum for white space (@304NotModified) **Performance** - [#3683](https://github.com/NLog/NLog/pull/3683) ObjectGraphScanner - Avoid holding list.SyncRoot lock while scanning (@snakefoot) - [#3691](https://github.com/NLog/NLog/pull/3691) FileTarget - ConcurrentWrites=true on NetCore now much faster when archive enabled (@snakefoot) - [#3694](https://github.com/NLog/NLog/pull/3694) + [#3705](https://github.com/NLog/NLog/pull/3705) JsonConverter - Write DateTime directly without string allocation (@snakefoot) - [#3692](https://github.com/NLog/NLog/pull/3692) XmlLayout - Removed unnecessary double conversion to string (@snakefoot) - [#3735](https://github.com/NLog/NLog/pull/3735) WebServiceTarget - Reduced memory allocations by removing unnecessary delegate capture (@snakefoot) - [#3739](https://github.com/NLog/NLog/pull/3739) NetworkTarget - Reduced memory allocation for encoding into bytes without string allocation (@snakefoot) - [#3748](https://github.com/NLog/NLog/pull/3748) AsyncTaskTarget - Skip default AsyncWrapper since already having internal queue (@snakefoot) - [#3767](https://github.com/NLog/NLog/pull/3767) Mark Condition Expressions as ThreadSafe to improve concurrency in Layouts (@snakefoot) - [#3764](https://github.com/NLog/NLog/pull/3764) DatabaseTarget - Added IsolationLevel option that activates transactions for better batching performance (@snakefoot) - [#3779](https://github.com/NLog/NLog/pull/3779) SimpleLayout - Assignment of string-reference with null-value will translate into FixedText (@304NotModified) - [#3790](https://github.com/NLog/NLog/pull/3790) AsyncWrapper - Less aggressive with scheduling timer events for background writing (@snakefoot) - [#3830](https://github.com/NLog/NLog/pull/3830) Faster assignment of properties accessed through reflection (@304NotModified) - [#3832](https://github.com/NLog/NLog/pull/3832) ${replace} - Faster search and replace when not explicitly have requested regex support (@snakefoot) - [#3828](https://github.com/NLog/NLog/pull/3828) Skip need for Activator.CreateInstance in DbTypeSetter (@304NotModified) ### Version 4.6.8 (2019/11/04) **Fixes** - [#3566](https://github.com/NLog/NLog/pull/3566) DatabaseTarget - Auto escape special chars in password, and improve handling of empty username/password (@304NotModified) - [#3584](https://github.com/NLog/NLog/pull/3584) LoggingRule - Fixed IndexOutOfRangeException for SetLoggingLevels with LogLevel.Off (@snakefoot) - [#3609](https://github.com/NLog/NLog/pull/3609) FileTarget - Improved handling of relative path in ArchiveFileName (@snakefoot) - [#3631](https://github.com/NLog/NLog/pull/3631) ExceptionLayoutRenderer - Fixed missing separator when Format-value gives empty result (@brinko99) - [#3647](https://github.com/NLog/NLog/pull/3647) ${substring} - Length should not be mandatory (@304NotModified) - [#3653](https://github.com/NLog/NLog/pull/3653) SimpleLayout - Fixed NullReferenceException in PreCalculate during TryGetRawValue optimization (@snakefoot) **Features** - [#3578](https://github.com/NLog/NLog/pull/3578) LogFactory - AutoShutdown can be configured to unhook from AppDomain-Unload, and avoid premature shutdown with IHostBuilder (@snakefoot) - [#3579](https://github.com/NLog/NLog/pull/3579) PerformanceCounterLayoutRenderer - Added Layout-support for Instance-property (@snakefoot) - [#3583](https://github.com/NLog/NLog/pull/3583) ${local-ip} Layout Renderer for local machine ip-address (@snakefoot + @304NotModified) - [#3583](https://github.com/NLog/NLog/pull/3583) CachedLayoutRendererWrapper - Added CachedSeconds as ambient property. Ex. ${local-ip:cachedSeconds=60} (@snakefoot) - [#3586](https://github.com/NLog/NLog/pull/3586) JsonLayout - Added EscapeForwardSlash-option to skip Json-escape of forward slash (@304NotModified) - [#3593](https://github.com/NLog/NLog/pull/3593) AllEventPropertiesLayoutRenderer - Added Exclude-option that specifies property-keys to skip (@snakefoot) - [#3611](https://github.com/NLog/NLog/pull/3611) ${Exception} - Added new Format-option values HResult and Properties (@snakefoot) **Improvements** - [#3622](https://github.com/NLog/NLog/pull/3622) + [#3651](https://github.com/NLog/NLog/pull/3651) ConcurrentRequestQueue refactoring to reduce code complexity (@snakefoot) - [#3636](https://github.com/NLog/NLog/pull/3636) AsyncTargetWrapper now fallback to clearing internal queue if flush fails to release blocked writer threads (@snakefoot) - [#3641](https://github.com/NLog/NLog/pull/3641) ${CallSite} - Small improvements for recognizing async callsite cases (@snakefoot) - [#3642](https://github.com/NLog/NLog/pull/3642) LogManager.GetCurrentClassLogger - Improved capture of Logger name when called within lambda_method (@snakefoot) - [#3649](https://github.com/NLog/NLog/pull/3649) ${BaseDir:FixTempDir=true} fallback to process directory for .NET Core 3 Single File Publish (@snakefoot) - [#3649](https://github.com/NLog/NLog/pull/3649) Auto-loading NLog configuration from process.exe.nlog will priotize process directory for .NET Core 3 Single File Publish (@snakefoot) - [#3654](https://github.com/NLog/NLog/pull/3654) ObjectPathRendererWrapper minor refactorings (@snakefoot) - [#3660](https://github.com/NLog/NLog/pull/3660) ObjectHandleSerializer.GetObjectData includes SerializationFormatter=true for use in MDLC + NDLC (@snakefoot) - [#3662](https://github.com/NLog/NLog/pull/3662) FileTarget - Extra logging when FileName Layout renders empty string (@snakefoot) **Performance** - [#3618](https://github.com/NLog/NLog/pull/3618) LogFactory - Faster initial assembly reflection and config loading (@snakefoot) - [#3635](https://github.com/NLog/NLog/pull/3635) ConsoleTarget - Added WriteBuffer option that allows batch writing to console-stream with reduced allocations (@snakefoot) - [#3635](https://github.com/NLog/NLog/pull/3635) ConsoleTarget - Added global lock to prevent any threadsafety issue from unsafe console (@snakefoot) ### Version 4.6.7 (2019/08/25) **Features** - [#3531](https://github.com/NLog/NLog/pull/3531) Added ${object-path} / ${exception:objectpath=PropertyName}, for rendering a property of an object (e.g. an exception) (#3531) (@304NotModified) - [#3560](https://github.com/NLog/NLog/pull/3560) WhenMethodFilter - Support dynamic filtering using lambda (#3560) (@snakefoot) - [#3184](https://github.com/NLog/NLog/pull/3184) Added support for dynamic layout renderer in log level filters (e.g. minLevel, maxLevel) (#3184) (@snakefoot) - [#3558](https://github.com/NLog/NLog/pull/3558) ExceptionLayoutRenderer - Added Source as new format parameter. (@snakefoot) - [#3523](https://github.com/NLog/NLog/pull/3523) ColoredConsoleTarget - Added DetectOutputRedirected to skip coloring on redirect (@snakefoot) **Improvements** - [#3541](https://github.com/NLog/NLog/pull/3541) MessageTemplateParameters - Improve validation of parameters when isPositional (#3541) (@snakefoot) - [#3546](https://github.com/NLog/NLog/pull/3546) NetworkTarget - HttpNetworkSender no longer sends out-of-order (@snakefoot) - [#3522](https://github.com/NLog/NLog/pull/3522) NetworkTarget - Fix InternalLogger.Trace to include Target name (#3522) (@snakefoot) - [#3562](https://github.com/NLog/NLog/pull/3562) XML config - Support ThrowConfigExceptions=true even when xml is invalid (@snakefoot) - [#3532](https://github.com/NLog/NLog/pull/3532) Fix summary of NoRawValueLayoutRendererWrapper class (#3532) (@304NotModified) **Performance** - [#3540](https://github.com/NLog/NLog/pull/3540) MessageTemplateParameters - Skip object allocation when no parameters (@snakefoot) - [#3527](https://github.com/NLog/NLog/pull/3527) XmlLayout - Defer allocation of ObjectReflectionCache until needed (#3527) (@snakefoot) ### Version 4.6.6 (2019/07/14) **Features** - [#3514](https://github.com/NLog/NLog/pull/3514) Added XmlLoggingConfiguration(XmlReader reader) ctor, improved docs and annotations (@dmitrychilli, @304NotModified) - [#3513](https://github.com/NLog/NLog/pull/3513) AutoFlushTargetWrapper - Added FlushOnConditionOnly property (@snakefoot) **Performance** - [#3492](https://github.com/NLog/NLog/pull/3492) FileTarget - improvements when ConcurrentWrites=false (@snakefoot) ### Version 4.6.5 (2019/06/13) **Fixes** - [#3476](https://github.com/NLog/NLog/pull/3476) Fix broken XSD schema - NLog.Schema package (@snakefoot, @304NotModified) **Features** - [#3478](https://github.com/NLog/NLog/pull/3478) XSD: Support `<value>` in `<variable>` (@304NotModified) - [#3477](https://github.com/NLog/NLog/pull/3477) ${AppSetting} - Added support for ConnectionStrings Lookup (@snakefoot) - [#3469](https://github.com/NLog/NLog/pull/3469) LogLevel - Added support for TypeConverter (@snakefoot) - [#3453](https://github.com/NLog/NLog/pull/3453) Added null terminator line ending for network target (@Kahath) - [#3442](https://github.com/NLog/NLog/pull/3442) Log4JXmlEventLayout - Added IncludeCallSite + IncludeSourceInfo (@snakefoot) **Improvements** - [#3482](https://github.com/NLog/NLog/pull/3482) Fix typos in docs and comments (@304NotModified) **Performance** - [#3444](https://github.com/NLog/NLog/pull/3444) RetryingMultiProcessFileAppender - better init BufferSize (@snakefoot) ### Version 4.6.4 (2019/05/28) **Fixes** - [#3392](https://github.com/NLog/NLog/pull/3392) NLog.Schema: Added missing defaultAction attribute on filters element in XSD (@304NotModified) - [#3415](https://github.com/NLog/NLog/pull/3415) AsyncWrapper in Blocking Mode can cause deadlock (@snakefoot) **Features** - [#3430](https://github.com/NLog/NLog/pull/3430) Added "Properties" property on Logger for reading and editing properties.(@snakefoot, @304NotModified) - [#3423](https://github.com/NLog/NLog/pull/3423) ${all-event-properties}: Added IncludeEmptyValues option (@304NotModified) - [#3394](https://github.com/NLog/NLog/pull/3394) ${when}, support for non-string values (@304NotModified) - [#3398](https://github.com/NLog/NLog/pull/3398) ${whenEmpty} support for non-string values (@snakefoot, @304NotModified) - [#3391](https://github.com/NLog/NLog/pull/3391) Added ${environment-user} (@snakefoot) - [#3389](https://github.com/NLog/NLog/pull/3389) Log4JXmlEventLayout - Added support for configuration of Parameters (@snakefoot) - [#3411](https://github.com/NLog/NLog/pull/3411) LoggingConfigurationParser - Recognize LoggingRule.RuleName property (@snakefoot) **Improvements** - [#3393](https://github.com/NLog/NLog/pull/3393) Update package descriptions to note the issues with `<PackageReference>` (@304NotModified) - [#3409](https://github.com/NLog/NLog/pull/3409) Various XSD improvements (NLog.Schema package) (@304NotModified) **Performance** - [#3398](https://github.com/NLog/NLog/pull/3398) ${whenEmpty} faster rendering of string values (@snakefoot, @304NotModified) - [#3405](https://github.com/NLog/NLog/pull/3405) FilteringTargetWrapper: Add support for batch writing (@snakefoot, @304NotModified) - [#3405](https://github.com/NLog/NLog/pull/3405) PostFilteringTargetWrapper: performance optimizations (@snakefoot, @304NotModified) - [#3435](https://github.com/NLog/NLog/pull/3435) Async / buffering wrapper: Improve performance when blocking (@snakefoot) - [#3434](https://github.com/NLog/NLog/pull/3434) ObjectReflectionCache - Skip property-reflection for IFormattable (@snakefoot) ### Version 4.6.3 (2019/04/30) **Fixes** - [#3345](https://github.com/NLog/NLog/pull/3345) Fixed potential memory issue and message duplication with large strings (@snakefoot) - [#3316](https://github.com/NLog/NLog/pull/3316) TargetWithContext - serialize MDC and MDLC values properly (@304NotModified) **Features** - [#3298](https://github.com/NLog/NLog/pull/3298) Added WithProperty and SetProperty on Logger (@snakefoot) - [#3329](https://github.com/NLog/NLog/pull/3329) ${EventProperties} - Added ObjectPath for rendering nested property (@snakefoot, @304NotModified) - [#3337](https://github.com/NLog/NLog/pull/3337) ${ShortDate} added support for IRawValue + IStringValueRenderer (@snakefoot) - [#3328](https://github.com/NLog/NLog/pull/3328) Added truncate ambient property, e.g. ${message:truncate=80} (@snakefoot) - [#3278](https://github.com/NLog/NLog/pull/3278) ConsoleTarget & ColoredConsoleTarget - Added AutoFlush and improve default flush behavior (@snakefoot) **Improvements** - [#3322](https://github.com/NLog/NLog/pull/3322) FileTarget - Introduced EnableFileDeleteSimpleMonitor without FileSystemWatcher for non-Windows (@snakefoot) - [#3332](https://github.com/NLog/NLog/pull/3332) LogFactory - GetLogger should validate name of logger (@snakefoot) - [#3320](https://github.com/NLog/NLog/pull/3320) FallbackGroupTarget - Fixed potential issue with WINDOWS_PHONE (@snakefoot) - [#3261](https://github.com/NLog/NLog/pull/3261) NLog config file loading: use process name (e.g. applicationname.exe.nlog) when app.config is not available (@snakefoot) **Performance** - [#3311](https://github.com/NLog/NLog/pull/3311) Split string - avoid allocation of object array. Added StringHelpers.SplitAndTrimTokens (@snakefoot) - [#3305](https://github.com/NLog/NLog/pull/3305) AppSettingLayoutRenderer - Mark as ThreadSafe and ThreadAgnostic (@snakefoot) **Other** - [#3338](https://github.com/NLog/NLog/pull/3338) Update docs of various context classes (@304NotModified) - [#3288](https://github.com/NLog/NLog/pull/3288) Move NLogPackageLoaders for better unittest debugging experience of NLog (@304NotModified) - [#3274](https://github.com/NLog/NLog/pull/3274) Make HttpNetworkSender mockable, add unit test, introduce NSubsitute (@304NotModified) - 10 pull requests with refactorings (@snakefoot, @304NotModified) ### Version 4.6.2 (2019/04/02) **Fixes** - [#3260](https://github.com/NLog/NLog/pull/3260) Fix escaping nested close brackets when parsing layout renderers (@lobster2012-user) - [#3271](https://github.com/NLog/NLog/pull/3271) NLog config - Fixed bug where empty xml-elements were ignored (@snakefoot, @jonreis) ### Version 4.6.1 (2019/03/29) **Fixes** - [#3199](https://github.com/NLog/NLog/pull/3199) LoggingConfigurationParser - Fixed bug in handling of extensions prefix (@snakefoot) - [#3253](https://github.com/NLog/NLog/pull/3253) Fix wrong warnings on `<nlog>` element (only wrong warnings) (#3253) (@snakefoot, @304NotModified) - [#3195](https://github.com/NLog/NLog/pull/3195) SimpleStringReader: fix DebuggerDisplay value (#3195) (@lobster2012-user) - [#3198](https://github.com/NLog/NLog/pull/3198) XmlLayout - Fixed missing encode of xml element value (@snakefoot) - [#3191](https://github.com/NLog/NLog/pull/3191) VariableLayoutRenderer - Fixed format-string for internal logger warning (@snakefoot, @lobster2012-user) - [#3258](https://github.com/NLog/NLog/pull/3258) Fix error with Embedded Assembly in LogAssemblyVersion (@snakefoot) **Improvements** - [#3255](https://github.com/NLog/NLog/pull/3255) Auto-flush on process exit improvements (@snakefoot) - [#3189](https://github.com/NLog/NLog/pull/3189) AsyncTaskTarget - Respect TaskDelayMilliseconds on low activity (@snakefoot) **Performance** - [#3256](https://github.com/NLog/NLog/pull/3256) ${NDLC} + ${NDC} - Faster checking when TopFrames = 1 (@snakefoot) - [#3201](https://github.com/NLog/NLog/pull/3201) ${GDC} reading is now lockfree (#3201) (@snakefoot) ### Version 4.6 **Features** - [#2363](https://github.com/NLog/NLog/pull/2363) + [#2899](https://github.com/NLog/NLog/pull/2899) + [#3085](https://github.com/NLog/NLog/pull/3085) + [#3091](https://github.com/NLog/NLog/pull/3091) Database target: support for DbType for parameters (including SqlDbType) - (@hubo0831,@ObikeDev,@sorvis, @304NotModified, @snakefoot) - [#2610](https://github.com/NLog/NLog/pull/2610) AsyncTargetWrapper with LogEventDropped- + LogEventQueueGrow-events (@Pomoinytskyi) - [#2670](https://github.com/NLog/NLog/pull/2670) + [#3014](https://github.com/NLog/NLog/pull/3014) XmlLayout - Render LogEventInfo.Properties as XML (@snakefoot) - [#2678](https://github.com/NLog/NLog/pull/2678) NetworkTarget - Support for SSL & TLS (@snakefoot) - [#2709](https://github.com/NLog/NLog/pull/2709) XML Config: Support for constant variable in level attributes (level, minlevel, etc) (@304NotModified) - [#2848](https://github.com/NLog/NLog/pull/2848) Added defaultAction for `<filter>` (@304NotModified) - [#2849](https://github.com/NLog/NLog/pull/2849) IRawValue-interface and ${db-null} layout renderer (@304NotModified) - [#2902](https://github.com/NLog/NLog/pull/2902) JsonLayout with support for System.Dynamic-objects (@304NotModified) - [#2907](https://github.com/NLog/NLog/pull/2907) New Substring, Left & Right Wrappers (@304NotModified) - [#3098](https://github.com/NLog/NLog/pull/3098) `<rule>` support for one or more '*' and '?' wildcards and in any position (@beppemarazzi) - [#2909](https://github.com/NLog/NLog/pull/2909) AsyncTaskTarget - BatchSize + RetryCount (@snakefoot) - [#3018](https://github.com/NLog/NLog/pull/3018) ColoredConsoleTarget - Added EnableAnsiOutput option (VS Code support) (@jp7677 + @snakefoot) - [#3031](https://github.com/NLog/NLog/pull/3031) + [#3092](https://github.com/NLog/NLog/pull/3092) Support ${currentdir},${basedir},${tempdir} and Environment Variables for internalLogFile when parsing nlog.config (@snakefoot) - [#3050](https://github.com/NLog/NLog/pull/3050) Added IncludeGdc property in JsonLayout (@casperc89) - [#3071](https://github.com/NLog/NLog/pull/3071) ${HostName} Layout Renderer for full computer DNS name (@amitsaha) - [#3053](https://github.com/NLog/NLog/pull/3053) ${AppSetting} Layout Renderer (app.config + web.config) moved from NLog.Extended for NetFramework (@snakefoot) - [#3060](https://github.com/NLog/NLog/pull/3060) TargetWithContext - Support for PropertyType using IRawValue-interface (@snakefoot) - [#3124](https://github.com/NLog/NLog/pull/3124) NetworkTarget - Added support for KeepAliveTimeSeconds (@snakefoot) - [#3129](https://github.com/NLog/NLog/pull/3129) ConfigSetting - Preregister so it can be accessed without extension registration (#3129) (@snakefoot) * [#3165](https://github.com/NLog/NLog/pull/3165) Added noRawValue layout wrapper (@snakefoot) **Improvements** - [#2989](https://github.com/NLog/NLog/pull/2989) JsonLayout includes Type-property when rendering Exception-object (@snakefoot) - [#2891](https://github.com/NLog/NLog/pull/2891) LoggingConfigurationParser - Extracted from XmlLoggingConfiguration (Prepare for appsettings.json) (@snakefoot) - [#2910](https://github.com/NLog/NLog/pull/2910) Added support for complex objects in MDLC and NDLC on Net45 (@snakefoot) - [#2918](https://github.com/NLog/NLog/pull/2918) PerformanceCounter - Improve behavior for CPU usage calculation (@snakefoot) - [#2941](https://github.com/NLog/NLog/pull/2941) TargetWithContext - Include all properties even when duplicate names (@snakefoot) - [#2974](https://github.com/NLog/NLog/pull/2974) Updated resharper annotations for better validation (@imanushin) - [#2979](https://github.com/NLog/NLog/pull/2979) Improve default reflection support on NetCore Native (@snakefoot) - [#3017](https://github.com/NLog/NLog/pull/3017) EventLogTarget with better support for MaximumKilobytes configuration (@Coriolanuss) - [#3039](https://github.com/NLog/NLog/pull/3039) Added Xamarin PreserveAttribute for the entire Assembly to improve AOT-linking (@snakefoot) - [#3045](https://github.com/NLog/NLog/pull/3045) Create snupkg packages and use portable PDB (@snakefoot) - [#3048](https://github.com/NLog/NLog/pull/3048) KeepFileOpen + ConcurrentWrites on Xamarin + UWP - [#3079](https://github.com/NLog/NLog/pull/3079) (@304NotModified) - [#3082](https://github.com/NLog/NLog/pull/3082) + [#3100](https://github.com/NLog/NLog/pull/3100) WebService Target allow custom override of SoapAction-header for Soap11 (@AlexeyRokhin) - [#3162](https://github.com/NLog/NLog/pull/3162) ContextProperty with IncludeEmptyValue means default value for ValueType (#3162) (@snakefoot) - [#3159](https://github.com/NLog/NLog/pull/3159) AppSettingLayoutRenderer - Include Item for NLog.Extended (@snakefoot) - [#3187](https://github.com/NLog/NLog/pull/3187) AsyncTaskTarget - Fixed unwanted delay caused by slow writer (@snakefoot) - Various refactorings (19 pull requests) (@beppemarazzi, @304NotModified, @snakefoot) **Performance** - [#2650](https://github.com/NLog/NLog/pull/2650) AsyncTargetWrapper using ConcurrentQueue for NetCore2 for better thread-concurrency (@snakefoot) - [#2890](https://github.com/NLog/NLog/pull/2890) AsyncTargetWrapper - TimeToSleepBetweenBatches changed default to 1ms (@snakefoot) - [#2897](https://github.com/NLog/NLog/pull/2897) InternalLogger performance optimization when LogLevel.Off (@snakefoot) - [#2935](https://github.com/NLog/NLog/pull/2935) InternalLogger LogLevel changes to LogLevel.Off by default unless being used. (@snakefoot) - [#2934](https://github.com/NLog/NLog/pull/2934) CsvLayout - Allocation optimizations and optional skip quoting-check for individual columns. (@snakefoot) - [#2949](https://github.com/NLog/NLog/pull/2949) MappedDiagnosticsLogicalContext - SetScoped with IReadOnlyList (Prepare for MEL BeginScope) (@snakefoot) - [#2973](https://github.com/NLog/NLog/pull/2973) IRenderString-interface to improve performance for Layout with single LayoutRenderer (@snakefoot) - [#3103](https://github.com/NLog/NLog/pull/3103) StringBuilderPool - Reduce memory overhead until required (@snakefoot) **LibLog Breaking change** * [damianh/LibLog#181](https://github.com/damianh/LibLog/pull/181) - Sub-components using LibLog ver. 5.0.3 (or newer) will now use MDLC + NDLC (Instead of MDC + NDC) when detecting application is using NLog ver. 4.6. Make sure to update NLog.config to match this change. Make sure that all sub-components have upgraded to LibLog ver. 5.0.3 (or newer) if they make use of `OpenNestedContext` or `OpenMappedContext`. See also [NLog 4.6 Milestone](https://github.com/NLog/NLog/milestone/44?closed=1) ### Version 4.5.11 (2018/11/06) **Improvements** - [#2985](https://github.com/NLog/NLog/pull/2985) LogBuilder - Support fluent assignment of message-template after properties (@snakefoot) - [#2983](https://github.com/NLog/NLog/pull/2983) JsonSerializer - Use ReferenceEquals instead of object.Equals when checking for cyclic object loops (#2983) (@snakefoot) - [#2988](https://github.com/NLog/NLog/pull/2988) NullAppender - Added missing SecuritySafeCritical (@snakefoot) **Fixes** - [#2987](https://github.com/NLog/NLog/pull/2987) JSON encoding should create valid JSON for non-string dictionary-keys (@snakefoot) ### Version 4.5.10 (2018/09/17) **Fixes** - [#2883](https://github.com/NLog/NLog/pull/2883) Fix LoadConfiguration for not found config file (@snakefoot, @304NotModified) ### Version 4.5.9 (2018/08/24) **Fixes** - [#2865](https://github.com/NLog/NLog/pull/2865) JSON encoding should create valid JSON for special double values (@snakefoot) **Improvements** - [#2846](https://github.com/NLog/NLog/pull/2846) Include Entry Assembly File Location when loading candidate NLog.config (@snakefoot) ### Version 4.5.8 (2018/08/05) **Features** - [#2809](https://github.com/NLog/NLog/pull/2809) MethodCallTarget - Support for Lamba method (@snakefoot) - [#2816](https://github.com/NLog/NLog/pull/2816) MessageTemplates - Support rendering of alignment + padding (@snakefoot) **Fixes** - [#2827](https://github.com/NLog/NLog/pull/2827) FileTarget - Failing to CreateArchiveMutex should not stop logging (@snakefoot) - [#2830](https://github.com/NLog/NLog/pull/2830) Auto loading of assemblies was broken in some cases (@snakefoot) **Improvements** - [#2814](https://github.com/NLog/NLog/pull/2814) LoggingConfiguration - Improves CheckUnusedTargets to handle target wrappers (@snakefoot) **Performance** - [#2817](https://github.com/NLog/NLog/pull/2817) Optimize LayoutRendererWrappers to reduce string allocations (#2817) (@snakefoot) ### Version 4.5.7 (2018/07/19) **Features** - [#2792](https://github.com/nlog/nlog/pull/2792) OutputDebugStringTarget - Support Xamarin iOS and Android (@snakefoot) - [#2776](https://github.com/nlog/nlog/pull/2776) FileTarget - Introduced OpenFileFlushTimeout to help when AutoFlush = false (@snakefoot) **Fixes** - [#2761](https://github.com/nlog/nlog/pull/2761) ${Callsite} fix class naming when includeNamespace=false and cleanNamesOfAnonymousDelegates=true (@Azatey) - [#2752](https://github.com/nlog/nlog/pull/2752) JSON: Fixes issue where char types are not properly escaped (#2752) (@smbecker) **Improvements** - [#2804](https://github.com/nlog/nlog/pull/2804) FileTarget - Do not trust Last File Write TimeStamp when AutoFlush=false (@snakefoot) - [#2763](https://github.com/nlog/nlog/pull/2763) Throw better error when target name is null (@masters3d) - [#2788](https://github.com/nlog/nlog/pull/2788) ${Assembly-version} make GetAssembly protected and virtual (@alexangas) - [#2756](https://github.com/nlog/nlog/pull/2756) LongDateLayoutRenderer: Improve comments (@stic) - [#2749](https://github.com/nlog/nlog/pull/2749) NLog.WindowsEventLog: Update dependency System.Diagnostics.EventLog to RTM version (@304NotModified) **Performance** - [#2797](https://github.com/nlog/nlog/pull/2797) Better performance with Activator.CreateInstance (@tangdf) ### Version 4.5.6 (2018/05/29) **Fixes** - [#2747](https://github.com/nlog/nlog/pull/2747) JsonSerializer - Generate valid Json when hitting the MaxRecursionLimit (@snakefoot) - Fixup for [NLog.WindowsEventLog package](https://www.nuget.org/packages/NLog.WindowsEventLog) **Improvements** - [#2745](https://github.com/nlog/nlog/pull/2745) FileTarget - Improve support for Linux FileSystem without BirthTime (@snakefoot) **Performance** - [#2744](https://github.com/nlog/nlog/pull/2744) LogEventInfo - HasProperties should allocate PropertiesDicitonary when needed (@snakefoot) - [#2743](https://github.com/nlog/nlog/pull/2743) JsonLayout - Reduce allocations when needing to escape string (44% time improvement) (@snakefoot) ### Version 4.5.5 (2018/05/25) **Fixes** - [#2736](https://github.com/NLog/NLog/pull/2736) FileTarget - Calculate correct archive date when multiple file appenders (@snakefoot) **Features** - [#2726](https://github.com/nlog/nlog/pull/2726) WhenRepeated - Support logging rules with multiple targets (@snakefoot) - [#2727](https://github.com/nlog/nlog/pull/2727) Support for custom targets that implements IUsesStackTrace (@snakefoot) - [#2719](https://github.com/nlog/nlog/pull/2719) DatabaseTarget: use parameters on install (@Jejuni) **Improvements** - [#2718](https://github.com/nlog/nlog/pull/2718) JsonLayout - Always stringify when requested (@snakefoot) - [#2739](https://github.com/nlog/nlog/pull/2739) Target.WriteAsyncLogEvents(IList) to public **Performance** - [#2704](https://github.com/nlog/nlog/pull/2704) Allocation improvement in precalculating layouts (@snakefoot) ### Version 4.5.4 (2018/05/05) **Fixes** - [#2688](https://github.com/nlog/nlog/pull/2688) Faulty invalidate of FormattedMessage when getting PropertiesDictionary (@snakefoot) - [#2687](https://github.com/nlog/nlog/pull/2687) Fix: NLog.config build-action and copy for non-core projects, it's now "copy if newer" (@304NotModified) - [#2698](https://github.com/nlog/nlog/pull/2698) FileTarget - Calculate correct archive date, when using Monthly archive (@snakefoot) **Improvements** - [#2673](https://github.com/nlog/nlog/pull/2673) TargetWithContext - Easier to use without needing to override ContextProperties (@snakefoot) - [#2684](https://github.com/nlog/nlog/pull/2684) DatabaseTarget - Skip static assembly lookup for .Net Standard (@snakefoot) - [#2689](https://github.com/nlog/nlog/pull/2689) LogEventInfo - Structured logging parameters are not always immutable (@snakefoot) - [#2679](https://github.com/nlog/nlog/pull/2679) Target.WriteAsyncThreadSafe should always have exception handler (@snakefoot) - [#2586](https://github.com/nlog/nlog/pull/2586) Target.MergeEventProperties is now obsolete (@snakefoot) - Sonar warning fixes: [#2691](https://github.com/nlog/nlog/pull/2691), [#2694](https://github.com/nlog/nlog/pull/2694), [#2693](https://github.com/nlog/nlog/pull/2693), [#2690](https://github.com/nlog/nlog/pull/2690), [#2685](https://github.com/nlog/nlog/pull/2685), [#2683](https://github.com/nlog/nlog/pull/2683), [#2696](https://github.com/NLog/NLog/pull/2696) (@snakefoot, @304NotModified) ### Version 4.5.3 (2018/04/16) **Fixes** - [#2662](https://github.com/nlog/nlog/pull/2662) FileTarget - Improve handling of archives with multiple active files (@snakefoot) **Improvements** - [#2587](https://github.com/nlog/nlog/pull/2587) Internal Log - Include target type and target name in the log messages (@snakefoot) - [#2651](https://github.com/nlog/nlog/pull/2651) Searching for NLog Extension Files should handle DirectoryNotFoundException (@snakefoot) **Performance** - [#2653](https://github.com/nlog/nlog/pull/2653) LayoutRenderer ThreadSafe Attribute introduced to allow lock free Precalculate + other small performance improvements (@snakefoot) ### Version 4.5.2 (2018/04/06) **Features** - [#2648](https://github.com/nlog/nlog/pull/2648) ${processtime} and ${time} added invariant option (@snakefoot) **Fixes** - [#2643](https://github.com/nlog/nlog/pull/2643) UWP with NetStandard2 on Net Native does not support Assembly.CodeBase + Handle native methods in StackTrace (#2643) (@snakefoot) - [#2644](https://github.com/nlog/nlog/pull/2644) FallbackGroupTarget: handle async state on fallback correctly (@snakefoot) **Performance** - [#2645](https://github.com/nlog/nlog/pull/2645) Minor performance optimization of some layoutrenderers (@snakefoot) - [#2642](https://github.com/nlog/nlog/pull/2642) FileTarget - InitializeFile should skip dictionary lookup when same file (@snakefoot) ### Version 4.5.1 (2018/04/03) **Fixes** - [#2637](https://github.com/nlog/nlog/pull/2637) Fix IndexOutOfRangeException in NestedDiagnosticsLogicalContext (@snakefoot) - [#2638](https://github.com/nlog/nlog/pull/2638) Handle null values correctly in LogReceiverSecureService (@304NotModified) **Performance** - [#2639](https://github.com/nlog/nlog/pull/2639) MessageTemplates - Optimize ParseHole for positional templates (@snakefoot) - [#2640](https://github.com/nlog/nlog/pull/2640) FileTarget - InitializeFile no longer need justData parameter + dispose fileapenders earlier (@snakefoot) - [#2628](https://github.com/nlog/nlog/pull/2628) RoundRobinGroupTarget - Replaced lock with Interlocked for performance (@snakefoot) ### Version 4.5 RTM (2018/03/25) NLog 4.5 adds structured logging and .NET Standard support/UPW without breaking changes! Also a lot features has been added! List of important changes in NLog 4.5 **Features** - Support for .Net Standard 2.0 [#2263](https://github.com/nlog/nlog/pull/2263) + [#2402](https://github.com/nlog/nlog/pull/2402) (@snakefoot) - Support for .Net Standard 1.5 [#2341](https://github.com/nlog/nlog/pull/2341) (@snakefoot) - Support for .Net Standard 1.3 (and UWP) [#2441](https://github.com/nlog/nlog/pull/2441) + [#2597](https://github.com/nlog/nlog/pull/2597) (Remember to manually flush on app suspend). (@snakefoot) - Introduced Structured logging [#2208](https://github.com/nlog/nlog/pull/2208) + [#2262](https://github.com/nlog/nlog/pull/2262) + [#2244](https://github.com/nlog/nlog/pull/2244) + [#2544](https://github.com/nlog/nlog/pull/2544) (@snakefoot, @304NotModified, @jods4, @nblumhardt) - see https://github.com/NLog/NLog/wiki/How-to-use-structured-logging - Json conversion also supports object properties [#2179](https://github.com/nlog/nlog/pull/2179), [#2555](https://github.com/nlog/nlog/pull/2555) (@snakefoot, @304NotModified) - event-properties layout-renderer can now render objects as json [#2241](https://github.com/nlog/nlog/pull/2241) (@snakefoot, @304NotModified) - exception layout-renderer can now render exceptions as json [#2357](https://github.com/nlog/nlog/pull/2357) (@snakefoot) - Default file archive logic is now easier to use [#1993](https://github.com/nlog/nlog/pull/1993) (@snakefoot) - Introduced InstallationContext.ThrowExceptions [#2214](https://github.com/nlog/nlog/pull/2214) (@rbarillec) - WebServiceTarget - Allow configuration of proxy address [#2375](https://github.com/nlog/nlog/pull/2375) (@snakefoot) - WebServiceTarget - JsonPost with JsonLayout without being wrapped in parameter [#2590](https://github.com/nlog/nlog/pull/2590) (@snakefoot) - ${guid}, added GeneratedFromLogEvent [#2226](https://github.com/nlog/nlog/pull/2226) (@snakefoot) - TraceTarget RawWrite to always perform Trace.WriteLine independent of LogLevel [#1968](https://github.com/nlog/nlog/pull/1968) (@snakefoot) - Adding OverflowAction options to BufferingTargetWrapper [#2276](https://github.com/nlog/nlog/pull/2276) (@mikegron) - WhenRepeatedFilter - Filtering of identical LogEvents [#2123](https://github.com/nlog/nlog/pull/2123) + [#2297](https://github.com/nlog/nlog/pull/2297) (@snakefoot) - ${callsite} added CleanNamesOfAsyncContinuations option [#2292](https://github.com/nlog/nlog/pull/2292) (@tkhaugen, @304NotModified) - ${ndlctiming} allows timing of ndlc-scopes [#2377](https://github.com/nlog/nlog/pull/2377) (@snakefoot) - NLogViewerTarget - Enable override of the Logger-name [#2390](https://github.com/nlog/nlog/pull/2390) (@snakefoot) - ${sequenceid} added [#2411](https://github.com/nlog/nlog/pull/2411) (@MikeFH) - Added "regex-matches" for filtering [#2437](https://github.com/nlog/nlog/pull/2437) (@MikeFH) - ${gdc}, ${mdc} & {mdlc} - Support Format parameter [#2500](https://github.com/nlog/nlog/pull/2500) (@snakefoot) - ${currentDir} added [#2491](https://github.com/nlog/nlog/pull/2491) (@UgurAldanmaz) - ${AssemblyVersion}: add type (File, Assembly, Informational) option [#2487](https://github.com/nlog/nlog/pull/2487) (@alexangas) - FileTarget: Support byte order mark [#2456](https://github.com/nlog/nlog/pull/2456) (@KYegres) - TargetWithContext - Easier to create custom NLog targets with support for MDLC and NDLC [#2467](https://github.com/nlog/nlog/pull/2467) (@snakefoot) - ${callname-filename} - Without line number [#2591](https://github.com/nlog/nlog/pull/2591) (@brunotag) - MDC + MDLC with SetScoped property support [#2592](https://github.com/nlog/nlog/pull/2592) (@MikeFH) - LoggingConfiguration AddRule includes final-parameter [#2612](https://github.com/nlog/nlog/pull/2612) (@893949088) **Fixes** - Improve archive stability during concurrent file access [#1889](https://github.com/nlog/nlog/pull/1889) (@snakefoot) - FallbackGroup could lose log events [#2265](https://github.com/nlog/nlog/pull/2265) (@frabar666) - ${exception} - only include separator when items are available [#2257](https://github.com/nlog/nlog/pull/2257) (@jojosardez) - LogFactory - Fixes broken EventArgs for ConfigurationChanged [#1897](https://github.com/nlog/nlog/pull/1897) (@snakefoot) - Do not report wrapped targets as unused targets [#2290](https://github.com/nlog/nlog/pull/2290) (@thesmallbang) - Added IIncludeContext, implemented missing properties [#2117](https://github.com/nlog/nlog/pull/2117) (@304NotModified) - Improve logging of callsite linenumber for async-methods [#2386](https://github.com/nlog/nlog/pull/2386) (@snakefoot) - NLogTraceListener - DisableFlush is enabled by default when AutoFlush=true [#2407](https://github.com/nlog/nlog/pull/2407) (@snakefoot) - NLogViewer - Better defaults for connection limits [#2404](https://github.com/nlog/nlog/pull/2404) (@304NotModified) - LoggingConfiguration.LoggingRules is not thread safe [#2393](https://github.com/nlog/nlog/pull/2393), [#2418](https://github.com/nlog/nlog/pull/2418) - Fix XmlLoggingConfiguration reloading [#2475](https://github.com/nlog/nlog/pull/2475) (@snakefoot) - Database Target now supports EntityFramework ConnectionStrings [#2510](https://github.com/nlog/nlog/pull/2510) (@Misiu, @snakefoot) - LoggingConfiguration.RemoveTarget now works while actively logging [#2549](https://github.com/nlog/nlog/pull/2549) (@jojosardez, @snakefoot) - FileTarget does not fail on platforms without global mutex support [#2604](https://github.com/nlog/nlog/pull/2604) (@snakefoot) - LoggingConfiguration does not fail when AutoReload is not possible on the platforms without FileWatcher [#2603](https://github.com/nlog/nlog/pull/2603) (@snakefoot) **Performance** - More targets has OptimizeBufferReuse enabled by default [#1913](https://github.com/nlog/nlog/pull/1913) + [#1923](https://github.com/nlog/nlog/pull/1923) + [#1912](https://github.com/nlog/nlog/pull/1912) + [#1911](https://github.com/nlog/nlog/pull/1911) + [#1910](https://github.com/nlog/nlog/pull/1910) + [#1909](https://github.com/nlog/nlog/pull/1909) + [#1908](https://github.com/nlog/nlog/pull/1908) + [#1907](https://github.com/nlog/nlog/pull/1907) + [#2560](https://github.com/nlog/nlog/pull/2560) (@snakefoot) - StringBuilderPool - Improved Layout Render Performance by reusing StringBuilders [#2208](https://github.com/nlog/nlog/pull/2208) (@snakefoot) - JsonLayout - Improved Layout Performance, by optimizing use of StringBuilder [#2208](https://github.com/nlog/nlog/pull/2208) (@snakefoot) - FileTarget - Faster byte-encoding of log messsages, by using crude Encoding.GetMaxByteCount() instead of exact Encoding.GetByteCount() [#2208](https://github.com/nlog/nlog/pull/2208) (@snakefoot) - Target - Precalculate Layout should ignore sub-layouts for complex layout (Ex Json) [#2378](https://github.com/nlog/nlog/pull/2378) (@snakefoot) - MessageLayoutRenderer - Skip `string.Format` allocation (for caching) when writing to a single target, instead format directly into output buffer. [#2507](https://github.com/nlog/nlog/pull/2507) (@snakefoot) Changes since rc 07: - [#2621](https://github.com/nlog/nlog/pull/2621) Single Target optimization logic refactored to reuse optimization approval (@snakefoot) - [#2622](https://github.com/nlog/nlog/pull/2622) NetworkTarget - Http / Https should not throw on async error response (@snakefoot) - [#2619](https://github.com/nlog/nlog/pull/2619) NetworkTarget - Reduce allocation when buffer is less than MaxMessageSize (@snakefoot) - [#2616](https://github.com/nlog/nlog/pull/2616) LogManager.Shutdown - Should disable file watcher and avoid auto reload (@snakefoot) - [#2620](https://github.com/nlog/nlog/pull/2620) Single Target optimization should only be done when parseMessageTemplate = null (@snakefoot) ### Version 4.5-rc07 (2018/03/07) - [#2614](https://github.com/nlog/nlog/pull/2614) NLog 4.5 RC7 changelog & version (@304NotModified) - [#2612](https://github.com/nlog/nlog/pull/2612) add final param to `AddRule` Methods (#2612) (@893949088) - [#2590](https://github.com/nlog/nlog/pull/2590) WebServiceTarget - JsonPost with support for single nameless parameter (@snakefoot) - [#2604](https://github.com/nlog/nlog/pull/2604) FileTarget - Failing to CreateArchiveMutex should not stop logging (#2604) (@snakefoot) - [#2592](https://github.com/nlog/nlog/pull/2592) Make Set methods of MDC and MDLC return IDisposable (#2592) (@MikeFH) - [#2591](https://github.com/nlog/nlog/pull/2591) callsite-filename renderer (#2591) (@brunotag) - [#2597](https://github.com/nlog/nlog/pull/2597) Replace WINDOWS_UWP with NETSTANDARD1_3 to support UWP10 shared libraries (@snakefoot) - [#2599](https://github.com/nlog/nlog/pull/2599) TryImplicitConversion should only check object types (@snakefoot) - [#2595](https://github.com/nlog/nlog/pull/2595) IsSafeToDeferFormatting - Convert.GetTypeCode is faster and better (@snakefoot) - [#2609](https://github.com/nlog/nlog/pull/2609) NLog - Fix Callsite when wrapping ILogger in Microsoft Extension Logging (@snakefoot) - [#2613](https://github.com/nlog/nlog/pull/2613) Attempt to make some unit-tests more stable (@snakefoot) - [#2603](https://github.com/nlog/nlog/pull/2603) MultiFileWatcher - Improve error handling if FileSystemWatcher fails (@snakefoot) ### Version 4.5-rc06 (2018/02/20) - [#2585](https://github.com/nlog/nlog/pull/2585) NLog 4.5 rc6 version and changelog (#2585) (@304NotModified) - [#2581](https://github.com/nlog/nlog/pull/2581) MessageTemplateParameter(s) ctors to internal (@304NotModified) - [#2576](https://github.com/nlog/nlog/pull/2576) Fix possible infinite loop in message template parser + better handling incorrect templates (@304NotModified) - [#2580](https://github.com/nlog/nlog/pull/2580) ColoredConsoleTarget.cs: Fix typo (@perlun) ### Version 4.5-rc05 (2018/02/13) - [#2571](https://github.com/nlog/nlog/pull/2571) 4.5 rc5 version and release notes (@304NotModified) - [#2572](https://github.com/nlog/nlog/pull/2572) copyright 2018 (@304NotModified) - [#2570](https://github.com/nlog/nlog/pull/2570) Update nuspec NLog.Config and NLog.Schema (@304NotModified) - [#2542](https://github.com/nlog/nlog/pull/2542) Added TooManyStructuredParametersShouldKeepBeInParamList testcase (@304NotModified) - [#2467](https://github.com/nlog/nlog/pull/2467) TargetWithContext - Easier to capture snapshot of MDLC and NDLC context (#2467) (@snakefoot) - [#2555](https://github.com/nlog/nlog/pull/2555) JsonLayout - Added MaxRecursionLimit and set default to 0 (@snakefoot) - [#2568](https://github.com/nlog/nlog/pull/2568) WebServiceTarget - Rollback added Group-Layout (@snakefoot) - [#2544](https://github.com/nlog/nlog/pull/2544) MessageTemplate renderer with support for mixed mode templates (@snakefoot) - [#2538](https://github.com/nlog/nlog/pull/2538) Renamed ValueSerializer to ValueFormatter (@snakefoot) - [#2554](https://github.com/nlog/nlog/pull/2554) LogBuilder - Check level before allocation of Properties-dictionary (@snakefoot) - [#2550](https://github.com/nlog/nlog/pull/2550) DefaultJsonSerializer - Reflection should skip index-item-properties (@snakefoot) - [#2549](https://github.com/nlog/nlog/pull/2549) LoggingConfiguration - FindTargetByName should also find target + fix for logging on a target even after removed (@snakefoot) - [#2548](https://github.com/nlog/nlog/pull/2548) IAppDomain.FriendlyName should also work on NetStandard15 (@snakefoot) - [#2563](https://github.com/nlog/nlog/pull/2563) WebService-Target fails internally with PlatformNotSupportedException on NetCore (@snakefoot) - [#2560](https://github.com/nlog/nlog/pull/2560) Network/NLogViewer/Chainsaw Target - Enabled OptimizeBufferReuse by default, but not for sub classes (@snakefoot) - [#2551](https://github.com/nlog/nlog/pull/2551) Blackhole LoggingRule without targets (@snakefoot) - [#2534](https://github.com/nlog/nlog/pull/2534) Docs for DefaultJsonSerializer/(i)ValueSerializer (#2534) (@304NotModified) - [#2519](https://github.com/nlog/nlog/pull/2519) RegisterItemsFromAssembly - Include assemblies from nuget packages (Strict) (@304NotModified, @snakefoot) - [#2524](https://github.com/nlog/nlog/pull/2524) FileTarget - Dynamic archive mode with more strict file-mask for cleanup (@snakefoot) - [#2518](https://github.com/nlog/nlog/pull/2518) DatabaseTarget - Added DbProvider System.Data.SqlClient for NetStandard (@snakefoot) - [#2514](https://github.com/nlog/nlog/pull/2514) Added missing docgen for different options (Less noise in appveyor) (@snakefoot) ### Version 4.5-rc04 (2018/01/15) - [#2490](https://github.com/nlog/nlog/pull/2490) LogEventInfo.MessageTemplateParameters as class instead of interface (#2490) (@snakefoot) - [#2510](https://github.com/nlog/nlog/pull/2510) Database target entity framework connection string (@snakefoot) - [#2513](https://github.com/nlog/nlog/pull/2513) Update docs for [AppDomainFixedOutput], remove [AppDomainFixedOutput] on ${currentDir} (@NLog) - [#2512](https://github.com/nlog/nlog/pull/2512) LogManager.LoadConfiguration - Support relative paths by default (@snakefoot) - [#2507](https://github.com/nlog/nlog/pull/2507) Reduce string allocations for logevents with single target destination (@snakefoot) - [#2491](https://github.com/nlog/nlog/pull/2491) Added ${currentDir} (#2491) (@UgurAldanmaz) - [#2500](https://github.com/nlog/nlog/pull/2500) ${gdc}, ${mdc} & {mdlc} - Support Format parameter (@snakefoot) - [#2497](https://github.com/nlog/nlog/pull/2497) RegisterItemsFromAssembly - Include assemblies from nuget packages (Fix) (@snakefoot) - [#2472](https://github.com/nlog/nlog/pull/2472) LogManager.LoadConfiguration - Prepare for custom config file readers (@snakefoot) - [#2486](https://github.com/nlog/nlog/pull/2486) JsonConverter- Sanitize Exception.Data dictionary keys option (on by default) (@snakefoot) - [#2495](https://github.com/nlog/nlog/pull/2495) MultiFileWatcher - Detach from FileSystemWatcher before disposing (@snakefoot) - [#2493](https://github.com/nlog/nlog/pull/2493) RegisterItemsFromAssembly - Include assemblies from nuget packages (@snakefoot) - [#2487](https://github.com/nlog/nlog/pull/2487) Adds version types to AssemblyVersion layout renderer (#2487) (@alexangas) - [#2464](https://github.com/nlog/nlog/pull/2464) Add methods to enabling/disabling LogLevels (@MikeFH) - [#2477](https://github.com/nlog/nlog/pull/2477) fix typo (@heldersepu) - [#2485](https://github.com/nlog/nlog/pull/2485) FileTarget - Dispose Archive-Mutex after completing file-archive (@snakefoot) - [#2475](https://github.com/nlog/nlog/pull/2475) Fix XmlLoggingConfiguration reloading (@MikeFH) - [#2471](https://github.com/nlog/nlog/pull/2471) TreatWarningsAsErrors = true (@snakefoot) - [#2462](https://github.com/nlog/nlog/pull/2462) AsyncLogEventInfo - Removed private setter (@snakefoot) ### Version 4.5-rc03 (2017/12/11) - [#2460](https://github.com/nlog/nlog/pull/2460) NLog 4.5 rc3 version and changelog (@304NotModified) - [#2459](https://github.com/nlog/nlog/pull/2459) StringBuilderExt.CopyToStream - Optimize MemoryStream allocation (@snakefoot) - [#2456](https://github.com/nlog/nlog/pull/2456) FileTarget: Support byte order mark (optional) (#2456) (@KYegres) - [#2453](https://github.com/nlog/nlog/pull/2453) NestedDiagnosticsContext - Only allocate Stack-object on Write (@snakefoot) - [#2458](https://github.com/nlog/nlog/pull/2458) Document and (minor) refactor on MruCache class (@ie-zero) - [#2452](https://github.com/nlog/nlog/pull/2452) ThreadLocalStorageHelper - NetStandard only allocate when needed (@snakefoot) ### Version 4.5-rc02 (2017/12/04) - [#2444](https://github.com/nlog/nlog/pull/2444) NLog 4.5 RC2 version and changelog (@304NotModified) - [#2450](https://github.com/nlog/nlog/pull/2450) No need to call type(T) (@304NotModified) - [#2451](https://github.com/nlog/nlog/pull/2451) FileTarget - Improved and less internal logging (@snakefoot) - [#2449](https://github.com/nlog/nlog/pull/2449) Refactor: fix comment, remove unused, cleanup, String ->` string etc (#2449) (@304NotModified) - [#2447](https://github.com/nlog/nlog/pull/2447) CallSiteInformation - Prepare for fast classname lookup from filename and linenumber (@snakefoot) - [#2446](https://github.com/nlog/nlog/pull/2446) Refactor - split methodes, remove duplicates (#2446) (@304NotModified) - [#2437](https://github.com/nlog/nlog/pull/2437) Create regex-matches condition method (#2437) (@MikeFH) - [#2441](https://github.com/nlog/nlog/pull/2441) Support for UWP platform (@snakefoot) - [#2439](https://github.com/nlog/nlog/pull/2439) Better config Better Code Hub (@304NotModified) - [#2431](https://github.com/nlog/nlog/pull/2431) NetCoreApp - Improve auto loading of NLog extension dlls (@snakefoot) - [#2418](https://github.com/nlog/nlog/pull/2418) LoggingConfiguration - Modify and clone LoggingRules under lock (@snakefoot) - [#2422](https://github.com/nlog/nlog/pull/2422) Avoid unnecessary string-allocation, skip unnecessary lock (@snakefoot) - [#2419](https://github.com/nlog/nlog/pull/2419) Logger - Added missing MessageTemplateFormatMethodAttribute + removed obsolete internal method (@snakefoot) - [#2421](https://github.com/nlog/nlog/pull/2421) Changed IIncludeContext to internal interface until someone needs it (@snakefoot) - [#2417](https://github.com/nlog/nlog/pull/2417) IsMono - Cache Type.GetType to avoid constant AppDomain.TypeResolve events (@snakefoot) - [#2420](https://github.com/nlog/nlog/pull/2420) Merged CallSite Test from PR1812 (@snakefoot) ### Version 4.5-rc01 (2017/11/23) - [#2414](https://github.com/nlog/nlog/pull/2414) Revert breaking change of NestedDiagnosticsLogicalContext.Pop() (@304NotModified) - [#2415](https://github.com/nlog/nlog/pull/2415) NetStandard15 - Moved dependency System.Xml.XmlSerializer to NLog.Wcf (@snakefoot) - [#2413](https://github.com/nlog/nlog/pull/2413) NestedDiagnosticsLogicalContext - Protect against double dispose (@snakefoot) - [#2412](https://github.com/nlog/nlog/pull/2412) MessageTemplate - Render test of DateTime, TimeSpan, DateTimeOffset (@snakefoot) - [#2411](https://github.com/nlog/nlog/pull/2411) Create SequenceIdLayoutRenderer (@MikeFH) - [#2409](https://github.com/nlog/nlog/pull/2409) Revert "Avoid struct copy on readonly field access" (@snakefoot) - [#2403](https://github.com/nlog/nlog/pull/2403) NLog 4.5 beta 8 (@304NotModified) - [#2406](https://github.com/nlog/nlog/pull/2406) From [StringFormatMethod] to [MessageTemplateFormatMethod] (@304NotModified) - [#2402](https://github.com/nlog/nlog/pull/2402) Introduced NLog.Wcf and Nlog.WindowsIdentity for .NET standard (@snakefoot) - [#2404](https://github.com/nlog/nlog/pull/2404) Updated NLog viewer target defaults (@304NotModified) - [#2405](https://github.com/nlog/nlog/pull/2405) Added unit test for JsonLayout - serialize of objects (@304NotModified) - [#2407](https://github.com/nlog/nlog/pull/2407) NLogTraceListener - set DisableFlush true by default (@snakefoot) - [#2401](https://github.com/nlog/nlog/pull/2401) MailTarget is supported by NetStandard2.0 (but without SmtpSection) (@snakefoot) - [#2398](https://github.com/nlog/nlog/pull/2398) Log4JXml - Fixed initalization of XmlWriterSettings for IndentXml (@snakefoot) - [#2386](https://github.com/nlog/nlog/pull/2386) LogEventInfo.StackTrace moved into CallSiteInformation (@snakefoot) - [#2399](https://github.com/nlog/nlog/pull/2399) Avoid struct copy on readonly field access (@snakefoot) - [#2389](https://github.com/nlog/nlog/pull/2389) Fixed Sonar Lint code analysis warnings (@snakefoot) - [#2396](https://github.com/nlog/nlog/pull/2396) Update xunit and Microsoft.NET.Test.Sdk (@304NotModified) - [#2387](https://github.com/nlog/nlog/pull/2387) JsonConverter - Do not include static properties by default (@snakefoot) - [#2392](https://github.com/nlog/nlog/pull/2392) Removed unneeded default references like System.Drawing for NetFramework (@snakefoot) - [#2390](https://github.com/nlog/nlog/pull/2390) NLogViewerTarget - Enable override of the Logger-name (@snakefoot) - [#2385](https://github.com/nlog/nlog/pull/2385) FileTarget - ArchiveMutex only created when needed (@snakefoot) - [#2378](https://github.com/nlog/nlog/pull/2378) Target - Precalculate Layout should ignore sub-layouts for complex layouts (@snakefoot) - [#2388](https://github.com/nlog/nlog/pull/2388) PropertiesDictionary - Removed obsolete (private) method (@snakefoot) - [#2384](https://github.com/nlog/nlog/pull/2384) InternalLogger should work when NetCore loads NetFramework DLL (@snakefoot) - [#2377](https://github.com/nlog/nlog/pull/2377) NDLC - Perform low resolution scope timing (@snakefoot) - [#2372](https://github.com/nlog/nlog/pull/2372) Log4JXmlEventLayoutRenderer - Minor platform fixes for IncludeNdlc (@snakefoot) - [#2371](https://github.com/nlog/nlog/pull/2371) FileTarget - Enable archive mutex for Unix File Appender (if available) (@snakefoot) - [#2375](https://github.com/nlog/nlog/pull/2375) WebServiceTarget - Allow configuration of proxy address (@snakefoot) - [#2362](https://github.com/nlog/nlog/pull/2362) NLog - NETSTANDARD1_5 (Cleanup package references) (@snakefoot) - [#2361](https://github.com/nlog/nlog/pull/2361) Use expression-bodied members (@c0shea) ### Version 4.5-beta07 (2017/10/15) - [#2359](https://github.com/nlog/nlog/pull/2359) WrapperLayoutRendererBase - Transform with access to LogEventInfo (@snakefoot) - [#2357](https://github.com/nlog/nlog/pull/2357) ExceptionLayoutRenderer - Support Serialize Format (@snakefoot) - [#2358](https://github.com/nlog/nlog/pull/2358) WrapperLayoutRendererBuilderBase - Transform with access to LogEventInfo (@snakefoot) - [#2314](https://github.com/nlog/nlog/pull/2314) Refactor InternalLogger class (@304NotModified, @ie-zero) - [#2356](https://github.com/nlog/nlog/pull/2356) NLog - MessageTemplates - Renamed config to parseMessageTemplates (@snakefoot) - [#2353](https://github.com/nlog/nlog/pull/2353) remove old package.config (@304NotModified) - [#2354](https://github.com/nlog/nlog/pull/2354) NLog - NETSTANDARD1_5 (revert breaking change) (@snakefoot) - [#2342](https://github.com/nlog/nlog/pull/2342) Remove redundant qualifiers (#2342) (@c0shea) - [#2349](https://github.com/nlog/nlog/pull/2349) NLog - NETSTANDARD1_5 (Fix uppercase with culture) (@snakefoot) - [#2341](https://github.com/nlog/nlog/pull/2341) NLog - NETSTANDARD1_5 (@snakefoot) ### Version 4.5-beta06 (2017/10/12) - [#2346](https://github.com/nlog/nlog/pull/2346) Add messageTemplateParser to XSD (@304NotModified) - [#2348](https://github.com/nlog/nlog/pull/2348) NLog MessageTemplateParameter with CaptureType (@snakefoot) ### Version 4.5-beta05 (2017/10/12) - [#2340](https://github.com/nlog/nlog/pull/2340) NLog - MessageTemplateParameters - Always parse when IsPositional (@304NotModified, @snakefoot) - [#2337](https://github.com/nlog/nlog/pull/2337) Use string interpolation (@c0shea) - [#2327](https://github.com/nlog/nlog/pull/2327) Naming: consistent private fields (@304NotModified) ### Version 4.5-beta04 (2017/10/10) - [#2318](https://github.com/nlog/nlog/pull/2318) NLog 4.5 beta 4 (@304NotModified) - [#2326](https://github.com/nlog/nlog/pull/2326) NLog - ValueSerializer - Faster integer and enum (@snakefoot) - [#2328](https://github.com/nlog/nlog/pull/2328) fix xunit warning (@304NotModified) - [#2117](https://github.com/nlog/nlog/pull/2117) Added IIncludeContext, implemented missing properties, added includeNdlc, sync NDLC and NDC (@304NotModified) - [#2317](https://github.com/nlog/nlog/pull/2317) More explicit side effect (@304NotModified) - [#2290](https://github.com/nlog/nlog/pull/2290) Do not report wrapped targets as unused targets (#2290) (@thesmallbang) - [#2319](https://github.com/nlog/nlog/pull/2319) NLog - MessageTemplateParameter - IsReservedFormat (@snakefoot) - [#2316](https://github.com/nlog/nlog/pull/2316) LogManager.LogFactory public (@304NotModified) - [#2208](https://github.com/nlog/nlog/pull/2208) Added Structured events / Message Templates (@snakefoot) - [#2312](https://github.com/nlog/nlog/pull/2312) Improve stability of unstable test on Travis: BufferingTargetWrapperA… (@304NotModified) - [#2309](https://github.com/nlog/nlog/pull/2309) 2017 copyright in T4 files (@304NotModified) - [#2292](https://github.com/nlog/nlog/pull/2292) ${callsite} added CleanNamesOfAsyncContinuations option (#2292) (@304NotModified) - [#2310](https://github.com/nlog/nlog/pull/2310) Upgrade xUnit to 2.3.0 RTM (@304NotModified) - [#2313](https://github.com/nlog/nlog/pull/2313) Removal of old package.config files (@304NotModified) - [#1872](https://github.com/nlog/nlog/pull/1872) FileTarget: more internal logging (@304NotModified) - [#1897](https://github.com/nlog/nlog/pull/1897) LogFactory - Fixed EventArgs for ConfigurationChanged (@snakefoot) - [#2301](https://github.com/nlog/nlog/pull/2301) Docs, rename and refactor of PropertiesDictionary/MessageTemplateParameters (@304NotModified) - [#2302](https://github.com/nlog/nlog/pull/2302) Copyright to 2017 (@304NotModified) - [#2262](https://github.com/nlog/nlog/pull/2262) LogEventInfo.MessageTemplate - Subset of LogEventInfo.Properties (@snakefoot) - [#2300](https://github.com/nlog/nlog/pull/2300) Fixed title (@304NotModified) ### Version 4.5-beta03 (2017/09/30) - [#2298](https://github.com/nlog/nlog/pull/2298) Search also for lowercase nlog.config (@304NotModified) - [#2297](https://github.com/nlog/nlog/pull/2297) WhenRepeatedFilter - Log after timeout (@snakefoot) ### Version 4.5-beta01 (2017/09/16) - [#2263](https://github.com/nlog/nlog/pull/2263) Support .NET Standard 2.0 and move to VS 2017 (@snakefoot) ### Version 4.4.13 (2018/02/28) **Fixes** - [#2600](https://github.com/nlog/nlog/pull/2600) Fix 'System.ReadOnlySpan`1[System.Char]' cannot be converted to type 'System.String' (@snakefoot) ### Version 4.4.12 (2017/08/08) **Fixes** - [#2229](https://github.com/nlog/nlog/pull/2229) Fix: ReconfigExistingLoggers sometimes throws an Exception (@jpdillingham) ### Version 4.4.11 (2017/06/17) **Fixes** - [#2164](https://github.com/nlog/nlog/pull/2164) JsonLayout - Don't mark ThreadAgnostic when IncludeMdc or IncludeMdlc is enabled (@snakefoot) ### Version 4.4.10 (2017/05/31) **Features** - [#2110](https://github.com/nlog/nlog/pull/2110) NdlcLayoutRenderer - Nested Diagnostics Logical Context (@snakefoot) - [#2114](https://github.com/nlog/nlog/pull/2114) EventlogTarget: Support for MaximumKilobytes (@304NotModified, @ajitpeter) - [#2109](https://github.com/nlog/nlog/pull/2109) JsonLayout - IncludeMdc and IncludeMdlc (@snakefoot) **Fixes** - [#2138](https://github.com/nlog/nlog/pull/2138) ReloadConfigOnTimer - fix potential NullReferenceException (@snakefoot) - [#2113](https://github.com/nlog/nlog/pull/2113) BugFix: `<targets>` after `<rules>` won't work (@304NotModified, @Moafak) - [#2131](https://github.com/nlog/nlog/pull/2131) Fix : LogManager.ReconfigureExistingLoggers() could throw InvalidOperationException (@304NotModified, @jpdillingham) **Improvements** - [#2137](https://github.com/nlog/nlog/pull/2137) NLogTraceListener - Reduce overhead by checking LogLevel (@snakefoot) - [#2112](https://github.com/nlog/nlog/pull/2112) LogReceiverWebServiceTarget - Ensure PrecalculateVolatileLayouts (@snakefoot) - [#2103](https://github.com/nlog/nlog/pull/2103) Improve Install of targets / crash Install on Databasetarget. (@M4ttsson) - [#2101](https://github.com/nlog/nlog/pull/2101) LogFactory.Shutdown - Add warning on target flush timeout (@snakefoot) ### Version 4.4.9 **Features** - [#2090](https://github.com/nlog/nlog/pull/2090) ${log4jxmlevent} - Added IncludeAllProperties option (@snakefoot) - [#2090](https://github.com/nlog/nlog/pull/2090) Log4JXmlEvent Layout - Added IncludeAllProperties, IncludeMdlc and IncludeMdc option (@snakefoot) **Fixes** - [#2090](https://github.com/nlog/nlog/pull/2090) Log4JXmlEvent Layout - Fixed bug with empty nlog:properties (@snakefoot) - [#2093](https://github.com/nlog/nlog/pull/2093) Fixed bug to logging by day of week (@RussianDragon) - [#2095](https://github.com/nlog/nlog/pull/2095) Fix: include ignoreErrors attribute not working for non-existent file (@304NotModified, @ghills) ### Version 4.4.8 (2017/04/28) **Features** - [#2078](https://github.com/nlog/nlog/pull/2078) Include MDLC in log4j renderer (option) (@thoemmi) ### Version 4.4.7 (2017/04/25) **Features** - [#2063](https://github.com/nlog/nlog/pull/2063) JsonLayout - Added JsonAttribute property EscapeUnicode (@snakefoot) **Improvements** - [#2075](https://github.com/nlog/nlog/pull/2075) StackTraceLayoutRenderer with Raw format should display source FileName (@snakefoot) - [#2067](https://github.com/nlog/nlog/pull/2067) ${EventProperties}, ${newline}, ${basedir} & ${tempdir} as ThreadAgnostic (performance improvement) (@snakefoot) - [#2061](https://github.com/nlog/nlog/pull/2061) MethodCallTarget - Fixed possible null-reference-exception on initialize (@snakefoot) ## Version 4.4.6 (2017/04/11) **Features** - [#2006](https://github.com/nlog/nlog/pull/2006) Added AsyncTaskTarget - Base class for using async methods (@snakefoot) - [#2051](https://github.com/nlog/nlog/pull/2051) Added LogMessageGenerator overloads for exceptions (#2051) (@c0shea) - [#2034](https://github.com/nlog/nlog/pull/2034) ${level} add format option (full, single char and ordinal) (#2034) (@c0shea) - [#2042](https://github.com/nlog/nlog/pull/2042) AutoFlushTargetWrapper - Added AsyncFlush property (@snakefoot) **Improvements** - [#2048](https://github.com/nlog/nlog/pull/2048) Layout - Ensure StackTraceUsage works for all types of Layout (@snakefoot) - [#2041](https://github.com/nlog/nlog/pull/2041) Reduce memory allocations (AsyncContinuation exceptionHandler) & refactor (@snakefoot) - [#2040](https://github.com/nlog/nlog/pull/2040) WebServiceTarget - Avoid re-throwing exceptions in async completion method (@snakefoot) ### Version 4.4.5 (2017/03/28) **Fixes** - [#2010](https://github.com/nlog/nlog/pull/2010) LogFactory - Ensure to flush and close on shutdown - fixes broken logging (@snakefoot) - [#2017](https://github.com/nlog/nlog/pull/2017) WebServiceTarget - Fix boolean parameter conversion for Xml and Json (lowercase) (@snakefoot) **Improvements** - [#2017](https://github.com/nlog/nlog/pull/2017) Merged the JSON serializer code into DefaultJsonSerializer (@snakefoot) ### Version 4.4.4 (2017/03/10) **Features** - [#2000](https://github.com/nlog/nlog/pull/2000) Add weekly archival option to FileTarget (@dougthor42) - [#2009](https://github.com/nlog/nlog/pull/2009) Load assembly event (@304NotModified) - [#1917](https://github.com/nlog/nlog/pull/1917) Call NLogPackageLoader.Preload (static) for NLog packages on load (@304NotModified) **Improvements** - [#2007](https://github.com/nlog/nlog/pull/2007) Target.Close() - Extra logging to investigate shutdown order (@snakefoot) - [#2003](https://github.com/nlog/nlog/pull/2003) Update XSD for `<NLog>` options (@304NotModified) - [#1977](https://github.com/nlog/nlog/pull/1977) update xsd template (internallogger) for 4.4.3 version (@AuthorProxy) - [#1956](https://github.com/nlog/nlog/pull/1956) Improve docs ThreadAgnosticAttribute (#1956) (@304NotModified) - [#1992](https://github.com/nlog/nlog/pull/1992) Fixed merge error of XML documentation for Target Write-methods (@snakefoot) **Fixes** - [#1995](https://github.com/nlog/nlog/pull/1995) Proper apply default-target-parameters to nested targets in WrappedTargets (@nazim9214) ### Version 4.4.3 (2017/02/17) **Fixes** - [#1966](https://github.com/nlog/nlog/pull/1966) System.UriFormatException on load (Mono) (@JustArchi) - [#1960](https://github.com/nlog/nlog/pull/1960) EventLogTarget: Properly parse and set EventLog category (@marinsky) ### Version 4.4.2 (2017/02/06) **Features** - [#1799](https://github.com/nlog/nlog/pull/1799) FileTarget: performance improvement: 10-70% faster, less garbage collecting (3-4 times less) by reusing buffers (@snakefoot, @AndreGleichner) - [#1919](https://github.com/nlog/nlog/pull/1919) Func overloads for InternalLogger (@304NotModified) - [#1915](https://github.com/nlog/nlog/pull/1915) allow wildcard (*) in `<include>` (@304NotModified) - [#1914](https://github.com/nlog/nlog/pull/1914) basedir: added option processDir=true (@304NotModified) - [#1906](https://github.com/nlog/nlog/pull/1906) Allow Injecting basedir (@304NotModified) **Improvements** - [#1927](https://github.com/nlog/nlog/pull/1927) InternalLogger - Better support for multiple threads when using file (@snakefoot) - [#1871](https://github.com/nlog/nlog/pull/1871) Filetarget - Allocations optimization (#1871) (@nazim9214) - [#1931](https://github.com/nlog/nlog/pull/1931) FileTarget - Validate File CreationTimeUtc when non-Windows (@snakefoot) - [#1942](https://github.com/nlog/nlog/pull/1942) FileTarget - KeepFileOpen should watch for file deletion, but not every second (@snakefoot) - [#1876](https://github.com/nlog/nlog/pull/1876) FileTarget - Faster archive check by caching the static file-create-time (60-70% improvement) (#1876) (@snakefoot) - [#1878](https://github.com/nlog/nlog/pull/1878) FileTarget - KeepFileOpen should watch for file deletion (#1878) (@snakefoot) - [#1932](https://github.com/nlog/nlog/pull/1932) FileTarget - Faster rendering of filepath, when not ThreadAgnostic (@snakefoot) - [#1937](https://github.com/nlog/nlog/pull/1937) LogManager.Shutdown - Verify that active config exists (@snakefoot) - [#1926](https://github.com/nlog/nlog/pull/1926) RetryingWrapper - Allow closing target, even when busy retrying (@snakefoot) - [#1925](https://github.com/nlog/nlog/pull/1925) JsonLayout - Support Precalculate for async processing (@snakefoot) - [#1816](https://github.com/nlog/nlog/pull/1816) EventLogTarget - don't crash with invalid Category / EventId (@304NotModified) - [#1815](https://github.com/nlog/nlog/pull/1815) Better parsing for Layouts with int/bool type. (@304NotModified, @rymk) - [#1868](https://github.com/nlog/nlog/pull/1868) WebServiceTarget - FlushAsync - Avoid premature flush (#1868) (@snakefoot) - [#1899](https://github.com/nlog/nlog/pull/1899) LogManager.Shutdown - Use the official method for closing down (@snakefoot) **Fixes** - [#1886](https://github.com/nlog/nlog/pull/1886) FileTarget - Archive should not fail when ArchiveFileName matches FileName (@snakefoot) - [#1893](https://github.com/nlog/nlog/pull/1893) FileTarget - MONO doesn't like using the native Win32 API (@snakefoot) - [#1883](https://github.com/nlog/nlog/pull/1883) LogFactory.Dispose - Should always close down created targets (@snakefoot) ### Version 4.4.1 (2016/12/24) Summary: - Fixes for medium trust (@snakefoot, @304notmodified) - Performance multiple improvements for flush events (@snakefoot) - FileTarget: Improvements for archiving (@snakefoot) - FileTarget - Reopen filehandle when file write fails (@snakefoot) - ConsoleTarget: fix crash when console isn't available (@snakefoot) - NetworkTarget - UdpNetworkSender should exercise the provided Close-callback (@snakefoot) Detail: - [#1874](https://github.com/nlog/nlog/pull/1874) Fixes for medium trust (@snakefoot, @304notmodified) - [#1873](https://github.com/nlog/nlog/pull/1873) PartialTrustDomain - Handle SecurityException to allow startup and logging (#1873) (@snakefoot) - [#1859](https://github.com/nlog/nlog/pull/1859) FileTarget - MONO should also check SupportsSharableMutex (#1859) (@snakefoot) - [#1853](https://github.com/nlog/nlog/pull/1853) AsyncTargetWrapper - Flush should start immediately without waiting (#1853) (@snakefoot) - [#1858](https://github.com/nlog/nlog/pull/1858) FileTarget - Reopen filehandle when file write fails (#1858) (@snakefoot) - [#1867](https://github.com/nlog/nlog/pull/1867) FileTarget - Failing to delete old archive files, should not stop logging (@snakefoot) - [#1865](https://github.com/nlog/nlog/pull/1865) Compile MethodInfo into LateBoundMethod-delegate (ReflectedType is deprecated) (@snakefoot) - [#1850](https://github.com/nlog/nlog/pull/1850) ConsoleTarget - Apply Encoding on InitializeTarget, if Console available (#1850) (@snakefoot) - [#1862](https://github.com/nlog/nlog/pull/1862) SHFB config cleanup & simplify (@304NotModified) - [#1863](https://github.com/nlog/nlog/pull/1863) Minor cosmetic changes on FileTarget class (@ie-zero) - [#1861](https://github.com/nlog/nlog/pull/1861) Helper class ParameterUtils removed (@ie-zero) - [#1847](https://github.com/nlog/nlog/pull/1847) LogFactory.Dispose() fixed race condition with reloadtimer (#1847) (@snakefoot) - [#1849](https://github.com/nlog/nlog/pull/1849) NetworkTarget - UdpNetworkSender should exercise the provided Close-callback (@snakefoot) - [#1857](https://github.com/nlog/nlog/pull/1857) Fix immutability of LogLevel properties (@ie-zero) - [#1860](https://github.com/nlog/nlog/pull/1860) FileAppenderCache implements IDisposable (@ie-zero) - [#1848](https://github.com/nlog/nlog/pull/1848) Standarise implementation of events (@ie-zero) - [#1844](https://github.com/nlog/nlog/pull/1844) FileTarget - Mono2 runtime detection to skip using named archive-mutex (@snakefoot) ### Version 4.4 (2016/12/14) **Features** - [#1583](https://github.com/nlog/nlog/pull/1583) Don't stop logging when there is an invalid layoutrenderer in the layout. (@304NotModified) - [#1740](https://github.com/nlog/nlog/pull/1740) WebServiceTarget support for JSON & Injecting JSON serializer into NLog (#1740) (@tetrodoxin) - [#1754](https://github.com/nlog/nlog/pull/1754) JsonLayout: JsonLayout: add includeAllProperties & excludeProperties (@aireq) - [#1439](https://github.com/nlog/nlog/pull/1439) Allow comma separated values (List) for Layout Renderers in nlog.config (@304NotModified) - [#1782](https://github.com/nlog/nlog/pull/1782) Improvement on #1439: Support Generic (I)List and (I)Set for Target/Layout/Layout renderers properties in nlog.config (@304NotModified) - [#1769](https://github.com/nlog/nlog/pull/1769) Optionally keeping variables during configuration reload (@nazim9214) - [#1514](https://github.com/nlog/nlog/pull/1514) Add LimitingTargetWrapper (#1514) (@Jeinhaus) - [#1581](https://github.com/nlog/nlog/pull/1581) Registering Layout renderers with func (one line needed), easier registering layout/layoutrender/targets (@304NotModified) - [#1735](https://github.com/nlog/nlog/pull/1735) UrlHelper - Added standard support for UTF8 encoding, added support for RFC2396 & RFC3986 (#1735) (@snakefoot) - [#1768](https://github.com/nlog/nlog/pull/1768) ExceptionLayoutRenderer - Added support for AggregateException (@snakefoot) - [#1752](https://github.com/nlog/nlog/pull/1752) Layout processinfo with support for custom Format-string (@snakefoot) - [#1836](https://github.com/nlog/nlog/pull/1836) Callsite: add includeNamespace option (@304NotModified) - [#1817](https://github.com/nlog/nlog/pull/1817) Added condition to AutoFlushWrappper (@nazim9214) **Improvements** - [#1732](https://github.com/nlog/nlog/pull/1732) Handle duplicate attributes (error or using first occurence) in nlog.config (@nazim9214) - [#1778](https://github.com/nlog/nlog/pull/1778) ConsoleTarget - DetectConsoleAvailable - Disabled by default (@snakefoot) - [#1585](https://github.com/nlog/nlog/pull/1585) More clear internallog when reading XML config (@304NotModified) - [#1784](https://github.com/nlog/nlog/pull/1784) ProcessInfoLayoutRenderer - Applied usage of LateBoundMethod (@snakefoot) - [#1771](https://github.com/nlog/nlog/pull/1771) FileTarget - Added extra archive check is needed, after closing stale file handles (@snakefoot) - [#1779](https://github.com/nlog/nlog/pull/1779) Improve performance of filters (2-3 x faster) (@snakefoot) - [#1780](https://github.com/nlog/nlog/pull/1780) PropertiesLayoutRenderer - small performance improvement (@snakefoot) - [#1776](https://github.com/nlog/nlog/pull/1776) Don't crash on an invalid (xml) app.config by default (@304NotModified) - [#1763](https://github.com/nlog/nlog/pull/1763) JsonLayout - Performance improvements (@snakefoot) - [#1755](https://github.com/nlog/nlog/pull/1755) General performance improvement (@snakefoot) - [#1756](https://github.com/nlog/nlog/pull/1755) WindowsMultiProcessFileAppender (@snakefoot, @AndreGleichner) ### Version 4.3.11 (2016/11/07) **Improvements** - [#1700](https://github.com/nlog/nlog/pull/1700) Improved concurrency when multiple Logger threads are writing to async Target (@snakefoot) - [#1750](https://github.com/nlog/nlog/pull/1750) Log payload for NLogViewerTarget/NetworkTarget to Internal Logger (@304NotModified) - [#1745](https://github.com/nlog/nlog/pull/1745) FilePathLayout - Reduce memory-allocation for cleanup of filename (@snakefoot) - [#1746](https://github.com/nlog/nlog/pull/1746) DateLayout - Reduce memory allocation when low time resolution (@snakefoot) - [#1719](https://github.com/nlog/nlog/pull/1719) Avoid (Internal)Logger-boxing and params-array-allocation on Exception (@snakefoot) - [#1683](https://github.com/nlog/nlog/pull/1683) FileTarget - Faster async processing of LogEvents for the same file (@snakefoot) - [#1730](https://github.com/nlog/nlog/pull/1730) Conditions: Try interpreting first as non-string value (@304NotModified) - [#1814](https://github.com/nlog/nlog/pull/1814) Improve [Obsolete] warnings - include the Nlog version when it became obsolete (#1814) (@ie-zero) - [#1809](https://github.com/nlog/nlog/pull/1809) FileTarget - Close stale file handles outside archive mutex lock (@snakefoot) **Fixes** - [#1749](https://github.com/nlog/nlog/pull/1749) Try-catch for permission when autoloading - fixing Android permission issue (@304NotModified) - [#1751](https://github.com/nlog/nlog/pull/1751) ExceptionLayoutRenderer: prevent nullrefexception when exception is null (@304NotModified) - [#1706](https://github.com/nlog/nlog/pull/1706) Console Target Automatic Detect if console is available on Mono (@snakefoot) ### Version 4.3.10 (2016/10/11) **Features** - [#1680](https://github.com/nlog/nlog/pull/1680) Append to existing archive file (@304NotModified) - [#1669](https://github.com/nlog/nlog/pull/1669) AsyncTargetWrapper - Allow TimeToSleepBetweenBatches = 0 (@snakefoot) - [#1668](https://github.com/nlog/nlog/pull/1668) Console Target Automatic Detect if console is available (@snakefoot) **Improvements** - [#1697](https://github.com/nlog/nlog/pull/1697) Archiving should never fail writing (@304NotModified) - [#1695](https://github.com/nlog/nlog/pull/1695) Performance: Counter/ProcessId/ThreadId-LayoutRenderer allocations less memory (@snakefoot) - [#1693](https://github.com/nlog/nlog/pull/1693) Performance (allocation) improvement in Aysnc handling (@snakefoot) - [#1694](https://github.com/nlog/nlog/pull/1694) FilePathLayout - CleanupInvalidFilePath - Happy path should not allocate (@snakefoot) - [#1675](https://github.com/nlog/nlog/pull/1675) unseal databasetarget and make BuildConnectionString protected (@304NotModified) - [#1690](https://github.com/nlog/nlog/pull/1690) Fix memory leak in AppDomainWrapper (@snakefoot) - [#1702](https://github.com/nlog/nlog/pull/1702) Performance: InternalLogger should only allocate params-array when needed (@snakefoot) **Fixes** - [#1676](https://github.com/nlog/nlog/pull/1676) Fix FileTarget on Xamarin: Remove mutex usage for Xamarin 'cause of runtime exceptions (@304NotModified) - [#1591](https://github.com/nlog/nlog/pull/1591) Count operation on AsyncRequestQueue is not thread-safe (@snakefoot) ### Version 4.3.9 (2016/09/18) **Features** - [#1641](https://github.com/nlog/nlog/pull/1641) FileTarget: Add WriteFooterOnArchivingOnly parameter. (@bhaeussermann) - [#1628](https://github.com/nlog/nlog/pull/1628) Add ExceptionDataSeparator option for ${exception} (@FroggieFrog) - [#1626](https://github.com/nlog/nlog/pull/1626) cachekey option for cache layout wrapper (@304NotModified) **Improvements** - [#1643](https://github.com/nlog/nlog/pull/1643) Pause logging when the race condition occurs in (Colored)Console Target (@304NotModified) - [#1632](https://github.com/nlog/nlog/pull/1632) Prevent possible crash when archiving in folder with non-archived files (@304NotModified) **Fixes** - [#1646](https://github.com/nlog/nlog/pull/1646) FileTarget: Fix file archive race-condition. (@bhaeussermann) - [#1642](https://github.com/nlog/nlog/pull/1642) MDLC: fixing mutable dictionary issue (improvement) (@vlardn) - [#1635](https://github.com/nlog/nlog/pull/1635) Fix ${tempdir} and ${nlogdir} if both have dir and file. (@304NotModified) ### Version 4.3.8 (2016/09/05) **Features** - [#1619](https://github.com/NLog/NLog/pull/1619) NetworkTarget: Added option to specify EOL (@kevindaub) **Improvements** - [#1596](https://github.com/NLog/NLog/pull/1596) Performance tweak in NLog routing (@304NotModified) - [#1593](https://github.com/NLog/NLog/pull/1593) FileTarget: large performance improvement - back to 1 million/sec (@304NotModified) - [#1621](https://github.com/nlog/nlog/pull/1621) FileTarget: writing to non-existing drive was slowing down NLog a lot (@304NotModified) **Fixes** - [#1616](https://github.com/nlog/nlog/pull/1616) FileTarget: Don't throw an exception if a dir is missing when deleting old files on startup (@304NotModified) ### Version 4.3.7 (2016/08/06) **Features** - [#1469](https://github.com/nlog/nlog/pull/1469) Allow overwriting possible nlog configuration file paths (@304NotModified) - [#1578](https://github.com/nlog/nlog/pull/1578) Add support for name parameter on ${Assembly-version} (@304NotModified) - [#1580](https://github.com/nlog/nlog/pull/1580) Added option to not render empty literals on nested json objects (@johnkors) **Improvements** - [#1558](https://github.com/nlog/nlog/pull/1558) Callsite layout renderer: improve string comparison test (performance) (@304NotModified) - [#1582](https://github.com/nlog/nlog/pull/1582) FileTarget: Performance improvement for CleanupInvalidFileNameChars (@304NotModified) **Fixes** - [#1556](https://github.com/nlog/nlog/pull/1556) Bugfix: Use the culture when rendering the layout (@304NotModified) ### Version 4.3.6 (2016/07/24) **Features** - [#1531](https://github.com/nlog/nlog/pull/1531) Support Android 4.4 (@304NotModified) - [#1551](https://github.com/nlog/nlog/pull/1551) Addded CompoundLayout (@luigiberrettini) **Fixes** - [#1548](https://github.com/nlog/nlog/pull/1548) Bugfix: Can't update EventLog's Source property (@304NotModified, @Page-Not-Found) - [#1553](https://github.com/nlog/nlog/pull/1553) Bugfix: Throw configException when registering invalid extension assembly/type. (@304NotModified, @Jeinhaus) - [#1547](https://github.com/nlog/nlog/pull/1547) LogReceiverWebServiceTarget is leaking communication channels (@MartinTherriault) ### Version 4.3.5 (2016/06/13) **Features** - [#1471](https://github.com/nlog/nlog/pull/1471) Add else option to ${when} (@304NotModified) - [#1481](https://github.com/nlog/nlog/pull/1481) get items for diagnostic contexts (DiagnosticsContextes, GetNames() method) (@tiljanssen) **Fixes** - [#1504](https://github.com/nlog/nlog/pull/1504) Fix ${callsite} with async method with return value (@PELNZ) ### Version 4.3.4 (2016/05/16) **Features** - [#1423](https://github.com/nlog/nlog/pull/1423) Injection of zip-compressor for fileTarget (@AndreGleichner) - [#1434](https://github.com/nlog/nlog/pull/1434) Added constructors with name argument to the target types (@304NotModified, @flyingcroissant) - [#1400](https://github.com/nlog/nlog/pull/1400) Added WrapLineLayoutRendererWrapper (@mathieubrun) **Improvements** - [#1456](https://github.com/nlog/nlog/pull/1456) FileTarget: Improvements in FileTarget archive cleanup. (@bhaeussermann) - [#1417](https://github.com/nlog/nlog/pull/1417) FileTarget prevent stackoverflow after setting FileName property on init (@304NotModified) **Fixes** - [#1454](https://github.com/nlog/nlog/pull/1454) Fix LoggingRule.ToString (@304NotModified) - [#1453](https://github.com/nlog/nlog/pull/1453) Fix potential nullref exception in LogManager.Shutdown() (@304NotModified) - [#1450](https://github.com/nlog/nlog/pull/1450) Fix duplicate Target after config Initialize (@304NotModified) - [#1446](https://github.com/nlog/nlog/pull/1446) FileTarget: create dir if CreateDirs=true and replacing file content (@304NotModified) - [#1432](https://github.com/nlog/nlog/pull/1432) Check if directory NLog.dll is detected in actually exists (@gregmac) **Other** - [#1440](https://github.com/nlog/nlog/pull/1440) Added extra unit tests for context classes (@304NotModified) ### Version 4.3.3 (2016/04/28) - [#1411](https://github.com/nlog/nlog/pull/1411) MailTarget: fix "From" errors (bug introduced in NLog 4.3.2) (@304NotModified) ### Version 4.3.2 (2016/04/26) - [#1404](https://github.com/nlog/nlog/pull/1404) FileTarget cleanup: move to background thread. (@304NotModified) - [#1403](https://github.com/nlog/nlog/pull/1403) Fix filetarget: Thread was being aborted (#2) (@304NotModified) - [#1402](https://github.com/nlog/nlog/pull/1402) Getting the 'From' when UseSystemNetMailSettings is true (@MoaidHathot) - [#1401](https://github.com/nlog/nlog/pull/1401) Allow target configuration to support a hierachy of XML nodes (#1401) (@304NotModified) - [#2](https://github.com/nlog/nlog/pull/2) Fix filetarget: Thread was being aborted (#2) (@304NotModified) - [#1394](https://github.com/nlog/nlog/pull/1394) Make test methods public (#1394) (@luigiberrettini) - [#1393](https://github.com/nlog/nlog/pull/1393) Remove test dependency on locale (@luigiberrettini) ### Version 4.3.1 (2016/04/20) - [#1386](https://github.com/nlog/nlog/pull/1386) Fix "allLayouts is null" exception (@304NotModified) - [#1387](https://github.com/nlog/nlog/pull/1387) Fix filetarget: Thread was being aborted (@304NotModified) - [#1383](https://github.com/nlog/nlog/pull/1383) Fix configuration usage in `${var}` renderer (@bhaeussermann, @304NotModified) ### Version 4.3.0 (2016/04/16) - [#1211](https://github.com/nlog/nlog/pull/1211) Update nlog.config for 4.3 (@304NotModified) - [#1368](https://github.com/nlog/nlog/pull/1368) Update license (@304NotModified) ### Version 4.3.0-rc3 (2016/04/09) - [#1348](https://github.com/nlog/nlog/pull/1348) Fix nullref + fix relative path for file archive (@304NotModified) - [#1352](https://github.com/nlog/nlog/pull/1352) Fix for writing log file to root path (@304NotModified) - [#1357](https://github.com/nlog/nlog/pull/1357) autoload NLog.config in assets folder (Xamarin Android) (@304NotModified) - [#1358](https://github.com/nlog/nlog/pull/1358) no-recusive logging in internallogger. (@304NotModified) - [#1364](https://github.com/nlog/nlog/pull/1364) Fix stacktraceusage with more than 1 rule (@304NotModified) ### Version 4.3.0-rc2 (2016/03/26) - [#1335](https://github.com/nlog/nlog/pull/1335) Fix all build warnings (@304NotModified) - [#1336](https://github.com/nlog/nlog/pull/1336) Throw NLogConfigurationException if TimeToSleepBetweenBatches `<= 0` (@vincechan) - [#1333](https://github.com/nlog/nlog/pull/1333) Fix ${callsite} when loggerType can't be found due to inlining (@304NotModified) - [#1329](https://github.com/nlog/nlog/pull/1329) Update SHFB (@304NotModified) ### Version 4.3.0-rc1 (2016/03/22) - [#1323](https://github.com/nlog/nlog/pull/1323) Add TimeStamp options to XML, Appsetting and environment var (@304NotModified) - [#1286](https://github.com/nlog/nlog/pull/1286) Easier api: AddRule methods, fix AllTargets crash, fix IsLevelEnabled(off) crash, refactor internal (@304NotModified) - [#1317](https://github.com/nlog/nlog/pull/1317) don't require ProviderName attribute when using `<connectionStrings>` (app.config etc) (@304NotModified) - [#1316](https://github.com/nlog/nlog/pull/1316) Fix scan for stacktrace usage (bug never released) (@304NotModified) - [#1299](https://github.com/nlog/nlog/pull/1299) Also use logFactory for ThrowConfigExceptions (@304NotModified) - [#1309](https://github.com/nlog/nlog/pull/1309) Added nested json from xml unit test (@pysco68, @304NotModified) - [#1310](https://github.com/nlog/nlog/pull/1310) Fix threadsafe issue of GetLogger / GetCurrentClassLogger (+improve performance) (@304NotModified) - [#1313](https://github.com/nlog/nlog/pull/1313) Added the NLog.Owin.Logging badges to README packages list (@pysco68) - [#1222](https://github.com/nlog/nlog/pull/1222) internalLogger, write to System.Diagnostics.Debug / System.Diagnostics.Trace #1217 (@bryjamus) - [#1303](https://github.com/nlog/nlog/pull/1303) Fix threadsafe issue of ScanProperties3 (@304NotModified) - [#1273](https://github.com/nlog/nlog/pull/1273) Added the ability to allow virtual paths for SMTP pickup directory (@michaeljbaird) - [#1298](https://github.com/nlog/nlog/pull/1298) NullReferenceException fix for VariableLayoutRenderer (@neris) - [#1295](https://github.com/nlog/nlog/pull/1295) Fix Callsite render bug introducted in 4.3 beta (@304NotModified) - [#1285](https://github.com/nlog/nlog/pull/1285) Fix: {$processtime} has incorrect milliseconds formatting (@304NotModified) - [#1296](https://github.com/nlog/nlog/pull/1296) CachedLayoutRender: allow ClearCache as (ambient) property (@304NotModified) - [#1294](https://github.com/nlog/nlog/pull/1294) Fix thread-safe issue ScanProperties (@304NotModified) - [#1281](https://github.com/nlog/nlog/pull/1281) FileTargetTests: Fix runtime overflow-of-minute issue in DateArchive_SkipPeriod. (@bhaeussermann) - [#1274](https://github.com/nlog/nlog/pull/1274) FileTarget: Fix archive does not work when date in file name. (@bhaeussermann) - [#1275](https://github.com/nlog/nlog/pull/1275) Less logging for unstable unit tests (and also probably too much) (@304NotModified) - [#1270](https://github.com/nlog/nlog/pull/1270) Added testcase (NestedJsonAttrTest) (@304NotModified) - [#1279](https://github.com/nlog/nlog/pull/1279) Fix tests to ensure all AsyncTargetWrapper's are closed. (@bhaeussermann) - [#1238](https://github.com/nlog/nlog/pull/1238) Control throwing of NLogConfigurationExceptions (LogManager.ThrowConfigExceptions) (@304NotModified) - [#1265](https://github.com/nlog/nlog/pull/1265) More thread-safe method (@304NotModified) - [#1260](https://github.com/nlog/nlog/pull/1260) try read nlog.config in ios/android (@304NotModified) - [#1253](https://github.com/nlog/nlog/pull/1253) Added docs for UrlEncode (@304NotModified) - [#1252](https://github.com/nlog/nlog/pull/1252) improve InternalLoggerTests unit test (@304NotModified) - [#1259](https://github.com/nlog/nlog/pull/1259) Internallogger improvements (@304NotModified) - [#1258](https://github.com/nlog/nlog/pull/1258) fixed typo in NLog.config (@icnocop) - [#1256](https://github.com/nlog/nlog/pull/1256) Badges Shields.io ->` Badge.fury.io (@304NotModified) - [#1225](https://github.com/nlog/nlog/pull/1225) XmlLoggingConfiguration: Set config values on correct LogFactory object (@bhaeussermann, @304NotModified) - [#1](https://github.com/nlog/nlog/pull/1) Fix ambiguity in `cref` in comments. (@304NotModified) - [#1254](https://github.com/nlog/nlog/pull/1254) Remove SubversionScc / AnkhSVN info from solutions (@304NotModified) - [#1247](https://github.com/nlog/nlog/pull/1247) Init version issue template (@304NotModified) - [#1245](https://github.com/nlog/nlog/pull/1245) Add Logger.Swallow(Task task) (@breyed) - [#1246](https://github.com/nlog/nlog/pull/1246) added badges UWP / web.ASPNET5 (@304NotModified) - [#1227](https://github.com/nlog/nlog/pull/1227) LogFactory: Add generic-type versions of GetLogger() and GetCurrentClassLogger() (@bhaeussermann) - [#1242](https://github.com/nlog/nlog/pull/1242) Improve unit test (@304NotModified) - [#1213](https://github.com/nlog/nlog/pull/1213) Log more to InternalLogger (@304NotModified) - [#1240](https://github.com/nlog/nlog/pull/1240) Added StringHelpers + StringHelpers.IsNullOrWhiteSpace (@304NotModified) - [#1239](https://github.com/nlog/nlog/pull/1239) Fix unstable MDLC Unit test + MDLC free dataslot (@304NotModified, @MikeFH) - [#1236](https://github.com/nlog/nlog/pull/1236) Bugfix: Internallogger creates folder, even when turned off. (@eduardorascon) - [#1232](https://github.com/nlog/nlog/pull/1232) Fix HttpGet protocol for WebService (@MikeFH) - [#1223](https://github.com/nlog/nlog/pull/1223) Fix deadlock on Factory (@304NotModified) ### Version 4.3.0-beta2 (2016/02/04) - [#1220](https://github.com/nlog/nlog/pull/1220) FileTarget: Add internal logging for archive date. (@bhaeussermann) - [#1214](https://github.com/nlog/nlog/pull/1214) Better unit test cleanup between tests + fix threadsafe issue ScanProperties (@304NotModified) - [#1212](https://github.com/nlog/nlog/pull/1212) Support reading nlog.config from Android assets folder (@304NotModified) - [#1215](https://github.com/nlog/nlog/pull/1215) FileTarget: Archiving not working properly with AsyncWrapper (@bhaeussermann) - [#1216](https://github.com/nlog/nlog/pull/1216) Added more docs to InternalLogger (@304NotModified) - [#1207](https://github.com/nlog/nlog/pull/1207) FileTarget: Fix Footer for archiving. (@bhaeussermann) - [#1210](https://github.com/nlog/nlog/pull/1210) Added extra unit test (@304NotModified) - [#1191](https://github.com/nlog/nlog/pull/1191) Throw exception when base.InitializeTarget() is not called + inline GetAllLayouts() (@304NotModified) - [#1208](https://github.com/nlog/nlog/pull/1208) FileTargetTests: Supplemented ReplaceFileContentsOnEachWriteTest() to test with and without header and footer (@bhaeussermann) - [#1197](https://github.com/nlog/nlog/pull/1197) Improve XML Docs (@304NotModified) - [#1200](https://github.com/nlog/nlog/pull/1200) Added unit test for K datetime format (@304NotModified) ### Version 4.3.0-beta1 (2016/01/27) - [#1143](https://github.com/nlog/nlog/pull/1143) Consistent Exception handling v3 (@304NotModified) - [#1195](https://github.com/nlog/nlog/pull/1195) FileTarget: added ReplaceFileContentsOnEachWriteTest (@304NotModified) - [#925](https://github.com/nlog/nlog/pull/925) RegistryLayoutRenderer: Support for layouts, RegistryView (32, 64 bit) and all root key names (HKCU/HKLM etc) (@304NotModified, @Niklas-Peter) - [#1157](https://github.com/nlog/nlog/pull/1157) FIx (xml-) config classes for thread-safe issues (@304NotModified) - [#1183](https://github.com/nlog/nlog/pull/1183) FileTarget: Fix compress archive file not working when using concurrentWrites="True" and keepFileOpen="True" (@bhaeussermann) - [#1187](https://github.com/nlog/nlog/pull/1187) MethodCallTarget: allow optional parameters, no nullref exceptions. +unit tests (@304NotModified) - [#1171](https://github.com/nlog/nlog/pull/1171) Coloredconsole not compiled regex by default (@304NotModified) - [#1173](https://github.com/nlog/nlog/pull/1173) Unit test added for Variable node (@UgurAldanmaz) - [#1138](https://github.com/nlog/nlog/pull/1138) Callsite fix for async methods (@304NotModified) - [#1126](https://github.com/nlog/nlog/pull/1126) Fix and test archiving when writing to same file from different processes (@bhaeussermann) - [#1170](https://github.com/nlog/nlog/pull/1170) LogBuilder: add StringFormatMethod Annotations (@304NotModified) - [#1127](https://github.com/nlog/nlog/pull/1127) Max message length option for Eventlog target (@UgurAldanmaz) - [#1149](https://github.com/nlog/nlog/pull/1149) Fix crash during delete of old archives & archive delete optimization (@brutaldev) - [#1154](https://github.com/nlog/nlog/pull/1154) Fix nuget for Xamarin.iOs (@304NotModified) - [#1159](https://github.com/nlog/nlog/pull/1159) README-developers.md: Added pull request checklist. (@bhaeussermann) - [#1131](https://github.com/nlog/nlog/pull/1131) Reducing memory allocations in ShortDateLayoutRenderer by caching the formatted date. (@epignosisx) - [#1141](https://github.com/nlog/nlog/pull/1141) Remove code dup of InternalLogger (T4) (@304NotModified) - [#1144](https://github.com/nlog/nlog/pull/1144) add doc (@304NotModified) - [#1142](https://github.com/nlog/nlog/pull/1142) PropertyHelper: rename to readable names (@304NotModified) - [#1139](https://github.com/nlog/nlog/pull/1139) Reduce Memory Allocations in LongDateLayoutRenderer (@epignosisx) - [#1112](https://github.com/nlog/nlog/pull/1112) ColoredConsoleTarget performance improvements. (@bhaeussermann) - [#1135](https://github.com/nlog/nlog/pull/1135) FileTargetTests: Fix DateArchive_SkipPeriod test. (@bhaeussermann) - [#1119](https://github.com/nlog/nlog/pull/1119) FileTarget: Use last-write-time for archive file name (@bhaeussermann) - [#1089](https://github.com/nlog/nlog/pull/1089) Support For Relative Paths in the File Targets (@Page-Not-Found) - [#1068](https://github.com/nlog/nlog/pull/1068) Overhaul ExceptionLayoutRenderer (@Page-Not-Found) - [#1125](https://github.com/nlog/nlog/pull/1125) FileTarget: Fix continuous archiving bug. (@bhaeussermann) - [#1113](https://github.com/nlog/nlog/pull/1113) Bugfix: EventLogTarget OnOverflow=Split writes always to Info level (@UgurAldanmaz) - [#1116](https://github.com/nlog/nlog/pull/1116) Config: Implemented inheritance policy for autoReload in included config files (@bhaeussermann) - [#1100](https://github.com/nlog/nlog/pull/1100) FileTarget: Fix archive based on time does not always archive. (@bhaeussermann) - [#1110](https://github.com/nlog/nlog/pull/1110) Fix: Deadlock in NetworkTarget (@kt1996) - [#1109](https://github.com/nlog/nlog/pull/1109) FileTarget: Fix archiving for ArchiveFileName without a pattern. (@bhaeussermann) - [#1104](https://github.com/nlog/nlog/pull/1104) Merge from 4.2.3 (Improve performance of FileTarget, performance GDC) (@304NotModified, @epignosisx) - [#1095](https://github.com/nlog/nlog/pull/1095) Fix find calling method on stack trace (@304NotModified) - [#1099](https://github.com/nlog/nlog/pull/1099) Added extra callsite unit tests (@304NotModified) - [#1084](https://github.com/nlog/nlog/pull/1084) Log unused targets to internal logger (@UgurAldanmaz) ### Version 4.2.3 (2015/12/12) - [#1083](https://github.com/nlog/nlog/pull/1083) Changed the heading in Readme file (@Page-Not-Found) - [#1081](https://github.com/nlog/nlog/pull/1081) Update README.md (@UgurAldanmaz) - [#4](https://github.com/nlog/nlog/pull/4) Update from base repository (@304NotModified, @bhaeussermann, @ie-zero, @epignosisx, @stefandevo, @nathan-schubkegel) - [#1066](https://github.com/nlog/nlog/pull/1066) Add AllLevels and AllLoggingLevels to LogLevel.cs. (@rellis-of-rhindleton) - [#1062](https://github.com/nlog/nlog/pull/1062) Fix Xamarin Build in PR (and don't fail in fork) (@304NotModified) - [#1061](https://github.com/nlog/nlog/pull/1061) skip xamarin-dependent steps in appveyor PR builds (@nathan-schubkegel) - [#1040](https://github.com/nlog/nlog/pull/1040) Xamarin (iOS, Android) and Windows Phone 8 (@304NotModified, @stefandevo) - [#1041](https://github.com/nlog/nlog/pull/1041) EventLogTarget: Add overflow action for too large messages (@epignosisx) ### Version 4.2.2 (2015/11/21) - [#1054](https://github.com/nlog/nlog/pull/1054) LogReceiverWebServiceTarget.CreateLogReceiver() should be virtual (@304NotModified) - [#1048](https://github.com/nlog/nlog/pull/1048) Var layout renderer improvements (@304NotModified) - [#1043](https://github.com/nlog/nlog/pull/1043) Moved sourcecode tests to separate tool (@304NotModified) ### Version 4.2.1-RC1 (2015/11/13) - [#1031](https://github.com/nlog/nlog/pull/1031) NetworkTarget: linkedlist + configure max connections (@304NotModified) - [#1037](https://github.com/nlog/nlog/pull/1037) Added FilterResult tests (@304NotModified) - [#1036](https://github.com/nlog/nlog/pull/1036) Logbuilder tests + fix passing Off (@304NotModified) - [#1035](https://github.com/nlog/nlog/pull/1035) Added tests for Conditional logger (@304NotModified) - [#1033](https://github.com/nlog/nlog/pull/1033) Databasetarget: restored 'UseTransactions' and print warning if used (@304NotModified) - [#1032](https://github.com/nlog/nlog/pull/1032) Filetarget: Added tests for the 2 kind of slashes (@304NotModified) - [#1027](https://github.com/nlog/nlog/pull/1027) Reduce memory allocations in Logger.Log when using CsvLayout and JsonLayout (@epignosisx) - [#1020](https://github.com/nlog/nlog/pull/1020) Reduce memory allocations in Logger.Log by avoiding GetEnumerator. (@epignosisx) - [#1019](https://github.com/nlog/nlog/pull/1019) Issue #987: Filetarget: Max archives settings sometimes removes to many files (@bhaeussermann) - [#1021](https://github.com/nlog/nlog/pull/1021) Fix #2 ObjectGraphScanner.ScanProperties: Collection was modified (@304NotModified) - [#994](https://github.com/nlog/nlog/pull/994) Introduce FileAppenderCache class (@ie-zero) - [#968](https://github.com/nlog/nlog/pull/968) Fix: LogFactoryTests remove Windows specific values (@ie-zero) - [#999](https://github.com/nlog/nlog/pull/999) Unit Tests added to LogFactory class (@ie-zero) - [#1000](https://github.com/nlog/nlog/pull/1000) Fix methods' indentation in LogManager class (@ie-zero) - [#1001](https://github.com/nlog/nlog/pull/1001) Dump() now uses InternalLogger.Debug() consistent (@ie-zero) ### Version 4.2.0 (2015/10/24) - [#996](https://github.com/nlog/nlog/pull/996) ColoredConsoleTarget: Fixed broken WholeWords option of highlight-word. (@bhaeussermann) - [#995](https://github.com/nlog/nlog/pull/995) ArchiveFileCompression: auto add `.zip` to compressed filename when archiveName isn't specified (@bhaeussermann) - [#993](https://github.com/nlog/nlog/pull/993) changed to nuget appveyor account (@304NotModified) - [#992](https://github.com/nlog/nlog/pull/992) added logo (@304NotModified) - [#988](https://github.com/nlog/nlog/pull/988) Unit test for proving max-archive bug of #987 (@304NotModified) - [#991](https://github.com/nlog/nlog/pull/991) Document FileTarget inner properties/methods (@ie-zero) - [#986](https://github.com/nlog/nlog/pull/986) Added more unit tests for max archive with dates in files. (@304NotModified) - [#984](https://github.com/nlog/nlog/pull/984) Fixes #941. Add annotations for custom string formatting methods (@bhaeussermann) - [#985](https://github.com/nlog/nlog/pull/985) Fix: file archiving DateAndSequence & FileArchivePeriod.Day won't work always (wrong switching day detected) (@304NotModified) - [#982](https://github.com/nlog/nlog/pull/982) Document FileTarget inner properties/methods (@ie-zero) - [#983](https://github.com/nlog/nlog/pull/983) Remove obsolete code from FileTarget (@ie-zero) - [#981](https://github.com/nlog/nlog/pull/981) More tests inner parse + docs (@304NotModified) - [#952](https://github.com/nlog/nlog/pull/952) Fixes #931. FileTarget: Log info concerning archiving to internal logger (@bhaeussermann) - [#976](https://github.com/nlog/nlog/pull/976) Fix SL4/SL5 warnings by adding/editing XML docs (@304NotModified) - [#973](https://github.com/nlog/nlog/pull/973) More fluent unit tests (@304NotModified) - [#975](https://github.com/nlog/nlog/pull/975) Fix parse of inner layout (@304NotModified) - [#3](https://github.com/nlog/nlog/pull/3) Update (@304NotModified, @UgurAldanmaz, @vbfox, @kevindaub, @Niklas-Peter, @bhaeussermann, @breyed, @wrangellboy) - [#974](https://github.com/nlog/nlog/pull/974) Small Codecoverage improvement (@304NotModified) - [#966](https://github.com/nlog/nlog/pull/966) Fix: Exception is thrown when archiving is enabled (@304NotModified) - [#939](https://github.com/nlog/nlog/pull/939) Bugfix: useSystemNetMailSettings=false still uses .config settings + feature: PickupDirectoryLocation from nlog.config (@dnlgmzddr) - [#972](https://github.com/nlog/nlog/pull/972) Added Codecov.io (@304NotModified) - [#971](https://github.com/nlog/nlog/pull/971) Removed unneeded System.Drawing references (@304NotModified) - [#967](https://github.com/nlog/nlog/pull/967) Getcurrentclasslogger documentation / error messages improvements (@304NotModified) - [#963](https://github.com/nlog/nlog/pull/963) FIx: Collection was modified - GetTargetsByLevelForLogger (@304NotModified) - [#954](https://github.com/nlog/nlog/pull/954) Issue 941: Add annotations for customer string formatting messages (@wrangellboy) - [#940](https://github.com/nlog/nlog/pull/940) Documented default fallback value and RanToCompletion (@breyed) - [#947](https://github.com/nlog/nlog/pull/947) Fixes #319. Added IncrementValue property. (@bhaeussermann) - [#945](https://github.com/nlog/nlog/pull/945) Added Travis Badge (@304NotModified) - [#944](https://github.com/nlog/nlog/pull/944) Skipped some unit tests for Mono (@304NotModified) - [#938](https://github.com/nlog/nlog/pull/938) Issue #913: Log NLog version to internal log. (@bhaeussermann) - [#937](https://github.com/nlog/nlog/pull/937) Added more registry unit tests (@304NotModified) - [#933](https://github.com/nlog/nlog/pull/933) Issue #612: Cached Layout Renderer is reevaluated when LoggingConfiguration is changed (@bhaeussermann) - [#2](https://github.com/nlog/nlog/pull/2) Support object vals for mdlc (@UgurAldanmaz) - [#927](https://github.com/nlog/nlog/pull/927) Comments change in LogFactory (@Niklas-Peter) - [#926](https://github.com/nlog/nlog/pull/926) Assure automatic re-configuration after configuration change (@Niklas-Peter) ### Version 4.1.2 (2015/09/20) - [#920](https://github.com/nlog/nlog/pull/920) Added AssemblyFileVersion as property to build script (@304NotModified) - [#912](https://github.com/nlog/nlog/pull/912) added fluent .properties, fix/add fluent unit tests (@304NotModified) - [#909](https://github.com/nlog/nlog/pull/909) added ThreadAgnostic on AllEventPropertiesLayoutRenderer (@304NotModified) - [#910](https://github.com/nlog/nlog/pull/910) Fixes "Collection was modified" crash with ReconfigExistingLoggers (@304NotModified) - [#906](https://github.com/nlog/nlog/pull/906) added some extra tests (@304NotModified) ### Version 4.1.1 (2015/09/12) - [#900](https://github.com/nlog/nlog/pull/900) fix generated code after change .tt (#894) (@304NotModified) - [#901](https://github.com/nlog/nlog/pull/901) Safe autoload (@304NotModified) - [#894](https://github.com/nlog/nlog/pull/894) fix generated code after change .tt (#894) (@304NotModified) - [#896](https://github.com/nlog/nlog/pull/896) Support object vals for mdlc (@UgurAldanmaz) - [#898](https://github.com/nlog/nlog/pull/898) Resolves Internal Logging With Just Filename (@kevindaub) - [#1](https://github.com/nlog/nlog/pull/1) Update from base repository (@304NotModified, @UgurAldanmaz, @vbfox) - [#892](https://github.com/nlog/nlog/pull/892) Remove unused windows.forms stuff (@304NotModified) - [#894](https://github.com/nlog/nlog/pull/894) Obsolete attribute doesn't specify the correct replacement (@vbfox) ### Version 4.1.0 (2015/08/30) - [#884](https://github.com/nlog/nlog/pull/884) Changes at MDLC to support .Net 4.0 and .Net 4.5 (@UgurAldanmaz) - [#881](https://github.com/nlog/nlog/pull/881) Change GitHub for Windows to GitHub Desktop (@campbeb) - [#874](https://github.com/nlog/nlog/pull/874) Wcf receiver client (@kevindaub, @304NotModified) - [#871](https://github.com/nlog/nlog/pull/871) ${event-properties} - Added culture and format properties (@304NotModified) - [#861](https://github.com/nlog/nlog/pull/861) LogReceiverServiceTests: Added one-way unit test (retry) (@304NotModified) - [#866](https://github.com/nlog/nlog/pull/866) FileTarget.DeleteOldDateArchive minor fix (@remye06) - [#872](https://github.com/nlog/nlog/pull/872) Updated appveyor.yml (unit test CMD) (@304NotModified) - [#743](https://github.com/nlog/nlog/pull/743) Support object values for GDC, MDC and NDC contexts. (@williamb1024) - [#773](https://github.com/nlog/nlog/pull/773) Fixed DateAndSequence archive numbering mode + bugfix no max archives (@remye06) - [#858](https://github.com/nlog/nlog/pull/858) Fixed travis build with unit tests (@kevindaub, @304NotModified) - [#856](https://github.com/nlog/nlog/pull/856) Revert "LogReceiverServiceTests: Added one-way unit test" (@304NotModified) - [#854](https://github.com/nlog/nlog/pull/854) LogReceiverServiceTests: Added one-way unit test (@304NotModified) - [#855](https://github.com/nlog/nlog/pull/855) Update appveyor.yml (@304NotModified) - [#853](https://github.com/nlog/nlog/pull/853) Update appveyor config (@304NotModified) - [#850](https://github.com/nlog/nlog/pull/850) Archive files delete right order (@304NotModified) - [#848](https://github.com/nlog/nlog/pull/848) Refactor file archive unittest (@304NotModified) - [#820](https://github.com/nlog/nlog/pull/820) fix unloaded appdomain with xml auto reload (@304NotModified) - [#789](https://github.com/nlog/nlog/pull/789) added config option for breaking change (Exceptions logging) in NLog 4.0 [WIP] (@304NotModified) - [#833](https://github.com/nlog/nlog/pull/833) Move MDLC and Traceactivity from Contrib + handle missing dir in filewachter (@304NotModified, @kichristensen) - [#818](https://github.com/nlog/nlog/pull/818) Updated InternalLogger to Create Directories If Needed (@kevindaub) - [#844](https://github.com/nlog/nlog/pull/844) Fix ThreadAgnosticAttributeTest unit test (@304NotModified) - [#834](https://github.com/nlog/nlog/pull/834) Fix SL5 (@304NotModified) - [#827](https://github.com/nlog/nlog/pull/827) added test: Combine archive every day and archive above size (@304NotModified) - [#811](https://github.com/nlog/nlog/pull/811) Easier API (@304NotModified) - [#816](https://github.com/nlog/nlog/pull/816) Overhaul NLog variables (@304NotModified) - [#788](https://github.com/nlog/nlog/pull/788) Fix: exception is not correctly logged when calling without message [WIP] (@304NotModified) - [#814](https://github.com/nlog/nlog/pull/814) Bugfix: `<extensions>` needs to be the first element in the config (@304NotModified) - [#813](https://github.com/nlog/nlog/pull/813) Added unit test: reload after replace (@304NotModified) - [#812](https://github.com/nlog/nlog/pull/812) Unit tests: added some extra time for completion (@304NotModified) - [#800](https://github.com/nlog/nlog/pull/800) Replace NewLines Layout Renderer Wrapper (@flower189) - [#805](https://github.com/nlog/nlog/pull/805) Fix issue #804: Logging to same file from multiple processes misses messages (@bhaeussermann) - [#797](https://github.com/nlog/nlog/pull/797) added switch to JsonLayout to suppress the extra spaces (@tmusico) - [#809](https://github.com/nlog/nlog/pull/809) Improve docs `ICreateFileParameters` (@304NotModified) - [#808](https://github.com/nlog/nlog/pull/808) Added logrecievertest with ServiceHost (@304NotModified) - [#780](https://github.com/nlog/nlog/pull/780) Call site line number layout renderer - fix (@304NotModified) - [#776](https://github.com/nlog/nlog/pull/776) added SwallowAsync(Task) (@breyed) - [#774](https://github.com/nlog/nlog/pull/774) FIxed ArchiveOldFileOnStartup with layout renderer used in ArchiveFileName (@remye06) - [#750](https://github.com/nlog/nlog/pull/750) Optional encoding for JsonAttribute (@grbinho) - [#742](https://github.com/nlog/nlog/pull/742) Fix monodevelop build. (@txdv) - [#781](https://github.com/nlog/nlog/pull/781) All events layout renderer: added `IncludeCallerInformation` option. (@304NotModified) - [#794](https://github.com/nlog/nlog/pull/794) Support for auto loading UNC paths (@mikeobrien) - [#786](https://github.com/nlog/nlog/pull/786) added unit test for forwardscomp (@304NotModified) ### Version 4.0.1 (2015/06/18) - [#762](https://github.com/nlog/nlog/pull/762) Improved config example (@304NotModified) - [#760](https://github.com/nlog/nlog/pull/760) Autoload fix for ASP.net + better autoloading logging (@304NotModified) - [#763](https://github.com/nlog/nlog/pull/763) Fixed reference for Siverlight (broken and fixed in 4.0.1) (@304NotModified) - [#759](https://github.com/nlog/nlog/pull/759) Check if directory watched exists (@kichristensen) - [#755](https://github.com/nlog/nlog/pull/755) Fix unneeded breaking change with requirement of MailTarget.SmtpServer (@304NotModified) - [#758](https://github.com/nlog/nlog/pull/758) Correct obsolete text (@kichristensen) - [#754](https://github.com/nlog/nlog/pull/754) Optimized references (@304NotModified) - [#753](https://github.com/nlog/nlog/pull/753) Fix autoflush (@304NotModified) - [#744](https://github.com/nlog/nlog/pull/744) Alternate fix for #730 (@williamb1024) - [#751](https://github.com/nlog/nlog/pull/751) Fix incorrect loglevel obsolete message (@SimonCropp) - [#747](https://github.com/nlog/nlog/pull/747) Correct race condition in AsyncTargetWrapperExceptionTest (@williamb1024) - [#746](https://github.com/nlog/nlog/pull/746) Fix for #736 (@akamyshanov) - [#736](https://github.com/nlog/nlog/pull/736) fixes issue (#736) when the NLog assembly is loaded from memory (@akamyshanov) - [#715](https://github.com/nlog/nlog/pull/715) Message queue target test check if queue exists (@304NotModified) ### Version 4.0.0 (2015/05/26) - [#583](https://github.com/nlog/nlog/pull/583) .gitattributes specifies which files should be considered as text (@ilya-g) ### Version 4.0-RC (2015/05/26) - [#717](https://github.com/nlog/nlog/pull/717) Improved description and warning. (@304NotModified) - [#718](https://github.com/nlog/nlog/pull/718) GOTO considered harmful (@304NotModified) - [#689](https://github.com/nlog/nlog/pull/689) Make alignment stay consistent when fixed-length truncation occurs.(AlignmentOnTruncation property) (@logiclrd) - [#716](https://github.com/nlog/nlog/pull/716) Flush always explicit (@304NotModified) - [#714](https://github.com/nlog/nlog/pull/714) added some docs for the ConditionalXXX methods (@304NotModified) - [#712](https://github.com/nlog/nlog/pull/712) nuspec: added author + added NLog tag (@304NotModified) - [#707](https://github.com/nlog/nlog/pull/707) Introduce auto flush behaviour again (@kichristensen) - [#705](https://github.com/nlog/nlog/pull/705) EventLogTarget.Source layoutable & code improvements to EventLogTarget (@304NotModified) - [#704](https://github.com/nlog/nlog/pull/704) Thread safe: GetCurrentClassLogger test + fix (@304NotModified) - [#703](https://github.com/nlog/nlog/pull/703) Added 'lost messages' Webservice unittest (@304NotModified) - [#692](https://github.com/nlog/nlog/pull/692) added Encoding property for consoleTarget + ColorConsoleTarget (@304NotModified) - [#699](https://github.com/nlog/nlog/pull/699) Added Webservice tests with REST api. (@304NotModified) - [#654](https://github.com/nlog/nlog/pull/654) Added unit test to validate the [DefaultValue] attribute values + update DefaultAttributes (@304NotModified) - [#671](https://github.com/nlog/nlog/pull/671) Bugfix: Broken xml stops logging (@304NotModified) - [#697](https://github.com/nlog/nlog/pull/697) V3.2.1 manual merge (@304NotModified, @kichristensen) - [#698](https://github.com/nlog/nlog/pull/698) Fixed where log files couldn't use the same name as archive file (@BrandonLegault) - [#691](https://github.com/nlog/nlog/pull/691) Right way to log exceptions (@304NotModified) - [#670](https://github.com/nlog/nlog/pull/670) added unit test: string with variable get expanded (@304NotModified) - [#547](https://github.com/nlog/nlog/pull/547) Fix use of single archive in file target (@kichristensen) - [#674](https://github.com/nlog/nlog/pull/674) Add a Gitter chat badge to README.md (@gitter-badger) - [#629](https://github.com/nlog/nlog/pull/629) BOM option/fix for WebserviceTarget + code improvements (@304NotModified) - [#650](https://github.com/nlog/nlog/pull/650) fix default value of Commandtype (@304NotModified) - [#651](https://github.com/nlog/nlog/pull/651) init `TimeStamp` and `SequenceID` in all ctors (@304NotModified) - [#657](https://github.com/nlog/nlog/pull/657) Fixed quite a few typos (@sean-gilliam) ### Version 3.2.1 (2015/03/26) - [#600](https://github.com/nlog/nlog/pull/600) Looks good (@kichristensen) - [#645](https://github.com/nlog/nlog/pull/645) Stacktrace broken fix 321 (@304NotModified) - [#606](https://github.com/nlog/nlog/pull/606) LineEndingMode type in xml configuration and xsd schema (@ilya-g) - [#608](https://github.com/nlog/nlog/pull/608) Archiving system runs when new log file is created #390 (@awardle) - [#584](https://github.com/nlog/nlog/pull/584) Stacktrace broken fix (@304NotModified, @ilya-g) - [#601](https://github.com/nlog/nlog/pull/601) Mailtarget allow empty 'To' and various code improvements (@304NotModified) - [#618](https://github.com/nlog/nlog/pull/618) Handle .tt in .csproj better (@304NotModified) - [#619](https://github.com/nlog/nlog/pull/619) Improved badges (@304NotModified) - [#616](https://github.com/nlog/nlog/pull/616) Added DEBUG-Conditional trace and debug methods #2 (@304NotModified) - [#10](https://github.com/nlog/nlog/pull/10) Manual merge with master (@304NotModified, @kichristensen, @YuLad, @ilya-g, @MartinTherriault, @aelij) - [#602](https://github.com/nlog/nlog/pull/602) Logger overloads generated by T4 (@304NotModified) - [#613](https://github.com/nlog/nlog/pull/613) Treat warnings as errors (@304NotModified) - [#9](https://github.com/nlog/nlog/pull/9) 304 not modified stacktrace broken fix (@304NotModified, @kichristensen, @YuLad, @ilya-g, @MartinTherriault, @aelij) - [#610](https://github.com/nlog/nlog/pull/610) Fixed NLog/NLog#609 (@dodexahedron) - [#8](https://github.com/nlog/nlog/pull/8) Refactoring + comments (@ilya-g) - [#4](https://github.com/nlog/nlog/pull/4) HiddenAssemblies list is treated like immutable. (@ilya-g) - [#6](https://github.com/nlog/nlog/pull/6) Sync back (@304NotModified, @kichristensen, @YuLad, @ilya-g, @MartinTherriault, @aelij) - [#512](https://github.com/nlog/nlog/pull/512) FileTarget uses time from the current TimeSource for date-based archiving (@ilya-g) - [#560](https://github.com/nlog/nlog/pull/560) Archive file zip compression (@aelij) - [#576](https://github.com/nlog/nlog/pull/576) Instance property XmlLoggingConfiguration.DefaultCultureInfo should not change global state (@ilya-g) - [#585](https://github.com/nlog/nlog/pull/585) improved Cyclomatic complexity of ConditionTokenizer (@304NotModified) - [#598](https://github.com/nlog/nlog/pull/598) Added nullref checks for MailTarget.To (@304NotModified) - [#582](https://github.com/nlog/nlog/pull/582) Fix NLog.proj build properties (@ilya-g) - [#5](https://github.com/nlog/nlog/pull/5) Extend stack trace frame skip condition to types derived from the loggerType (@ilya-g) - [#575](https://github.com/nlog/nlog/pull/575) Event Log Target unit tests improvement (@ilya-g) - [#556](https://github.com/nlog/nlog/pull/556) Enable the counter sequence parameter to take layouts (@304NotModified) - [#559](https://github.com/nlog/nlog/pull/559) Eventlog audit events (@304NotModified) - [#565](https://github.com/nlog/nlog/pull/565) Set the service contract for LogReceiverTarget as one way (@MartinTherriault) - [#563](https://github.com/nlog/nlog/pull/563) Added info sync projects + multiple .Net versions (@304NotModified) - [#542](https://github.com/nlog/nlog/pull/542) Delete stuff moved to NLog.Web (@kichristensen) - [#543](https://github.com/nlog/nlog/pull/543) Auto load extensions to allow easier integration with extensions (@kichristensen) - [#555](https://github.com/nlog/nlog/pull/555) SMTP Closing connections fix (@304NotModified) - [#3](https://github.com/nlog/nlog/pull/3) Sync back (@kichristensen, @304NotModified, @YuLad, @ilya-g) - [#544](https://github.com/nlog/nlog/pull/544) Escape closing bracket in AppDomainLayoutRenderer test (@kichristensen) - [#546](https://github.com/nlog/nlog/pull/546) Update nuget packages project url (@kichristensen) - [#545](https://github.com/nlog/nlog/pull/545) Merge exception tests (@kichristensen) - [#540](https://github.com/nlog/nlog/pull/540) Added CONTRIBUTING.md and schields (@304NotModified) - [#2](https://github.com/nlog/nlog/pull/2) sync back (@kichristensen, @304NotModified, @YuLad, @ilya-g) - [#535](https://github.com/nlog/nlog/pull/535) App domain layout renderer (@304NotModified) - [#519](https://github.com/nlog/nlog/pull/519) Fluent API available for ILogger interface (@ilya-g) - [#523](https://github.com/nlog/nlog/pull/523) Fix for issue #507: NLog optional or empty mail recipient (@YuLad) - [#497](https://github.com/nlog/nlog/pull/497) Remove Windows Forms targets (@kichristensen) - [#530](https://github.com/nlog/nlog/pull/530) Added Stacktrace layout renderer SkipFrames (@304NotModified) - [#490](https://github.com/nlog/nlog/pull/490) AllEventProperties Layout Renderer (@vladikk) - [#517](https://github.com/nlog/nlog/pull/517) Fluent API uses the same time source for timestamping as the Logger. (@ilya-g) - [#503](https://github.com/nlog/nlog/pull/503) Add missing tags to Nuget packages (@kichristensen) - [#496](https://github.com/nlog/nlog/pull/496) Fix monodevelop build (@dmitry-shechtman) - [#489](https://github.com/nlog/nlog/pull/489) Add .editorconfig (@damageboy) - [#491](https://github.com/nlog/nlog/pull/491) LogFactory Class Refactored (@ie-zero) - [#422](https://github.com/nlog/nlog/pull/422) Run logging code outside of transaction (@Giorgi) - [#474](https://github.com/nlog/nlog/pull/474) [Fix] ArchiveFileOnStartTest was failing (@ie-zero) - [#479](https://github.com/nlog/nlog/pull/479) LogManager class refactored (@ie-zero) - [#478](https://github.com/nlog/nlog/pull/478) Get[*]Logger() return Logger instead of ILogger (@ie-zero) - [#481](https://github.com/nlog/nlog/pull/481) JsonLayout (@vladikk) - [#473](https://github.com/nlog/nlog/pull/473) LineEndingMode Changed to Immutable Class (@ie-zero) - [#469](https://github.com/nlog/nlog/pull/469) Corrects a copy-pasted code comment. (@JoshuaRogers) - [#467](https://github.com/nlog/nlog/pull/467) LoggingRule.Final only suppresses matching levels. (@ilya-g) - [#465](https://github.com/nlog/nlog/pull/465) Fix #283: throwExceptions ="false" but Is still an error (@YuLad) - [#464](https://github.com/nlog/nlog/pull/464) Added 'enabled' attribute to the logging rule element. (@ilya-g) ### Version 3.2.0.0 (2014/12/21) - [#463](https://github.com/nlog/nlog/pull/463) Pluggable time sources support in NLog.xsd generator utility (@ilya-g) - [#460](https://github.com/nlog/nlog/pull/460) Add exception to NLogEvent (@kichristensen) - [#457](https://github.com/nlog/nlog/pull/457) Unobsolete XXXExceptions methods (@kichristensen) - [#449](https://github.com/nlog/nlog/pull/449) Added new archive numbering mode (@1and1-webhosting-infrastructure) - [#450](https://github.com/nlog/nlog/pull/450) Added support for hidden/blacklisted assemblies (@1and1-webhosting-infrastructure) - [#454](https://github.com/nlog/nlog/pull/454) DateRenderer now includes milliseconds (@ilivewithian) - [#448](https://github.com/nlog/nlog/pull/448) Added unit test to identify work around when using colons within when layout renderers (@reedyrm) - [#447](https://github.com/nlog/nlog/pull/447) Change GetCandidateFileNames() to also yield appname.exe.nlog when confi... (@jltrem) - [#443](https://github.com/nlog/nlog/pull/443) Implement Flush in LogReceiverWebServiceTarget (@kichristensen) - [#430](https://github.com/nlog/nlog/pull/430) Make ExceptionLayoutRenderer more extensible (@SurajGupta) - [#442](https://github.com/nlog/nlog/pull/442) BUG FIX: Modification to LogEventInfo.Properties While Iterating (@tsconn23) - [#439](https://github.com/nlog/nlog/pull/439) Fix for UDP broadcast (@dmitriyett) - [#415](https://github.com/nlog/nlog/pull/415) Fixed issue (#414) with AutoFlush on FileTarget. (@richol) - [#409](https://github.com/nlog/nlog/pull/409) Fix loss of exception info when reading Exception.Message property throw... (@wilbit) - [#407](https://github.com/nlog/nlog/pull/407) Added some missing [StringFormatMethod]s (@roji) - [#405](https://github.com/nlog/nlog/pull/405) Close channel (@kichristensen) - [#404](https://github.com/nlog/nlog/pull/404) Correctly delete first line i RichTextBox (@kichristensen) - [#402](https://github.com/nlog/nlog/pull/402) Add property to stop scanning properties (@kichristensen) - [#401](https://github.com/nlog/nlog/pull/401) Pass correct parameters into ConfigurationReloaded (@kichristensen) - [#397](https://github.com/nlog/nlog/pull/397) Improve test run time (@kichristensen) - [#398](https://github.com/nlog/nlog/pull/398) Remove obsolete attribute from ErrorException (@kichristensen) - [#395](https://github.com/nlog/nlog/pull/395) Speed up network target tests (@kichristensen) - [#394](https://github.com/nlog/nlog/pull/394) Always return exit code 0 from test scripts (@kichristensen) - [#393](https://github.com/nlog/nlog/pull/393) Avoid uneccassary reflection (@kichristensen) - [#392](https://github.com/nlog/nlog/pull/392) Remove EnumerableHelpers (@kichristensen) - [#369](https://github.com/nlog/nlog/pull/369) Add of archiveOldFileOnStartup parameter in FileTarget (@cvanbergen) - [#377](https://github.com/nlog/nlog/pull/377) Apply small performance patch (@pgatilov) - [#382](https://github.com/nlog/nlog/pull/382) contribute fluent log builder (@pwelter34) ### Version 3.1.0 (2014/06/23) - [#371](https://github.com/nlog/nlog/pull/371) Use merging of event properties in async target wrapper to fix empty collection issue (@tuukkapuranen) - [#357](https://github.com/nlog/nlog/pull/357) Extended ReplaceLayoutRendererWrapper and LayoutParser to support more advanced Regex replacements and more escape codes (@DannyVarod) - [#359](https://github.com/nlog/nlog/pull/359) Fix #71 : Removing invalid filename characters from created file (@cvanbergen) - [#366](https://github.com/nlog/nlog/pull/366) Fix for #365: Behaviour when logging null arguments (@cvanbergen) - [#372](https://github.com/nlog/nlog/pull/372) Fix #370: EventLogTarget source and log name case insensitive comparison (@cvanbergen) - [#358](https://github.com/nlog/nlog/pull/358) Made EndpointAddress virtual (@MikeChristensen) - [#353](https://github.com/nlog/nlog/pull/353) Configuration to disable expensive flushing in NLogTraceListener (@robertvazan) - [#351](https://github.com/nlog/nlog/pull/351) Obsolete added to LogException() method in Logger class. (@ie-zero) - [#352](https://github.com/nlog/nlog/pull/352) Remove public constructors from LogLevel (@ie-zero) - [#349](https://github.com/nlog/nlog/pull/349) Changed all ReSharper annotations to internal (issue 292) (@MichaelLogutov) ### Version 3.0 (2014/06/02) - [#346](https://github.com/nlog/nlog/pull/346) Fix: #333 Delete archived files in correct order (@cvanbergen) - [#347](https://github.com/nlog/nlog/pull/347) Fixed #281: Don't create empty batches when event list is empty (@robertvazan) - [#246](https://github.com/nlog/nlog/pull/246) Additional Layout Renderer "Assembly-Name" (@Slowpython) - [#344](https://github.com/nlog/nlog/pull/344) Replacement for [LogLevel]Exception methods (@ie-zero) - [#337](https://github.com/nlog/nlog/pull/337) Fixes an exception that occurs on startup in apps using NLog. AFAIK shou... (@activescott) - [#338](https://github.com/nlog/nlog/pull/338) Fix: File target doesn't duplicate header in archived files #245 (@cvanbergen) - [#341](https://github.com/nlog/nlog/pull/341) SpecialFolderLayoutRenderer honor file and dir (@arjoe) - [#345](https://github.com/nlog/nlog/pull/345) Default value added in EnviromentLayoutRender (@ie-zero) - [#335](https://github.com/nlog/nlog/pull/335) Fix/callsite incorrect (@JvanderStad) - [#334](https://github.com/nlog/nlog/pull/334) Fixes empty "properties" collection. (@erwinwolff) - [#336](https://github.com/nlog/nlog/pull/336) Fix for invalid XML characters in Log4JXmlEventLayoutRenderer (@JvanderStad) - [#329](https://github.com/nlog/nlog/pull/329) ExceptionLayoutRenderer extension (@tjandras) - [#323](https://github.com/nlog/nlog/pull/323) Update DatabaseTarget.cs (@GunsAkimbo) - [#315](https://github.com/nlog/nlog/pull/315) Dispose of dequeued SocketAsyncEventArgs (@gcschorer) - [#300](https://github.com/nlog/nlog/pull/300) Avoid NullReferenceException when environment variable not set. (@bkryl) - [#305](https://github.com/nlog/nlog/pull/305) Redirects Logger.Log(a, b, ex) to Logger.LogException(a, b, ex) (@arangas) - [#321](https://github.com/nlog/nlog/pull/321) Avoid NullArgumentException when running in a Unity3D application (@mattyway) - [#285](https://github.com/nlog/nlog/pull/285) Changed modifier of ProcessLogEventInfo (@cincuranet) - [#270](https://github.com/nlog/nlog/pull/270) Integrate JetBrains Annotations (@damageboy) ### Version 2.1.0 (2013/10/07) - [#257](https://github.com/nlog/nlog/pull/257) Fixed SL5 compilation error (@emazv72) - [#241](https://github.com/nlog/nlog/pull/241) Date Based File Archiving (@mkaltner) - [#239](https://github.com/nlog/nlog/pull/239) Add layout renderer for retrieving values from AppSettings. (@mpareja) - [#227](https://github.com/nlog/nlog/pull/227) Pluggable time sources (@robertvazan) - [#226](https://github.com/nlog/nlog/pull/226) Shared Mutex Improvement (@cjberg) - [#216](https://github.com/nlog/nlog/pull/216) Optional ConditionMethod arguments, ignoreCase argument for standard condition methods, EventLogTarget enhancements (@tg73) - [#219](https://github.com/nlog/nlog/pull/219) Avoid Win32-specific file functions in Mono where parts not implemented. (@KeithLRobertson) - [#215](https://github.com/nlog/nlog/pull/215) Revert "Fix writing NLog properties in Log4JXmlEvent" (@kichristensen) - [#206](https://github.com/nlog/nlog/pull/206) Correctly use comments in NLog.Config package (@kichristensen) ### Version 2.0.1 (2013/04/08) - [#197](https://github.com/nlog/nlog/pull/197) Better request queue logging (@kichristensen) - [#192](https://github.com/nlog/nlog/pull/192) Allow Form Control Target to specify append direction (@simongh) - [#182](https://github.com/nlog/nlog/pull/182) Fix locks around layoutCache (@brutaldev) - [#178](https://github.com/nlog/nlog/pull/178) Anonymous delegate class and method name cleanup (@aalex675) - [#168](https://github.com/nlog/nlog/pull/168) Deadlock in NLog library using Control-Target (WinForms) (@falstaff84) - [#176](https://github.com/nlog/nlog/pull/176) Fix for #175 NLogTraceListener not using LogFactory (@HakanL) - [#163](https://github.com/nlog/nlog/pull/163) #110 Exceptions swallowed in custom target (@johnrey1) - [#12](https://github.com/nlog/nlog/pull/12) AppDomain testability (@kichristensen) - [#11](https://github.com/nlog/nlog/pull/11) Updated code to not log exception double times (@ParthDesai) - [#10](https://github.com/nlog/nlog/pull/10) Improved Fix Code for issue 6575 (@ParthDesai) - [#7](https://github.com/nlog/nlog/pull/7) Fixed Issue in Code For Invalid XML (@ParthDesai) - [#6](https://github.com/nlog/nlog/pull/6) Fix For Issue #7031 (@ParthDesai) - [#5](https://github.com/nlog/nlog/pull/5) Codeplex BUG 6227 - LogManager.Flush throws... (@kichristensen) - [#4](https://github.com/nlog/nlog/pull/4) Adding a test for pull request #1 which fixes bug 6370 from Codeplex (@sebfischer83) - [#3](https://github.com/nlog/nlog/pull/3) TraceTarget no longer blocks on error messages. Fixes Codeplex bug 2599 (@kichristensen) - [#1](https://github.com/nlog/nlog/pull/1) Codeplex Bug 6370 (@sebfischer83) ### NLog-1.0-RC1 (2006/07/10) - [#27](https://github.com/nlog/nlog/pull/27) added Debugger target (#27), fixed Database ${callsite} (#26) (@jkowalski) - [#27](https://github.com/nlog/nlog/pull/27) added Debugger target (#27), fixed Database ${callsite} (#26) (@jkowalski) <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; using NLog.Internal; using Xunit; public class AsyncHelperTests : NLogTestBase { [Fact] public void OneTimeOnlyTest1() { var exceptions = new List<Exception>(); AsyncContinuation cont = exceptions.Add; cont = AsyncHelpers.PreventMultipleCalls(cont); // OneTimeOnly(OneTimeOnly(x)) == OneTimeOnly(x) var cont2 = AsyncHelpers.PreventMultipleCalls(cont); Assert.Same(cont, cont2); var sampleException = new ApplicationException("some message"); cont(null); cont(sampleException); cont(null); cont(sampleException); Assert.Single(exceptions); Assert.Null(exceptions[0]); } [Fact] public void OneTimeOnlyTest2() { var exceptions = new List<Exception>(); AsyncContinuation cont = exceptions.Add; cont = AsyncHelpers.PreventMultipleCalls(cont); var sampleException = new ApplicationException("some message"); cont(sampleException); cont(null); cont(sampleException); cont(null); Assert.Single(exceptions); Assert.Same(sampleException, exceptions[0]); } [Fact] public void OneTimeOnlyExceptionInHandlerTest() { using (new NoThrowNLogExceptions()) { var exceptions = new List<Exception>(); var sampleException = new ApplicationException("some message"); AsyncContinuation cont = ex => { exceptions.Add(ex); throw sampleException; }; cont = AsyncHelpers.PreventMultipleCalls(cont); cont(null); cont(null); cont(null); Assert.Single(exceptions); Assert.Null(exceptions[0]); } } [Fact] public void OneTimeOnlyExceptionInHandlerTest_RethrowExceptionEnabled() { LogManager.ThrowExceptions = true; var exceptions = new List<Exception>(); var sampleException = new ApplicationException("some message"); AsyncContinuation cont = ex => { exceptions.Add(ex); throw sampleException; }; cont = AsyncHelpers.PreventMultipleCalls(cont); try { cont(null); } catch { } try { cont(null); } catch { } try { cont(null); } catch { } Assert.Single(exceptions); Assert.Null(exceptions[0]); } [Fact] public void ContinuationTimeoutTest() { RetryingIntegrationTest(3, () => { var resetEvent = new ManualResetEvent(false); var exceptions = new List<Exception>(); // set up a timer to strike in 1 second var cont = AsyncHelpers.WithTimeout(ex => { exceptions.Add(ex); resetEvent.Set(); }, TimeSpan.FromMilliseconds(1)); resetEvent.WaitOne(TimeSpan.FromSeconds(1)); // make sure we got timeout exception Assert.Single(exceptions); Assert.IsType<TimeoutException>(exceptions[0]); Assert.Equal("Timeout.", exceptions[0].Message); // those will be ignored cont(null); cont(new ApplicationException("Some exception")); cont(null); cont(new ApplicationException("Some exception")); Assert.Single(exceptions); }); } [Fact] public void ContinuationTimeoutNotHitTest() { var exceptions = new List<Exception>(); // set up a timer to strike var cont = AsyncHelpers.WithTimeout(AsyncHelpers.PreventMultipleCalls(exceptions.Add), TimeSpan.FromMilliseconds(50)); // call success quickly, hopefully before the timer comes cont(null); // sleep to make sure timer event comes Thread.Sleep(100); // make sure we got success, not a timer exception Assert.Single(exceptions); Assert.Null(exceptions[0]); // those will be ignored cont(null); cont(new ApplicationException("Some exception")); cont(null); cont(new ApplicationException("Some exception")); Assert.Single(exceptions); Assert.Null(exceptions[0]); } [Fact] public void ContinuationErrorTimeoutNotHitTest() { var exceptions = new List<Exception>(); // set up a timer to strike var cont = AsyncHelpers.WithTimeout(AsyncHelpers.PreventMultipleCalls(exceptions.Add), TimeSpan.FromMilliseconds(50)); var exception = new ApplicationException("Foo"); // call success quickly, hopefully before the timer comes cont(exception); // sleep to make sure timer event comes Thread.Sleep(100); // make sure we got success, not a timer exception Assert.Single(exceptions); Assert.NotNull(exceptions[0]); Assert.Same(exception, exceptions[0]); // those will be ignored cont(null); cont(new ApplicationException("Some exception")); cont(null); cont(new ApplicationException("Some exception")); Assert.Single(exceptions); Assert.NotNull(exceptions[0]); } [Fact] public void RepeatTest1() { bool finalContinuationInvoked = false; Exception lastException = null; AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int callCount = 0; AsyncHelpers.Repeat(10, finalContinuation, cont => { callCount++; cont(null); }); Assert.True(finalContinuationInvoked); Assert.Null(lastException); Assert.Equal(10, callCount); } [Fact] public void RepeatTest2() { bool finalContinuationInvoked = false; Exception lastException = null; Exception sampleException = new ApplicationException("Some message"); AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int callCount = 0; AsyncHelpers.Repeat(10, finalContinuation, cont => { callCount++; cont(sampleException); cont(sampleException); }); Assert.True(finalContinuationInvoked); Assert.Same(sampleException, lastException); Assert.Equal(1, callCount); } [Fact] public void RepeatTest3() { using (new NoThrowNLogExceptions()) { bool finalContinuationInvoked = false; Exception lastException = null; Exception sampleException = new ApplicationException("Some message"); AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int callCount = 0; AsyncHelpers.Repeat(10, finalContinuation, cont => { callCount++; throw sampleException; }); Assert.True(finalContinuationInvoked); Assert.Same(sampleException, lastException); Assert.Equal(1, callCount); } } [Fact] [Obsolete("Marked obsolete on NLog 5.0")] public void ForEachItemSequentiallyTest1() { bool finalContinuationInvoked = false; Exception lastException = null; AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int sum = 0; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemSequentially(input, finalContinuation, (i, cont) => { sum += i; cont(null); cont(null); }); Assert.True(finalContinuationInvoked); Assert.Null(lastException); Assert.Equal(55, sum); } [Fact] [Obsolete("Marked obsolete on NLog 5.0")] public void ForEachItemSequentiallyTest2() { bool finalContinuationInvoked = false; Exception lastException = null; Exception sampleException = new ApplicationException("Some message"); AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int sum = 0; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemSequentially(input, finalContinuation, (i, cont) => { sum += i; cont(sampleException); cont(sampleException); }); Assert.True(finalContinuationInvoked); Assert.Same(sampleException, lastException); Assert.Equal(1, sum); } [Fact] [Obsolete("Marked obsolete on NLog 5.0")] public void ForEachItemSequentiallyTest3() { using (new NoThrowNLogExceptions()) { bool finalContinuationInvoked = false; Exception lastException = null; Exception sampleException = new ApplicationException("Some message"); AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int sum = 0; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemSequentially(input, finalContinuation, (i, cont) => { sum += i; throw sampleException; }); Assert.True(finalContinuationInvoked); Assert.Same(sampleException, lastException); Assert.Equal(1, sum); } } [Fact] public void ForEachItemInParallelEmptyTest() { int[] items = ArrayHelper.Empty<int>(); Exception lastException = null; bool finalContinuationInvoked = false; AsyncContinuation continuation = ex => { lastException = ex; finalContinuationInvoked = true; }; AsyncHelpers.ForEachItemInParallel(items, continuation, (i, cont) => { Assert.True(false, "Will not be reached"); }); Assert.True(finalContinuationInvoked); Assert.Null(lastException); } [Fact] public void ForEachItemInParallelTest() { var finalContinuationInvoked = new ManualResetEvent(false); Exception lastException = null; AsyncContinuation finalContinuation = ex => { lastException = ex; finalContinuationInvoked.Set(); }; int sum = 0; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemInParallel(input, finalContinuation, (i, cont) => { lock (input) { sum += i; } cont(null); cont(null); }); finalContinuationInvoked.WaitOne(); Assert.Null(lastException); Assert.Equal(55, sum); } [Fact] public void ForEachItemInParallelSingleFailureTest() { using (new InternalLoggerScope()) using (new NoThrowNLogExceptions()) { InternalLogger.LogLevel = LogLevel.Trace; var finalContinuationInvoked = new ManualResetEvent(false); Exception lastException = null; AsyncContinuation finalContinuation = ex => { lastException = ex; finalContinuationInvoked.Set(); }; int sum = 0; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemInParallel(input, finalContinuation, (i, cont) => { lock (input) { sum += i; } if (i == 7) { throw new ApplicationException("Some failure."); } cont(null); }); finalContinuationInvoked.WaitOne(); Assert.Equal(55, sum); Assert.NotNull(lastException); Assert.IsType<ApplicationException>(lastException); Assert.Equal("Some failure.", lastException.Message); } } [Fact] public void ForEachItemInParallelMultipleFailuresTest() { using (new NoThrowNLogExceptions()) { var finalContinuationInvoked = new ManualResetEvent(false); Exception lastException = null; AsyncContinuation finalContinuation = ex => { lastException = ex; finalContinuationInvoked.Set(); }; int sum = 0; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemInParallel(input, finalContinuation, (i, cont) => { lock (input) { sum += i; } throw new ApplicationException("Some failure."); }); finalContinuationInvoked.WaitOne(); Assert.Equal(55, sum); Assert.NotNull(lastException); Assert.IsType<NLogRuntimeException>(lastException); Assert.StartsWith("Got multiple exceptions:\r\n", lastException.Message); } } [Fact] [Obsolete("Marked obsolete on NLog 5.0")] public void PrecededByTest1() { int invokedCount1 = 0; int invokedCount2 = 0; int sequence = 7; int invokedCount1Sequence = 0; int invokedCount2Sequence = 0; AsyncContinuation originalContinuation = ex => { invokedCount1++; invokedCount1Sequence = sequence++; }; AsynchronousAction doSomethingElse = c => { invokedCount2++; invokedCount2Sequence = sequence++; c(null); c(null); }; AsyncContinuation cont = AsyncHelpers.PrecededBy(originalContinuation, doSomethingElse); cont(null); // make sure doSomethingElse was invoked first // then original continuation Assert.Equal(7, invokedCount2Sequence); Assert.Equal(8, invokedCount1Sequence); Assert.Equal(1, invokedCount1); Assert.Equal(1, invokedCount2); } [Fact] [Obsolete("Marked obsolete on NLog 5.0")] public void PrecededByTest2() { int invokedCount1 = 0; int invokedCount2 = 0; int sequence = 7; int invokedCount1Sequence = 0; int invokedCount2Sequence = 0; AsyncContinuation originalContinuation = ex => { invokedCount1++; invokedCount1Sequence = sequence++; }; AsynchronousAction doSomethingElse = c => { invokedCount2++; invokedCount2Sequence = sequence++; c(null); c(null); }; AsyncContinuation cont = AsyncHelpers.PrecededBy(originalContinuation, doSomethingElse); var sampleException = new ApplicationException("Some message."); cont(sampleException); // make sure doSomethingElse was not invoked Assert.Equal(0, invokedCount2Sequence); Assert.Equal(7, invokedCount1Sequence); Assert.Equal(1, invokedCount1); Assert.Equal(0, invokedCount2); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { /// <summary> /// Provides logging interface and utility functions. /// </summary> internal static class AssemblyExtensionTypes { public static void RegisterTypes(ConfigurationItemFactory factory) { #pragma warning disable CS0618 // Type or member is obsolete factory.RegisterTypeProperties<NLog.Targets.TargetWithContext.TargetWithContextLayout>(() => null); factory.RegisterTypeProperties<NLog.Layouts.CsvLayout.CsvHeaderLayout>(() => null); factory.RegisterTypeProperties<NLog.Conditions.ConditionAndExpression>(() => null); factory.RegisterTypeProperties<NLog.Conditions.ConditionExceptionExpression>(() => null); factory.RegisterTypeProperties<NLog.Conditions.ConditionLayoutExpression>(() => null); factory.RegisterTypeProperties<NLog.Conditions.ConditionLevelExpression>(() => null); factory.RegisterTypeProperties<NLog.Conditions.ConditionLiteralExpression>(() => null); factory.RegisterTypeProperties<NLog.Conditions.ConditionLoggerNameExpression>(() => null); factory.RegisterTypeProperties<NLog.Conditions.ConditionMessageExpression>(() => null); factory.RegisterTypeProperties<NLog.Conditions.ConditionMethodExpression>(() => null); factory.RegisterTypeProperties<NLog.Conditions.ConditionNotExpression>(() => null); factory.RegisterTypeProperties<NLog.Conditions.ConditionOrExpression>(() => null); factory.RegisterTypeProperties<NLog.Conditions.ConditionRelationalExpression>(() => null); factory.RegisterType<NLog.Config.LoggingRule>(); factory.FilterFactory.RegisterType<NLog.Filters.ConditionBasedFilter>("when"); factory.FilterFactory.RegisterType<NLog.Filters.WhenContainsFilter>("whenContains"); factory.FilterFactory.RegisterType<NLog.Filters.WhenEqualFilter>("whenEqual"); factory.FilterFactory.RegisterType<NLog.Filters.WhenNotContainsFilter>("whenNotContains"); factory.FilterFactory.RegisterType<NLog.Filters.WhenNotEqualFilter>("whenNotEqual"); factory.FilterFactory.RegisterType<NLog.Filters.WhenRepeatedFilter>("whenRepeated"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.AllEventPropertiesLayoutRenderer>("all-event-properties"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.AppDomainLayoutRenderer>("appdomain"); #if !NETSTANDARD factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.AppSettingLayoutRenderer>("appsetting"); #endif factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.AssemblyVersionLayoutRenderer>("assembly-version"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.BaseDirLayoutRenderer>("basedir"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.CallSiteFileNameLayoutRenderer>("callsite-filename"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.CallSiteLayoutRenderer>("callsite"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.CallSiteLineNumberLayoutRenderer>("callsite-linenumber"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.CounterLayoutRenderer>("counter"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.CurrentDirLayoutRenderer>("currentdir"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.DateLayoutRenderer>("date"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.DbNullLayoutRenderer>("db-null"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.DirectorySeparatorLayoutRenderer>("dir-separator"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.EnvironmentLayoutRenderer>("environment"); #if !NETSTANDARD1_3 && !NETSTANDARD1_5 factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.EnvironmentUserLayoutRenderer>("environment-user"); #endif factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.EventPropertiesLayoutRenderer>("event-properties"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.EventPropertiesLayoutRenderer>("event-property"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.EventPropertiesLayoutRenderer>("event-context"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.ExceptionDataLayoutRenderer>("exceptiondata"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.ExceptionDataLayoutRenderer>("exception-data"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.ExceptionLayoutRenderer>("exception"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.FileContentsLayoutRenderer>("file-contents"); factory.RegisterTypeProperties<NLog.LayoutRenderers.FuncThreadAgnosticLayoutRenderer>(() => null); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.GarbageCollectorInfoLayoutRenderer>("gc"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.GdcLayoutRenderer>("gdc"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.GuidLayoutRenderer>("guid"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.HostNameLayoutRenderer>("hostname"); #if !NETSTANDARD1_3 && !NETSTANDARD1_5 factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.IdentityLayoutRenderer>("identity"); #endif factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.InstallContextLayoutRenderer>("install-context"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.LevelLayoutRenderer>("level"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.LevelLayoutRenderer>("loglevel"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.LiteralLayoutRenderer>("literal"); factory.RegisterTypeProperties<NLog.LayoutRenderers.LiteralWithRawValueLayoutRenderer>(() => null); #if !NETSTANDARD1_3 && !NETSTANDARD1_5 factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.LocalIpAddressLayoutRenderer>("local-ip"); #endif factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Log4JXmlEventLayoutRenderer>("log4jxmlevent"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.LoggerNameLayoutRenderer>("loggername"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.LoggerNameLayoutRenderer>("logger"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.LongDateLayoutRenderer>("longdate"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.MachineNameLayoutRenderer>("machinename"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.MdcLayoutRenderer>("mdc"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.MdlcLayoutRenderer>("mdlc"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.MessageLayoutRenderer>("message"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.NdcLayoutRenderer>("ndc"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.NdlcLayoutRenderer>("ndlc"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.NdlcTimingLayoutRenderer>("ndlctiming"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.NewLineLayoutRenderer>("newline"); #if !NETSTANDARD1_3 factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.NLogDirLayoutRenderer>("nlogdir"); #endif #if !NETSTANDARD1_3 factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.ProcessDirLayoutRenderer>("processdir"); #endif #if !NETSTANDARD1_3 factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.ProcessIdLayoutRenderer>("processid"); #endif #if !NETSTANDARD1_3 factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.ProcessInfoLayoutRenderer>("processinfo"); #endif #if !NETSTANDARD1_3 factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.ProcessNameLayoutRenderer>("processname"); #endif factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.ProcessTimeLayoutRenderer>("processtime"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.ScopeContextIndentLayoutRenderer>("scopeindent"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.ScopeContextNestedStatesLayoutRenderer>("scopenested"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.ScopeContextPropertyLayoutRenderer>("scopeproperty"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.ScopeContextTimingLayoutRenderer>("scopetiming"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.SequenceIdLayoutRenderer>("sequenceid"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.ShortDateLayoutRenderer>("shortdate"); #if !NETSTANDARD1_3 && !NETSTANDARD1_5 factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.SpecialFolderApplicationDataLayoutRenderer>("userApplicationDataDir"); #endif #if !NETSTANDARD1_3 && !NETSTANDARD1_5 factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.SpecialFolderCommonApplicationDataLayoutRenderer>("commonApplicationDataDir"); #endif #if !NETSTANDARD1_3 && !NETSTANDARD1_5 factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.SpecialFolderLayoutRenderer>("specialfolder"); #endif #if !NETSTANDARD1_3 && !NETSTANDARD1_5 factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.SpecialFolderLocalApplicationDataLayoutRenderer>("userLocalApplicationDataDir"); #endif factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.StackTraceLayoutRenderer>("stacktrace"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.TempDirLayoutRenderer>("tempdir"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.ThreadIdLayoutRenderer>("threadid"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.ThreadNameLayoutRenderer>("threadname"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.TicksLayoutRenderer>("ticks"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.TimeLayoutRenderer>("time"); #if !NETSTANDARD1_3 && !NETSTANDARD1_5 factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.TraceActivityIdLayoutRenderer>("activityid"); #endif factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.VariableLayoutRenderer>("var"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.CachedLayoutRendererWrapper>("cached"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.CachedLayoutRendererWrapper>("Cached"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.CachedLayoutRendererWrapper>("ClearCache"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.CachedLayoutRendererWrapper>("CachedSeconds"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.FileSystemNormalizeLayoutRendererWrapper>("filesystem-normalize"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.FileSystemNormalizeLayoutRendererWrapper>("FSNormalize"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.JsonEncodeLayoutRendererWrapper>("json-encode"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.JsonEncodeLayoutRendererWrapper>("JsonEncode"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.LeftLayoutRendererWrapper>("left"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.LeftLayoutRendererWrapper>("Truncate"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.LowercaseLayoutRendererWrapper>("lowercase"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.LowercaseLayoutRendererWrapper>("Lowercase"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.LowercaseLayoutRendererWrapper>("ToLower"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.NoRawValueLayoutRendererWrapper>("norawvalue"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.NoRawValueLayoutRendererWrapper>("NoRawValue"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.ObjectPathRendererWrapper>("Object-Path"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.ObjectPathRendererWrapper>("ObjectPath"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.OnExceptionLayoutRendererWrapper>("onexception"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.OnHasPropertiesLayoutRendererWrapper>("onhasproperties"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.PaddingLayoutRendererWrapper>("pad"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.PaddingLayoutRendererWrapper>("Padding"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.PaddingLayoutRendererWrapper>("PadCharacter"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.PaddingLayoutRendererWrapper>("FixedLength"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.PaddingLayoutRendererWrapper>("AlignmentOnTruncation"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.ReplaceLayoutRendererWrapper>("replace"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.ReplaceNewLinesLayoutRendererWrapper>("replace-newlines"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.ReplaceNewLinesLayoutRendererWrapper>("ReplaceNewLines"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.RightLayoutRendererWrapper>("right"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.Rot13LayoutRendererWrapper>("rot13"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.SubstringLayoutRendererWrapper>("substring"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.TrimWhiteSpaceLayoutRendererWrapper>("trim-whitespace"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.TrimWhiteSpaceLayoutRendererWrapper>("TrimWhiteSpace"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.UppercaseLayoutRendererWrapper>("uppercase"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.UppercaseLayoutRendererWrapper>("Uppercase"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.UppercaseLayoutRendererWrapper>("ToUpper"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.UrlEncodeLayoutRendererWrapper>("url-encode"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.WhenEmptyLayoutRendererWrapper>("whenEmpty"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.WhenEmptyLayoutRendererWrapper>("WhenEmpty"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.WhenLayoutRendererWrapper>("when"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.WhenLayoutRendererWrapper>("When"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.WrapLineLayoutRendererWrapper>("wrapline"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.WrapLineLayoutRendererWrapper>("WrapLine"); factory.LayoutRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.XmlEncodeLayoutRendererWrapper>("xml-encode"); factory.AmbientRendererFactory.RegisterType<NLog.LayoutRenderers.Wrappers.XmlEncodeLayoutRendererWrapper>("XmlEncode"); factory.LayoutFactory.RegisterType<NLog.Layouts.CompoundLayout>("CompoundLayout"); factory.RegisterType<NLog.Layouts.CsvColumn>(); factory.LayoutFactory.RegisterType<NLog.Layouts.CsvLayout>("CsvLayout"); factory.LayoutFactory.RegisterType<NLog.Layouts.JsonArrayLayout>("JsonArrayLayout"); factory.RegisterType<NLog.Layouts.JsonAttribute>(); factory.LayoutFactory.RegisterType<NLog.Layouts.JsonLayout>("JsonLayout"); factory.LayoutFactory.RegisterType<NLog.Layouts.LayoutWithHeaderAndFooter>("LayoutWithHeaderAndFooter"); factory.LayoutFactory.RegisterType<NLog.Layouts.Log4JXmlEventLayout>("Log4JXmlEventLayout"); factory.LayoutFactory.RegisterType<NLog.Layouts.SimpleLayout>("SimpleLayout"); factory.RegisterType<NLog.Layouts.ValueTypeLayoutInfo>(); factory.RegisterType<NLog.Layouts.XmlAttribute>(); factory.LayoutFactory.RegisterType<NLog.Layouts.XmlLayout>("XmlLayout"); factory.TargetFactory.RegisterType<NLog.Targets.ChainsawTarget>("Chainsaw"); #if !NETSTANDARD1_3 factory.TargetFactory.RegisterType<NLog.Targets.ColoredConsoleTarget>("ColoredConsole"); #endif #if !NETSTANDARD1_3 factory.RegisterType<NLog.Targets.ConsoleRowHighlightingRule>(); #endif #if !NETSTANDARD1_3 factory.TargetFactory.RegisterType<NLog.Targets.ConsoleTarget>("Console"); #endif #if !NETSTANDARD1_3 factory.RegisterType<NLog.Targets.ConsoleWordHighlightingRule>(); #endif #if !NETSTANDARD1_3 && !NETSTANDARD1_5 factory.TargetFactory.RegisterType<NLog.Targets.DebuggerTarget>("Debugger"); #endif factory.TargetFactory.RegisterType<NLog.Targets.DebugSystemTarget>("DebugSystem"); factory.TargetFactory.RegisterType<NLog.Targets.DebugTarget>("Debug"); #if !NETSTANDARD factory.TargetFactory.RegisterType<NLog.Targets.EventLogTarget>("EventLog"); #endif factory.TargetFactory.RegisterType<NLog.Targets.FileTarget>("File"); #if !NETSTANDARD1_3 && !NETSTANDARD1_5 factory.TargetFactory.RegisterType<NLog.Targets.MailTarget>("Mail"); factory.TargetFactory.RegisterType<NLog.Targets.MailTarget>("Email"); factory.TargetFactory.RegisterType<NLog.Targets.MailTarget>("Smtp"); factory.TargetFactory.RegisterType<NLog.Targets.MailTarget>("SmtpClient"); #endif factory.TargetFactory.RegisterType<NLog.Targets.MemoryTarget>("Memory"); factory.RegisterType<NLog.Targets.MethodCallParameter>(); factory.TargetFactory.RegisterType<NLog.Targets.MethodCallTarget>("MethodCall"); factory.TargetFactory.RegisterType<NLog.Targets.NetworkTarget>("Network"); factory.RegisterType<NLog.Targets.NLogViewerParameterInfo>(); factory.TargetFactory.RegisterType<NLog.Targets.NLogViewerTarget>("NLogViewer"); factory.TargetFactory.RegisterType<NLog.Targets.NullTarget>("Null"); factory.RegisterType<NLog.Targets.TargetPropertyWithContext>(); #if !NETSTANDARD1_3 factory.TargetFactory.RegisterType<NLog.Targets.TraceTarget>("Trace"); factory.TargetFactory.RegisterType<NLog.Targets.TraceTarget>("TraceSystem"); #endif factory.TargetFactory.RegisterType<NLog.Targets.WebServiceTarget>("WebService"); factory.TargetFactory.RegisterType<NLog.Targets.Wrappers.AsyncTargetWrapper>("AsyncWrapper"); factory.TargetFactory.RegisterType<NLog.Targets.Wrappers.AutoFlushTargetWrapper>("AutoFlushWrapper"); factory.TargetFactory.RegisterType<NLog.Targets.Wrappers.BufferingTargetWrapper>("BufferingWrapper"); factory.TargetFactory.RegisterType<NLog.Targets.Wrappers.FallbackGroupTarget>("FallbackGroup"); factory.RegisterType<NLog.Targets.Wrappers.FilteringRule>(); factory.TargetFactory.RegisterType<NLog.Targets.Wrappers.FilteringTargetWrapper>("FilteringWrapper"); factory.TargetFactory.RegisterType<NLog.Targets.Wrappers.GroupByTargetWrapper>("GroupByWrapper"); factory.TargetFactory.RegisterType<NLog.Targets.Wrappers.LimitingTargetWrapper>("LimitingWrapper"); factory.TargetFactory.RegisterType<NLog.Targets.Wrappers.PostFilteringTargetWrapper>("PostFilteringWrapper"); factory.TargetFactory.RegisterType<NLog.Targets.Wrappers.RandomizeGroupTarget>("RandomizeGroup"); factory.TargetFactory.RegisterType<NLog.Targets.Wrappers.RepeatingTargetWrapper>("RepeatingWrapper"); factory.TargetFactory.RegisterType<NLog.Targets.Wrappers.RetryingTargetWrapper>("RetryingWrapper"); factory.TargetFactory.RegisterType<NLog.Targets.Wrappers.RoundRobinGroupTarget>("RoundRobinGroup"); factory.TargetFactory.RegisterType<NLog.Targets.Wrappers.SplitGroupTarget>("SplitGroup"); factory.TimeSourceFactory.RegisterType<NLog.Time.AccurateLocalTimeSource>("AccurateLocal"); factory.TimeSourceFactory.RegisterType<NLog.Time.AccurateUtcTimeSource>("AccurateUTC"); factory.TimeSourceFactory.RegisterType<NLog.Time.FastLocalTimeSource>("FastLocal"); factory.TimeSourceFactory.RegisterType<NLog.Time.FastUtcTimeSource>("FastUTC"); factory.ConditionMethodFactory.RegisterOneParameter("length", (logEvent,arg1) => NLog.Conditions.ConditionMethods.Length(arg1?.ToString())); factory.ConditionMethodFactory.RegisterTwoParameters("equals", (logEvent,arg1,arg2) => NLog.Conditions.ConditionMethods.Equals2(arg1?.ToString(), arg2?.ToString())); factory.ConditionMethodFactory.RegisterTwoParameters("strequals", (logEvent,arg1,arg2) => NLog.Conditions.ConditionMethods.Equals2(arg1?.ToString(), arg2?.ToString())); factory.ConditionMethodFactory.RegisterThreeParameters("strequals", (logEvent,arg1,arg2,arg3) => NLog.Conditions.ConditionMethods.Equals2(arg1?.ToString(), arg2?.ToString(), arg3 is bool ignoreCase ? ignoreCase : true)); factory.ConditionMethodFactory.RegisterTwoParameters("contains", (logEvent,arg1,arg2) => NLog.Conditions.ConditionMethods.Contains(arg1?.ToString(), arg2?.ToString())); factory.ConditionMethodFactory.RegisterThreeParameters("contains", (logEvent,arg1,arg2,arg3) => NLog.Conditions.ConditionMethods.Contains(arg1?.ToString(), arg2?.ToString(), arg3 is bool ignoreCase ? ignoreCase : true)); factory.ConditionMethodFactory.RegisterTwoParameters("starts-with", (logEvent,arg1,arg2) => NLog.Conditions.ConditionMethods.StartsWith(arg1?.ToString(), arg2?.ToString())); factory.ConditionMethodFactory.RegisterThreeParameters("starts-with", (logEvent,arg1,arg2,arg3) => NLog.Conditions.ConditionMethods.StartsWith(arg1?.ToString(), arg2?.ToString(), arg3 is bool ignoreCase ? ignoreCase : true)); factory.ConditionMethodFactory.RegisterTwoParameters("ends-with", (logEvent,arg1,arg2) => NLog.Conditions.ConditionMethods.EndsWith(arg1?.ToString(), arg2?.ToString())); factory.ConditionMethodFactory.RegisterThreeParameters("ends-with", (logEvent,arg1,arg2,arg3) => NLog.Conditions.ConditionMethods.EndsWith(arg1?.ToString(), arg2?.ToString(), arg3 is bool ignoreCase ? ignoreCase : true)); factory.ConditionMethodFactory.RegisterTwoParameters("regex-matches", (logEvent,arg1,arg2) => NLog.Conditions.ConditionMethods.RegexMatches(arg1?.ToString(), arg2?.ToString())); factory.ConditionMethodFactory.RegisterThreeParameters("regex-matches", (logEvent,arg1,arg2,arg3) => NLog.Conditions.ConditionMethods.RegexMatches(arg1?.ToString(), arg2?.ToString(), arg3?.ToString() ?? string.Empty)); #pragma warning restore CS0618 // Type or member is obsolete } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.MessageTemplates { using System; using System.Globalization; using Xunit; public class RendererTests { [Theory] [InlineData("{0}", new object[] { "a" }, "a")] [InlineData(" {0}", new object[] { "a" }, " a")] [InlineData(" {0} ", new object[] { "a" }, " a ")] [InlineData(" {0} {1} ", new object[] { "a", "b" }, " a b ")] [InlineData(" {1} {0} ", new object[] { "a", "b" }, " b a ")] [InlineData(" {1} {0} {0}", new object[] { "a", "b" }, " b a a")] [InlineData(" message {1} {0} {0}", new object[] { "a", "b" }, " message b a a")] [InlineData(" message {1} {0} {0}", new object[] { 'a', 'b' }, " message b a a")] [InlineData("char {one}", new object[] { 'X' }, "char \"X\"")] [InlineData("char {one:l}", new object[] { 'X' }, "char X")] [InlineData(" message {{{1}}} {0} {0}", new object[] { "a", "b" }, " message {b} a a")] [InlineData(" message {{{one}}} {two} {three}", new object[] { "a", "b", "c" }, " message {\"a\"} \"b\" \"c\"")] [InlineData(" message {{{1} {0} {0}}}", new object[] { "a", "b" }, " message {b a a}")] [InlineData(" completed in {time} sec", new object[] { 10 }, " completed in 10 sec")] [InlineData(" completed task {name} in {time} sec", new object[] { "test", 10 }, " completed task \"test\" in 10 sec")] [InlineData(" completed task {name:l} in {time} sec", new object[] { "test", 10 }, " completed task test in 10 sec")] [InlineData(" completed task {0} in {1} sec", new object[] { "test", 10 }, " completed task test in 10 sec")] [InlineData(" completed task {0} in {1:000} sec", new object[] { "test", 10 }, " completed task test in 010 sec")] [InlineData(" completed task {name} in {time:000} sec", new object[] { "test", 10 }, " completed task \"test\" in 010 sec")] [InlineData(" completed tasks {tasks} in {time:000} sec", new object[] { new [] { "parsing", "testing", "fixing"}, 10 }, " completed tasks \"parsing\", \"testing\", \"fixing\" in 010 sec")] [InlineData(" completed tasks {tasks:l} in {time:000} sec", new object[] { new [] { "parsing", "testing", "fixing"}, 10 }, " completed tasks parsing, testing, fixing in 010 sec")] #if !MONO [InlineData(" completed tasks {$tasks} in {time:000} sec", new object[] { new [] { "parsing", "testing", "fixing"}, 10 }, " completed tasks \"System.String[]\" in 010 sec")] [InlineData(" completed tasks {0} in {1:000} sec", new object[] { new [] { "parsing", "testing", "fixing"}, 10 }, " completed tasks System.String[] in 010 sec")] #endif [InlineData("{{{0:d}}}", new object[] { 3 }, "{d}")] //format is here "d}" ... because escape from left-to-right [InlineData("{{{0:d} }}", new object[] { 3 }, "{3 }")] [InlineData("{{{0:dd}}}", new object[] { 3 }, "{dd}")] [InlineData("{{{0:0{{}", new object[] { 3 }, "{3{")] //format is here "0{" [InlineData("hello {0}", new object[] { null }, "hello NULL")] [InlineData("if its {yes}, it should not be {no}", new object[] { true, false }, "if its true, it should not be false")] [InlineData("Always use the correct {enum}", new object[] { NLog.Config.ExceptionRenderingFormat.Method }, "Always use the correct Method")] [InlineData("Always use the correct {enum:D}", new object[] { NLog.Config.ExceptionRenderingFormat.Method }, "Always use the correct 4")] [InlineData("hello {0,-10}", new object[] { null }, "hello NULL ")] [InlineData("hello {0,10}", new object[] { null }, "hello NULL")] [InlineData("Status [0x{status:X8}]", new object[] { 16 }, "Status [0x00000010]")] public void RenderTest(string input, object[] args, string expected) { var culture = CultureInfo.InvariantCulture; RenderAndTest(input, culture, args, expected); } [Theory] [InlineData("test {0}", "nl", new object[] { 12.3 }, "test 12,3")] [InlineData("test {0}", "en-gb", new object[] { 12.3 }, "test 12.3")] public void RenderCulture(string input, string language, object[] args, string expected) { var culture = new CultureInfo(language); RenderAndTest(input, culture, args, expected); } [Theory] [InlineData("test {0:u}", "1970-01-01", "test 1970-01-01 00:00:00Z")] [InlineData("test {0:MM/dd/yy}", "1970-01-01", "test 01/01/70")] public void RenderDateTime(string input, string arg, string expected) { var culture = CultureInfo.InvariantCulture; DateTime dt = DateTime.Parse(arg, culture, DateTimeStyles.AdjustToUniversal); RenderAndTest(input, culture, new object[] { dt }, expected); } [Theory] [InlineData("test {0:c}", "1:2:3:4.5", "test 1.02:03:04.5000000")] [InlineData("test {0:hh\\:mm\\:ss\\.ff}", "1:2:3:4.5", "test 02:03:04.50")] public void RenderTimeSpan(string input, string arg, string expected) { var culture = CultureInfo.InvariantCulture; TimeSpan ts = TimeSpan.Parse(arg, culture); RenderAndTest(input, culture, new object[] { ts }, expected); } [Theory] [InlineData("test {0:u}", "1 Jan 1970 01:02:03Z", "test 1970-01-01 01:02:03Z")] [InlineData("test {0:s}", "1 Jan 1970 01:02:03Z", "test 1970-01-01T01:02:03")] public void RenderDateTimeOffset(string input, string arg, string expected) { var culture = CultureInfo.InvariantCulture; DateTimeOffset dto = DateTimeOffset.Parse(arg, culture, DateTimeStyles.AdjustToUniversal); RenderAndTest(input, culture, new object[] { dto }, expected); } private static void RenderAndTest(string input, CultureInfo culture, object[] args, string expected) { var logEventInfoAlways = new LogEventInfo(LogLevel.Info, "Logger", culture, input, args); logEventInfoAlways.SetMessageFormatter(new NLog.Internal.LogMessageTemplateFormatter(LogManager.LogFactory.ServiceRepository, true, false).MessageFormatter, null); var templateAlways = logEventInfoAlways.MessageTemplateParameters; Assert.Equal(expected, logEventInfoAlways.FormattedMessage); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using NLog.Common; using NLog.Config; using NLog.Internal; /// <summary> /// Creates and manages instances of <see cref="NLog.Logger" /> objects. /// </summary> /// <remarks> /// LogManager wraps a singleton instance of <see cref="NLog.LogFactory" />. /// </remarks> public static class LogManager { /// <remarks> /// Internal for unit tests /// </remarks> internal static readonly LogFactory factory = new LogFactory(); private static ICollection<Assembly> _hiddenAssemblies; private static readonly object lockObject = new object(); /// <summary> /// Gets the <see cref="NLog.LogFactory" /> instance used in the <see cref="LogManager"/>. /// </summary> /// <remarks>Could be used to pass the to other methods</remarks> public static LogFactory LogFactory => factory; /// <summary> /// Occurs when logging <see cref="Configuration" /> changes. /// </summary> public static event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged { add => factory.ConfigurationChanged += value; remove => factory.ConfigurationChanged -= value; } #if !NETSTANDARD1_3 /// <summary> /// Occurs when logging <see cref="Configuration" /> gets reloaded. /// </summary> [Obsolete("Replaced by ConfigurationChanged, but check args.ActivatedConfiguration != null. Marked obsolete on NLog 5.2")] public static event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded { add => factory.ConfigurationReloaded += value; remove => factory.ConfigurationReloaded -= value; } #endif /// <summary> /// Gets or sets a value indicating whether NLog should throw exceptions. /// By default exceptions are not thrown under any circumstances. /// </summary> public static bool ThrowExceptions { get => factory.ThrowExceptions; set => factory.ThrowExceptions = value; } /// <summary> /// Gets or sets a value indicating whether <see cref="NLogConfigurationException"/> should be thrown. /// </summary> /// <value>A value of <c>true</c> if exception should be thrown; otherwise, <c>false</c>.</value> /// <remarks> /// This option is for backwards-compatibility. /// By default exceptions are not thrown under any circumstances. /// /// </remarks> public static bool? ThrowConfigExceptions { get => factory.ThrowConfigExceptions; set => factory.ThrowConfigExceptions = value; } /// <summary> /// Gets or sets a value indicating whether Variables should be kept on configuration reload. /// </summary> public static bool KeepVariablesOnReload { get => factory.KeepVariablesOnReload; set => factory.KeepVariablesOnReload = value; } /// <summary> /// Gets or sets a value indicating whether to automatically call <see cref="LogManager.Shutdown"/> /// on AppDomain.Unload or AppDomain.ProcessExit /// </summary> public static bool AutoShutdown { get => factory.AutoShutdown; set => factory.AutoShutdown = value; } /// <summary> /// Gets or sets the current logging configuration. /// </summary> /// <remarks> /// Setter will re-configure all <see cref="Logger"/>-objects, so no need to also call <see cref="ReconfigExistingLoggers()" /> /// </remarks> public static LoggingConfiguration Configuration { get => factory.Configuration; set => factory.Configuration = value; } /// <summary> /// Begins configuration of the LogFactory options using fluent interface /// </summary> public static ISetupBuilder Setup() { return LogFactory.Setup(); } /// <summary> /// Begins configuration of the LogFactory options using fluent interface /// </summary> public static LogFactory Setup(Action<ISetupBuilder> setupBuilder) { return LogFactory.Setup(setupBuilder); } /// <summary> /// Loads logging configuration from file (Currently only XML configuration files supported) /// </summary> /// <param name="configFile">Configuration file to be read</param> /// <returns>LogFactory instance for fluent interface</returns> [Obsolete("Replaced by LogManager.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] public static LogFactory LoadConfiguration(string configFile) { factory.LoadConfiguration(configFile); return factory; } /// <summary> /// Gets or sets the global log threshold. Log events below this threshold are not logged. /// </summary> public static LogLevel GlobalThreshold { get => factory.GlobalThreshold; set => factory.GlobalThreshold = value; } /// <summary> /// Gets the logger with the full name of the current class, so namespace and class name. /// </summary> /// <returns>The logger.</returns> /// <remarks>This is a slow-running method. /// Make sure you're not doing this in a loop.</remarks> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.NoInlining)] public static Logger GetCurrentClassLogger() { return factory.GetLogger(StackTraceUsageUtils.GetClassFullName()); } internal static bool IsHiddenAssembly(Assembly assembly) { return _hiddenAssemblies != null && _hiddenAssemblies.Contains(assembly); } /// <summary> /// Adds the given assembly which will be skipped /// when NLog is trying to find the calling method on stack trace. /// </summary> /// <param name="assembly">The assembly to skip.</param> [MethodImpl(MethodImplOptions.NoInlining)] public static void AddHiddenAssembly(Assembly assembly) { lock (lockObject) { if (_hiddenAssemblies != null && _hiddenAssemblies.Contains(assembly)) return; _hiddenAssemblies = new HashSet<Assembly>(_hiddenAssemblies ?? Enumerable.Empty<Assembly>()) { assembly }; } InternalLogger.Trace("Assembly '{0}' will be hidden in callsite stacktrace", assembly?.FullName); } /// <summary> /// Gets a custom logger with the full name of the current class, so namespace and class name. /// Use <paramref name="loggerType"/> to create instance of a custom <see cref="Logger"/>. /// If you haven't defined your own <see cref="Logger"/> class, then use the overload without the loggerType. /// </summary> /// <param name="loggerType">The logger class. This class must inherit from <see cref="Logger" />.</param> /// <returns>The logger of type <paramref name="loggerType"/>.</returns> /// <remarks>This is a slow-running method. /// Make sure you're not doing this in a loop.</remarks> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.NoInlining)] [Obsolete("Replaced by LogFactory.GetCurrentClassLogger<T>(). Marked obsolete on NLog 5.2")] public static Logger GetCurrentClassLogger([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type loggerType) { return factory.GetLogger(StackTraceUsageUtils.GetClassFullName(), loggerType); } /// <summary> /// Creates a logger that discards all log messages. /// </summary> /// <returns>Null logger which discards all log messages.</returns> public static Logger CreateNullLogger() { return factory.CreateNullLogger(); } /// <summary> /// Gets the specified named logger. /// </summary> /// <param name="name">Name of the logger.</param> /// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns> public static Logger GetLogger(string name) { return factory.GetLogger(name); } /// <summary> /// Gets the specified named custom logger. /// Use <paramref name="loggerType"/> to create instance of a custom <see cref="Logger"/>. /// If you haven't defined your own <see cref="Logger"/> class, then use the overload without the loggerType. /// </summary> /// <param name="name">Name of the logger.</param> /// <param name="loggerType">The logger class. This class must inherit from <see cref="Logger" />.</param> /// <returns>The logger of type <paramref name="loggerType"/>. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns> /// <remarks>The generic way for this method is <see cref="NLog.LogFactory{loggerType}.GetLogger(string)"/></remarks> [Obsolete("Replaced by LogFactory.GetLogger<T>(). Marked obsolete on NLog 5.2")] public static Logger GetLogger(string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type loggerType) { return factory.GetLogger(name, loggerType); } /// <summary> /// Loops through all loggers previously returned by GetLogger. /// and recalculates their target and filter list. Useful after modifying the configuration programmatically /// to ensure that all loggers have been properly configured. /// </summary> public static void ReconfigExistingLoggers() { factory.ReconfigExistingLoggers(); } /// <summary> /// Loops through all loggers previously returned by GetLogger. /// and recalculates their target and filter list. Useful after modifying the configuration programmatically /// to ensure that all loggers have been properly configured. /// </summary> /// <param name="purgeObsoleteLoggers">Purge garbage collected logger-items from the cache</param> public static void ReconfigExistingLoggers(bool purgeObsoleteLoggers) { factory.ReconfigExistingLoggers(purgeObsoleteLoggers); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets) with the default timeout of 15 seconds. /// </summary> public static void Flush() { factory.Flush(); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public static void Flush(TimeSpan timeout) { factory.Flush(timeout); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public static void Flush(int timeoutMilliseconds) { factory.Flush(timeoutMilliseconds); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> public static void Flush(AsyncContinuation asyncContinuation) { factory.Flush(asyncContinuation); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public static void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout) { factory.Flush(asyncContinuation, timeout); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public static void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds) { factory.Flush(asyncContinuation, timeoutMilliseconds); } /// <summary> /// Suspends the logging, and returns object for using-scope so scope-exit calls <see cref="EnableLogging"/> /// </summary> /// <remarks> /// Logging is suspended when the number of <see cref="DisableLogging"/> calls are greater /// than the number of <see cref="EnableLogging"/> calls. /// </remarks> /// <returns>An object that implements IDisposable whose Dispose() method re-enables logging. /// To be used with C# <c>using ()</c> statement.</returns> [Obsolete("Use SuspendLogging() instead. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public static IDisposable DisableLogging() { return factory.SuspendLogging(); } /// <summary> /// Resumes logging if having called <see cref="DisableLogging"/>. /// </summary> /// <remarks> /// Logging is suspended when the number of <see cref="DisableLogging"/> calls are greater /// than the number of <see cref="EnableLogging"/> calls. /// </remarks> [Obsolete("Use ResumeLogging() instead. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public static void EnableLogging() { factory.ResumeLogging(); } /// <summary> /// Suspends the logging, and returns object for using-scope so scope-exit calls <see cref="ResumeLogging"/> /// </summary> /// <remarks> /// Logging is suspended when the number of <see cref="SuspendLogging"/> calls are greater /// than the number of <see cref="ResumeLogging"/> calls. /// </remarks> /// <returns>An object that implements IDisposable whose Dispose() method re-enables logging. /// To be used with C# <c>using ()</c> statement.</returns> public static IDisposable SuspendLogging() { return factory.SuspendLogging(); } /// <summary> /// Resumes logging if having called <see cref="SuspendLogging"/>. /// </summary> /// <remarks> /// Logging is suspended when the number of <see cref="SuspendLogging"/> calls are greater /// than the number of <see cref="ResumeLogging"/> calls. /// </remarks> public static void ResumeLogging() { factory.ResumeLogging(); } /// <summary> /// Returns <see langword="true" /> if logging is currently enabled. /// </summary> /// <remarks> /// Logging is suspended when the number of <see cref="SuspendLogging"/> calls are greater /// than the number of <see cref="ResumeLogging"/> calls. /// </remarks> /// <returns>A value of <see langword="true" /> if logging is currently enabled, /// <see langword="false"/> otherwise.</returns> public static bool IsLoggingEnabled() { return factory.IsLoggingEnabled(); } /// <summary> /// Dispose all targets, and shutdown logging. /// </summary> public static void Shutdown() { factory.Shutdown(); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Config; namespace NLog.UnitTests.LayoutRenderers.Wrappers { using NLog; using NLog.Layouts; using NLog.Targets; using Xunit; public class WrapLineTests : NLogTestBase { [Fact] public void WrapLineWithInnerLayoutDefaultTest() { ScopeContext.PushProperty("foo", "foobar"); SimpleLayout le = "${wrapline:${scopeproperty:foo}:WrapLine=3}"; Assert.Equal("foo" + System.Environment.NewLine + "bar", le.Render(LogEventInfo.CreateNullEvent())); } [Fact] public void WrapLineWithInnerLayoutTest() { ScopeContext.PushProperty("foo", "foobar"); SimpleLayout le = "${wrapline:Inner=${scopeproperty:foo}:WrapLine=3}"; Assert.Equal("foo" + System.Environment.NewLine + "bar", le.Render(LogEventInfo.CreateNullEvent())); } [Fact] public void WrapLineAtPositionOnceTest() { SimpleLayout l = "${message:wrapline=3}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "foobar"); Assert.Equal("foo" + System.Environment.NewLine + "bar", l.Render(le)); } [Fact] public void WrapLineAtPositionOnceTextLengthNotMultipleTest() { SimpleLayout l = "${message:wrapline=3}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "fooba"); Assert.Equal("foo" + System.Environment.NewLine + "ba", l.Render(le)); } [Fact] public void WrapLineMultipleTimesTest() { SimpleLayout l = "${message:wrapline=3}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "foobarbaz"); Assert.Equal("foo" + System.Environment.NewLine + "bar" + System.Environment.NewLine + "baz", l.Render(le)); } [Fact] public void WrapLineMultipleTimesTextLengthNotMultipleTest() { SimpleLayout l = "${message:wrapline=3}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "foobarba"); Assert.Equal("foo" + System.Environment.NewLine + "bar" + System.Environment.NewLine + "ba", l.Render(le)); } [Fact] public void WrapLineAtPositionAtExactTextLengthTest() { SimpleLayout l = "${message:wrapline=6}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "foobar"); Assert.Equal("foobar", l.Render(le)); } [Fact] public void WrapLineAtPositionGreaterThanTextLengthTest() { SimpleLayout l = "${message:wrapline=10}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "foobar"); Assert.Equal("foobar", l.Render(le)); } [Fact] public void WrapLineAtPositionZeroTest() { SimpleLayout l = "${message:wrapline=0}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "foobar"); Assert.Equal("foobar", l.Render(le)); } [Fact] public void WrapLineAtNegativePositionTest() { SimpleLayout l = "${message:wrapline=0}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "foobar"); Assert.Equal("foobar", l.Render(le)); } [Fact] public void WrapLineFromConfig() { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <target name='d1' type='Debug' layout='${message:wrapline=3}' /> </targets> <rules> <logger name=""*"" minlevel=""Trace"" writeTo=""d1"" /> </rules> </nlog>"); var d1 = configuration.FindTargetByName("d1") as DebugTarget; Assert.NotNull(d1); var layout = d1.Layout as SimpleLayout; Assert.NotNull(layout); var result = layout.Render(new LogEventInfo(LogLevel.Info, "Test", "foobar")); Assert.Equal("foo" + System.Environment.NewLine + "bar", result); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Linq; using NLog.Internal; using Xunit; namespace NLog.UnitTests.Internal { public class StringHelpersTests { [Theory] [InlineData("", true)] [InlineData(" ", true)] [InlineData(" \n", true)] [InlineData(" \na", false)] [InlineData("a", false)] [InlineData(" a", false)] public void IsNullOrWhiteSpaceTest(string input, bool result) { Assert.Equal(result, StringHelpers.IsNullOrWhiteSpace(input)); } [Theory] [InlineData("", new string[0])] [InlineData(" ", new string[0])] [InlineData(" , ", new string[0])] [InlineData("a", new string[] { "a" })] [InlineData("a ", new string[] { "a" })] [InlineData(" a", new string[] { "a" })] [InlineData(" a,", new string[] { "a" })] [InlineData(" a, ", new string[] { "a" })] [InlineData("a,b", new string[] { "a", "b" })] [InlineData("a ,b", new string[] { "a", "b" })] [InlineData(" a ,b", new string[] { "a", "b" })] [InlineData(" a , b ", new string[] { "a", "b" })] [InlineData(" a b ", new string[] { "a b" })] public void SplitAndTrimToken(string input, string[] expected) { var result = input.SplitAndTrimTokens(','); Assert.Equal(expected, result); } [Theory] [InlineData("", "", "", StringComparison.InvariantCulture, "")] [InlineData("", "", null, StringComparison.InvariantCulture, "")] [InlineData("a", "a", "b", StringComparison.InvariantCulture, "b")] [InlineData("aa", "a", "b", StringComparison.InvariantCulture, "bb")] [InlineData("aa", "a", "", StringComparison.InvariantCulture, "")] [InlineData(" Caac ", "a", "", StringComparison.InvariantCulture, " Cc ")] [InlineData(" Caac ", "a", " ", StringComparison.InvariantCulture, " C c ")] [InlineData("aA", "a", "b", StringComparison.InvariantCulture, "bA")] [InlineData("aA", "a", "b", StringComparison.InvariantCultureIgnoreCase, "bb")] [InlineData("�", "�", "", StringComparison.InvariantCulture, "")] [InlineData("�", "oe", "", StringComparison.OrdinalIgnoreCase, "�")] [InlineData("var ${var}", "${var}", "2", StringComparison.InvariantCulture, "var 2")] [InlineData("var ${var}", "${VAR}", "2", StringComparison.InvariantCulture, "var ${var}")] [InlineData("var ${VAR}", "${var}", "2", StringComparison.InvariantCulture, "var ${VAR}")] [InlineData("var ${var}", "${VAR}", "2", StringComparison.InvariantCultureIgnoreCase, "var 2")] [InlineData("var ${VAR}", "${var}", "2", StringComparison.InvariantCultureIgnoreCase, "var 2")] public void ReplaceTest(string input, string search, string replace, StringComparison comparer, string result) { Assert.Equal(result, StringHelpers.Replace(input, search, replace, comparer)); } [Theory] [InlineData(null, "", "", StringComparison.InvariantCulture)] [InlineData("", null, "", StringComparison.InvariantCulture)] public void ReplaceTestThrowsNullException(string input, string search, string replace, StringComparison comparer) { Assert.Throws<ArgumentNullException>(() => StringHelpers.Replace(input, search, replace, comparer)); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.Linq; using NLog.Internal; /// <summary> /// Async version of <see cref="NestedDiagnosticsContext" /> - a logical context structure that keeps a stack /// Allows for maintaining scope across asynchronous tasks and call contexts. /// </summary> [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public static class NestedDiagnosticsLogicalContext { /// <summary> /// Pushes the specified value on current stack /// </summary> /// <param name="value">The value to be pushed.</param> /// <returns>An instance of the object that implements IDisposable that returns the stack to the previous level when IDisposable.Dispose() is called. To be used with C# using() statement.</returns> [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public static IDisposable Push<T>(T value) { return ScopeContext.PushNestedState(value); } /// <summary> /// Pushes the specified value on current stack /// </summary> /// <param name="value">The value to be pushed.</param> /// <returns>An instance of the object that implements IDisposable that returns the stack to the previous level when IDisposable.Dispose() is called. To be used with C# using() statement.</returns> [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public static IDisposable PushObject(object value) { return Push(value); } /// <summary> /// Pops the top message off the NDLC stack. /// </summary> /// <returns>The top message which is no longer on the stack.</returns> /// <remarks>this methods returns a object instead of string, this because of backwards-compatibility</remarks> [Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")] public static object Pop() { return PopObject(); } /// <summary> /// Pops the top message from the NDLC stack. /// </summary> /// <param name="formatProvider">The <see cref="IFormatProvider"/> to use when converting the value to a string.</param> /// <returns>The top message, which is removed from the stack, as a string value.</returns> [Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")] public static string Pop(IFormatProvider formatProvider) { return FormatHelper.ConvertToString(PopObject() ?? string.Empty, formatProvider); } /// <summary> /// Pops the top message off the current NDLC stack /// </summary> /// <returns>The object from the top of the NDLC stack, if defined; otherwise <c>null</c>.</returns> [Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")] public static object PopObject() { return ScopeContext.PopNestedContextLegacy(); } /// <summary> /// Peeks the top object on the current NDLC stack /// </summary> /// <returns>The object from the top of the NDLC stack, if defined; otherwise <c>null</c>.</returns> [Obsolete("Replaced by ScopeContext.PeekNestedState. Marked obsolete on NLog 5.0")] public static object PeekObject() { return ScopeContext.PeekNestedState(); } /// <summary> /// Clears current stack. /// </summary> [Obsolete("Replaced by ScopeContext.Clear. Marked obsolete on NLog 5.0")] public static void Clear() { ScopeContext.ClearNestedContextLegacy(); } /// <summary> /// Gets all messages on the stack. /// </summary> /// <returns>Array of strings on the stack.</returns> [Obsolete("Replaced by ScopeContext.GetAllNestedStates. Marked obsolete on NLog 5.0")] public static string[] GetAllMessages() { return GetAllMessages(null); } /// <summary> /// Gets all messages from the stack, without removing them. /// </summary> /// <param name="formatProvider">The <see cref="IFormatProvider"/> to use when converting a value to a string.</param> /// <returns>Array of strings.</returns> [Obsolete("Replaced by ScopeContext.GetAllNestedStates. Marked obsolete on NLog 5.0")] public static string[] GetAllMessages(IFormatProvider formatProvider) { return GetAllObjects().Select((o) => FormatHelper.ConvertToString(o, formatProvider)).ToArray(); } /// <summary> /// Gets all objects on the stack. The objects are not removed from the stack. /// </summary> /// <returns>Array of objects on the stack.</returns> [Obsolete("Replaced by ScopeContext.GetAllNestedStates. Marked obsolete on NLog 5.0")] public static object[] GetAllObjects() { return ScopeContext.GetAllNestedStates(); } [Obsolete("Required to be compatible with legacy NLog versions, when using remoting. Marked obsolete on NLog 5.0")] interface INestedContext : IDisposable { INestedContext Parent { get; } int FrameLevel { get; } object Value { get; } long CreatedTimeUtcTicks { get; } } #if !NETSTANDARD1_3 && !NETSTANDARD1_5 [Serializable] #endif [Obsolete("Required to be compatible with legacy NLog versions, when using remoting. Marked obsolete on NLog 5.0")] sealed class NestedContext<T> : INestedContext { public INestedContext Parent { get; } public T Value { get; } public long CreatedTimeUtcTicks { get; } public int FrameLevel { get; } private int _disposed; object INestedContext.Value { get { object value = Value; #if NET35 || NET40 || NET45 if (value is ObjectHandleSerializer objectHandle) { return objectHandle.Unwrap(); } #endif return value; } } public NestedContext(INestedContext parent, T value) { Parent = parent; Value = value; CreatedTimeUtcTicks = DateTime.UtcNow.Ticks; // Low time resolution, but okay fast FrameLevel = parent?.FrameLevel + 1 ?? 1; } void IDisposable.Dispose() { if (System.Threading.Interlocked.Exchange(ref _disposed, 1) != 1) { PopObject(); } } public override string ToString() { object value = Value; return value?.ToString() ?? "null"; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections; using System.Collections.Generic; using NLog.Common; /// <summary> /// Provides helpers to sort log events and associated continuations. /// </summary> internal static class SortHelpers { /// <summary> /// Key selector delegate. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <param name="value">Value to extract key information from.</param> /// <returns>Key selected from log event.</returns> internal delegate TKey KeySelector<in TValue, out TKey>(TValue value); /// <summary> /// Performs bucket sort (group by) on an array of items and returns a dictionary for easy traversal of the result set. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <param name="inputs">The inputs.</param> /// <param name="keySelector">The key selector function.</param> /// <returns> /// Dictionary where keys are unique input keys, and values are lists of <see cref="AsyncLogEventInfo"/>. /// </returns> public static Dictionary<TKey, List<TValue>> BucketSort<TValue, TKey>(this IEnumerable<TValue> inputs, KeySelector<TValue, TKey> keySelector) { var buckets = new Dictionary<TKey, List<TValue>>(); foreach (var input in inputs) { var keyValue = keySelector(input); if (!buckets.TryGetValue(keyValue, out var eventsInBucket)) { eventsInBucket = new List<TValue>(); buckets.Add(keyValue, eventsInBucket); } eventsInBucket.Add(input); } return buckets; } /// <summary> /// Performs bucket sort (group by) on an array of items and returns a dictionary for easy traversal of the result set. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <param name="inputs">The inputs.</param> /// <param name="keySelector">The key selector function.</param> /// <returns> /// Dictionary where keys are unique input keys, and values are lists of <see cref="AsyncLogEventInfo"/>. /// </returns> public static ReadOnlySingleBucketDictionary<TKey, IList<TValue>> BucketSort<TValue, TKey>(this IList<TValue> inputs, KeySelector<TValue, TKey> keySelector) { return BucketSort(inputs, keySelector, EqualityComparer<TKey>.Default); } /// <summary> /// Performs bucket sort (group by) on an array of items and returns a dictionary for easy traversal of the result set. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <param name="inputs">The inputs.</param> /// <param name="keySelector">The key selector function.</param> /// <param name="keyComparer">The key comparer function.</param> /// <returns> /// Dictionary where keys are unique input keys, and values are lists of <see cref="AsyncLogEventInfo"/>. /// </returns> public static ReadOnlySingleBucketDictionary<TKey, IList<TValue>> BucketSort<TValue, TKey>(this IList<TValue> inputs, KeySelector<TValue, TKey> keySelector, IEqualityComparer<TKey> keyComparer) { Dictionary<TKey, IList<TValue>> buckets = null; TKey singleBucketKey = default(TKey); for (int i = 0; i < inputs.Count; i++) { TKey keyValue = keySelector(inputs[i]); if (i == 0) { singleBucketKey = keyValue; } else if (buckets is null) { if (!keyComparer.Equals(singleBucketKey, keyValue)) { // Multiple buckets needed, allocate full dictionary buckets = CreateBucketDictionaryWithValue(inputs, keyComparer, i, singleBucketKey, keyValue); } } else { if (!buckets.TryGetValue(keyValue, out var eventsInBucket)) { eventsInBucket = new List<TValue>(); buckets.Add(keyValue, eventsInBucket); } eventsInBucket.Add(inputs[i]); } } if (buckets is null) return new ReadOnlySingleBucketDictionary<TKey, IList<TValue>>(new KeyValuePair<TKey, IList<TValue>>(singleBucketKey, inputs), keyComparer); else return new ReadOnlySingleBucketDictionary<TKey, IList<TValue>>(buckets, keyComparer); } private static Dictionary<TKey, IList<TValue>> CreateBucketDictionaryWithValue<TValue, TKey>(IList<TValue> inputs, IEqualityComparer<TKey> keyComparer, int currentIndex, TKey firstBucketKey, TKey nextBucketKey) { var buckets = new Dictionary<TKey, IList<TValue>>(keyComparer); var firstBucket = new List<TValue>(currentIndex); for (int i = 0; i < currentIndex; i++) { firstBucket.Add(inputs[i]); } buckets[firstBucketKey] = firstBucket; var nextBucket = new List<TValue> { inputs[currentIndex] }; buckets[nextBucketKey] = nextBucket; return buckets; } /// <summary> /// Single-Bucket optimized readonly dictionary. Uses normal internally Dictionary if multiple buckets are needed. /// /// Avoids allocating a new dictionary, when all items are using the same bucket /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> public struct ReadOnlySingleBucketDictionary<TKey, TValue> : IDictionary<TKey, TValue> { KeyValuePair<TKey, TValue>? _singleBucket; // Not readonly to avoid struct-copy, and to avoid VerificationException when medium-trust AppDomain readonly Dictionary<TKey, TValue> _multiBucket; readonly IEqualityComparer<TKey> _comparer; public IEqualityComparer<TKey> Comparer => _comparer; public ReadOnlySingleBucketDictionary(KeyValuePair<TKey, TValue> singleBucket) : this(singleBucket, EqualityComparer<TKey>.Default) { } public ReadOnlySingleBucketDictionary(Dictionary<TKey, TValue> multiBucket) : this(multiBucket, EqualityComparer<TKey>.Default) { } public ReadOnlySingleBucketDictionary(KeyValuePair<TKey, TValue> singleBucket, IEqualityComparer<TKey> comparer) { _comparer = comparer; _multiBucket = null; _singleBucket = singleBucket; } public ReadOnlySingleBucketDictionary(Dictionary<TKey, TValue> multiBucket, IEqualityComparer<TKey> comparer) { _comparer = comparer; _multiBucket = multiBucket; _singleBucket = default(KeyValuePair<TKey, TValue>); } /// <inheritDoc/> public int Count { get { if (_multiBucket != null) return _multiBucket.Count; else if (_singleBucket.HasValue) return 1; else return 0; } } /// <inheritDoc/> public ICollection<TKey> Keys { get { if (_multiBucket != null) return _multiBucket.Keys; else if (_singleBucket.HasValue) return new[] { _singleBucket.Value.Key }; else return ArrayHelper.Empty<TKey>(); } } /// <inheritDoc/> public ICollection<TValue> Values { get { if (_multiBucket != null) return _multiBucket.Values; else if (_singleBucket.HasValue) return new TValue[] { _singleBucket.Value.Value }; else return ArrayHelper.Empty<TValue>(); } } /// <inheritDoc/> public bool IsReadOnly => true; /// <summary> /// Allows direct lookup of existing keys. If trying to access non-existing key exception is thrown. /// Consider to use <see cref="TryGetValue(TKey, out TValue)"/> instead for better safety. /// </summary> /// <param name="key">Key value for lookup</param> /// <returns>Mapped value found</returns> public TValue this[TKey key] { get { if (_multiBucket != null) return _multiBucket[key]; else if (_singleBucket.HasValue && _comparer.Equals(_singleBucket.Value.Key, key)) return _singleBucket.Value.Value; else throw new KeyNotFoundException(); } set => throw new NotSupportedException("Readonly"); } /// <summary> /// Non-Allocating struct-enumerator /// </summary> public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>> { bool _singleBucketFirstRead; KeyValuePair<TKey, TValue> _singleBucket; // Not readonly to avoid struct-copy, and to avoid VerificationException when medium-trust AppDomain readonly IEnumerator<KeyValuePair<TKey, TValue>> _multiBuckets; internal Enumerator(Dictionary<TKey, TValue> multiBucket) { _singleBucketFirstRead = false; _singleBucket = default(KeyValuePair<TKey, TValue>); _multiBuckets = multiBucket.GetEnumerator(); } internal Enumerator(KeyValuePair<TKey, TValue> singleBucket) { _singleBucketFirstRead = false; _singleBucket = singleBucket; _multiBuckets = null; } public KeyValuePair<TKey, TValue> Current { get { if (_multiBuckets != null) return new KeyValuePair<TKey, TValue>(_multiBuckets.Current.Key, _multiBuckets.Current.Value); else return new KeyValuePair<TKey, TValue>(_singleBucket.Key, _singleBucket.Value); } } object IEnumerator.Current => Current; public void Dispose() { if (_multiBuckets != null) _multiBuckets.Dispose(); } public bool MoveNext() { if (_multiBuckets != null) return _multiBuckets.MoveNext(); else if (_singleBucketFirstRead) return false; else return _singleBucketFirstRead = true; } public void Reset() { if (_multiBuckets != null) _multiBuckets.Reset(); else _singleBucketFirstRead = false; } } public Enumerator GetEnumerator() { if (_multiBucket != null) return new Enumerator(_multiBucket); else if (_singleBucket.HasValue) return new Enumerator(_singleBucket.Value); else return new Enumerator(new Dictionary<TKey, TValue>()); } /// <inheritDoc/> IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return GetEnumerator(); } /// <inheritDoc/> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <inheritDoc/> public bool ContainsKey(TKey key) { if (_multiBucket != null) return _multiBucket.ContainsKey(key); else if (_singleBucket.HasValue) return _comparer.Equals(_singleBucket.Value.Key, key); else return false; } /// <summary>Will always throw, as dictionary is readonly</summary> public void Add(TKey key, TValue value) { throw new NotSupportedException(); // Readonly } /// <summary>Will always throw, as dictionary is readonly</summary> public bool Remove(TKey key) { throw new NotSupportedException(); // Readonly } /// <inheritDoc/> public bool TryGetValue(TKey key, out TValue value) { if (_multiBucket != null) { return _multiBucket.TryGetValue(key, out value); } else if (_singleBucket.HasValue && _comparer.Equals(_singleBucket.Value.Key, key)) { value = _singleBucket.Value.Value; return true; } else { value = default(TValue); return false; } } /// <summary>Will always throw, as dictionary is readonly</summary> public void Add(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(); // Readonly } /// <summary>Will always throw, as dictionary is readonly</summary> public void Clear() { throw new NotSupportedException(); // Readonly } /// <inheritDoc/> public bool Contains(KeyValuePair<TKey, TValue> item) { if (_multiBucket != null) return ((IDictionary<TKey, TValue>)_multiBucket).Contains(item); else if (_singleBucket.HasValue) return _comparer.Equals(_singleBucket.Value.Key, item.Key) && EqualityComparer<TValue>.Default.Equals(_singleBucket.Value.Value, item.Value); else return false; } /// <inheritDoc/> public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { if (_multiBucket != null) ((IDictionary<TKey, TValue>)_multiBucket).CopyTo(array, arrayIndex); else if (_singleBucket.HasValue) array[arrayIndex] = _singleBucket.Value; } /// <summary>Will always throw, as dictionary is readonly</summary> public bool Remove(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(); // Readonly } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Text.RegularExpressions; /// <summary> /// Encapsulates <see cref="LoggingRule.LoggerNamePattern"/> and the logic to match the actual logger name /// All subclasses defines immutable objects. /// Concrete subclasses defines various matching rules through <see cref="LoggerNameMatcher.NameMatches(string)"/> /// </summary> abstract class LoggerNameMatcher { /// <summary> /// Creates a concrete <see cref="LoggerNameMatcher"/> based on <paramref name="loggerNamePattern"/>. /// </summary> /// <remarks> /// Rules used to select the concrete implementation returned: /// <list type="number"> /// <item>if <paramref name="loggerNamePattern"/> is null => returns <see cref="NoneLoggerNameMatcher"/> (never matches)</item> /// <item>if <paramref name="loggerNamePattern"/> doesn't contains any '*' nor '?' => returns <see cref="EqualsLoggerNameMatcher"/> (matches only on case sensitive equals)</item> /// <item>if <paramref name="loggerNamePattern"/> == '*' => returns <see cref="AllLoggerNameMatcher"/> (always matches)</item> /// <item>if <paramref name="loggerNamePattern"/> doesn't contain '?' /// <list type="number"> /// <item>if <paramref name="loggerNamePattern"/> contains exactly 2 '*' one at the beginning and one at the end (i.e. "*foobar*) => returns <see cref="ContainsLoggerNameMatcher"/></item> /// <item>if <paramref name="loggerNamePattern"/> contains exactly 1 '*' at the beginning (i.e. "*foobar") => returns <see cref="EndsWithLoggerNameMatcher"/></item> /// <item>if <paramref name="loggerNamePattern"/> contains exactly 1 '*' at the end (i.e. "foobar*") => returns <see cref="StartsWithLoggerNameMatcher"/></item> /// </list> /// </item> /// <item>returns <see cref="MultiplePatternLoggerNameMatcher"/></item> /// </list> /// </remarks> /// <param name="loggerNamePattern"> /// It may include one or more '*' or '?' wildcards at any position. /// <list type="bullet"> /// <item>'*' means zero or more occurrences of any character</item> /// <item>'?' means exactly one occurrence of any character</item> /// </list> /// </param> /// <returns>A concrete <see cref="LoggerNameMatcher"/></returns> public static LoggerNameMatcher Create(string loggerNamePattern) { if (loggerNamePattern is null) return NoneLoggerNameMatcher.Instance; if (loggerNamePattern.Trim()=="*") return AllLoggerNameMatcher.Instance; int starPos1 = loggerNamePattern.IndexOf('*'); int starPos2 = loggerNamePattern.IndexOf('*', starPos1 + 1); int questionPos = loggerNamePattern.IndexOf('?'); if (starPos1 < 0 && questionPos < 0) return new EqualsLoggerNameMatcher(loggerNamePattern); if (questionPos < 0) { if (starPos1 == 0 && starPos2 == loggerNamePattern.Length - 1) return new ContainsLoggerNameMatcher(loggerNamePattern); if (starPos2 < 0) { var loggerNameMatcher = CreateStartsOrEndsWithLoggerNameMatcher(loggerNamePattern, starPos1); if (loggerNameMatcher != null) { return loggerNameMatcher; } } } return new MultiplePatternLoggerNameMatcher(loggerNamePattern); } private static LoggerNameMatcher CreateStartsOrEndsWithLoggerNameMatcher(string loggerNamePattern, int starPos1) { if (starPos1 == 0) return new EndsWithLoggerNameMatcher(loggerNamePattern); if (starPos1 == loggerNamePattern.Length - 1) return new StartsWithLoggerNameMatcher(loggerNamePattern); return null; } /// <summary> /// Returns the argument passed to <see cref="LoggerNameMatcher.Create(string)"/> /// </summary> public string Pattern { get; } protected readonly string _matchingArgument; private readonly string _toString; protected LoggerNameMatcher(string pattern, string matchingArgument) { Pattern = pattern; _matchingArgument = matchingArgument; _toString = $"logNamePattern: ({matchingArgument}:{MatchMode})"; } public override string ToString() { return _toString; } protected abstract string MatchMode { get; } /// <summary> /// Checks whether given name matches the logger name pattern. /// </summary> /// <param name="loggerName">String to be matched.</param> /// <returns>A value of <see langword="true"/> when the name matches, <see langword="false" /> otherwise.</returns> public abstract bool NameMatches(string loggerName); /// <summary> /// Defines a <see cref="LoggerNameMatcher"/> that never matches. /// Used when pattern is null /// </summary> class NoneLoggerNameMatcher : LoggerNameMatcher { protected override string MatchMode => "None"; public static readonly NoneLoggerNameMatcher Instance = new NoneLoggerNameMatcher(); private NoneLoggerNameMatcher() : base(null, null) { } public override bool NameMatches(string loggerName) { return false; } } /// <summary> /// Defines a <see cref="LoggerNameMatcher"/> that always matches. /// Used when pattern is '*' /// </summary> class AllLoggerNameMatcher : LoggerNameMatcher { protected override string MatchMode => "All"; public static readonly AllLoggerNameMatcher Instance = new AllLoggerNameMatcher(); private AllLoggerNameMatcher() : base("*", null) { } public override bool NameMatches(string loggerName) { return true; } } /// <summary> /// Defines a <see cref="LoggerNameMatcher"/> that matches with a case-sensitive Equals /// Used when pattern is a string without wildcards '?' '*' /// </summary> class EqualsLoggerNameMatcher : LoggerNameMatcher { protected override string MatchMode => "Equals"; public EqualsLoggerNameMatcher(string pattern) : base(pattern, pattern) { } public override bool NameMatches(string loggerName) { if (loggerName is null) return _matchingArgument is null; return loggerName.Equals(_matchingArgument, StringComparison.Ordinal); } } /// <summary> /// Defines a <see cref="LoggerNameMatcher"/> that matches with a case-sensitive StartsWith /// Used when pattern is a string like "*foobar" /// </summary> class StartsWithLoggerNameMatcher : LoggerNameMatcher { protected override string MatchMode => "StartsWith"; public StartsWithLoggerNameMatcher(string pattern) : base(pattern, pattern.Substring(0, pattern.Length - 1)) { } public override bool NameMatches(string loggerName) { if (loggerName is null) return _matchingArgument is null; return loggerName.StartsWith(_matchingArgument, StringComparison.Ordinal); } } /// <summary> /// Defines a <see cref="LoggerNameMatcher"/> that matches with a case-sensitive EndsWith /// Used when pattern is a string like "foobar*" /// </summary> class EndsWithLoggerNameMatcher : LoggerNameMatcher { protected override string MatchMode => "EndsWith"; public EndsWithLoggerNameMatcher(string pattern) : base(pattern, pattern.Substring(1)) { } public override bool NameMatches(string loggerName) { if (loggerName is null) return _matchingArgument is null; return loggerName.EndsWith(_matchingArgument, StringComparison.Ordinal); } } /// <summary> /// Defines a <see cref="LoggerNameMatcher"/> that matches with a case-sensitive Contains /// Used when pattern is a string like "*foobar*" /// </summary> class ContainsLoggerNameMatcher : LoggerNameMatcher { protected override string MatchMode => "Contains"; public ContainsLoggerNameMatcher(string pattern) : base(pattern, pattern.Substring(1, pattern.Length - 2)) { } public override bool NameMatches(string loggerName) { if (loggerName is null) return _matchingArgument is null; return loggerName.IndexOf(_matchingArgument, StringComparison.Ordinal) >= 0; } } /// <summary> /// Defines a <see cref="LoggerNameMatcher"/> that matches with a complex wildcards combinations: /// <list type="bullet"> /// <item>'*' means zero or more occurrences of any character</item> /// <item>'?' means exactly one occurrence of any character</item> /// </list> /// used when pattern is a string containing any number of '?' or '*' in any position /// i.e. "*Server[*].Connection[?]" /// </summary> class MultiplePatternLoggerNameMatcher : LoggerNameMatcher { protected override string MatchMode => "MultiplePattern"; private readonly Regex _regex; private static string ConvertToRegex(string wildcardsPattern) { return '^' + Regex.Escape(wildcardsPattern) .Replace("\\*", ".*") .Replace("\\?", ".") + '$'; } public MultiplePatternLoggerNameMatcher(string pattern) : base(pattern, ConvertToRegex(pattern)) { _regex = new Regex(_matchingArgument, RegexOptions.CultureInvariant); } public override bool NameMatches(string loggerName) { if (loggerName is null) return false; return _regex.IsMatch(loggerName); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Layouts { using System; using System.Collections.Generic; using NLog.Layouts; using Xunit; public class XmlLayoutTests : NLogTestBase { [Fact] public void XmlLayoutRendering() { var xmlLayout = new XmlLayout() { Elements = { new XmlElement("date", "${longdate}"), new XmlElement("level", "${level}"), new XmlElement("message", "${message}"), }, IndentXml = true, IncludeEventProperties = true, }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" }; logEventInfo.Properties["nlogPropertyKey"] = "nlogPropertyValue"; Assert.Equal(string.Format(System.Globalization.CultureInfo.InvariantCulture, @"<logevent>{0}{1}<date>2010-01-01 12:34:56.0000</date>{0}{1}<level>Info</level>{0}{1}<message>hello, world</message>{0}{1}<property key=""nlogPropertyKey"">nlogPropertyValue</property>{0}</logevent>", Environment.NewLine, " "), xmlLayout.Render(logEventInfo)); } [Fact] public void XmlLayoutLog4j() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='debug'> <layout type='xmllayout' elementName='log4j:event' propertiesElementName='log4j:data' propertiesElementKeyAttribute='name' propertiesElementValueAttribute='value' includeAllProperties='true' includeMdc='true' includeMdlc='true' excludeProperties='BADPROPERTYKEY' > <attribute name='logger' layout='${logger}' includeEmptyValue='true' /> <attribute name='level' layout='${uppercase:${level}}' includeEmptyValue='true' /> <element name='log4j:message' value='${message}' /> <element name='log4j:throwable' value='${exception:format=tostring}' /> <element name='log4j:locationInfo'> <attribute name='class' layout='${callsite:methodName=false}' includeEmptyValue='true' /> </element> </layout> </target> </targets> <rules> <logger name='*' minlevel='debug' appendto='debug' /> </rules> </nlog>").LogFactory; ScopeContext.Clear(); ScopeContext.PushProperty("foo1", "bar1"); ScopeContext.PushProperty("foo2", "bar2"); ScopeContext.PushProperty("foo3", "bar3"); var logger = logFactory.GetLogger("hello"); var logEventInfo = LogEventInfo.Create(LogLevel.Debug, "A", null, null, "some message"); logEventInfo.Properties["nlogPropertyKey"] = "<nlog\r\nPropertyValue>"; logEventInfo.Properties["badPropertyKey"] = "NOT ME"; logger.Log(logEventInfo); var target = logFactory.Configuration.FindTargetByName<NLog.Targets.DebugTarget>("debug"); Assert.Equal(@"<log4j:event logger=""A"" level=""DEBUG""><log4j:message>some message</log4j:message><log4j:locationInfo class=""NLog.UnitTests.Layouts.XmlLayoutTests""/><log4j:data name=""foo1"" value=""bar1""/><log4j:data name=""foo2"" value=""bar2""/><log4j:data name=""foo3"" value=""bar3""/><log4j:data name=""nlogPropertyKey"" value=""&lt;nlog&#13;&#10;PropertyValue&gt;""/></log4j:event>", target.LastMessage); } [Fact] public void XmlLayout_EncodeValue_RenderXmlMessage() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}"), }, }; var logEventInfo = new LogEventInfo { Message = @"<hello planet=""earth""/>" }; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message>&lt;hello planet=&quot;earth&quot;/&gt;</message></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_SkipEncodeValue_RenderXmlMessage() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") { Encode = false } }, }; var logEventInfo = new LogEventInfo { Message = @"<hello planet=""earth""/>" }; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message><hello planet=""earth""/></message></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_IncludeEmptyValue_RenderEmptyValue() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") { IncludeEmptyValue = true }, }, IncludeEventProperties = true, IncludeEmptyValue = true, }; var logEventInfo = new LogEventInfo { Message = "" }; logEventInfo.Properties["nlogPropertyKey"] = null; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message></message><property key=""nlogPropertyKey"">null</property></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_NoIndent_RendersOneLine() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("level", "${level}"), new XmlElement("message", "${message}"), }, IndentXml = false, IncludeEventProperties = true, }; var logEventInfo = new LogEventInfo { Message = "message 1", Level = LogLevel.Debug }; logEventInfo.Properties["prop1"] = "a"; logEventInfo.Properties["prop2"] = "b"; logEventInfo.Properties["prop3"] = "c"; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><level>Debug</level><message>message 1</message><property key=""prop1"">a</property><property key=""prop2"">b</property><property key=""prop3"">c</property></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_ExcludeProperties_RenderNotProperty() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}"), }, IncludeEventProperties = true, ExcludeProperties = new HashSet<string> { "prop2" } }; var logEventInfo = new LogEventInfo { Message = "message 1" }; logEventInfo.Properties["prop1"] = "a"; logEventInfo.Properties["prop2"] = "b"; logEventInfo.Properties["prop3"] = "c"; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message>message 1</message><property key=""prop1"">a</property><property key=""prop3"">c</property></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_OnlyLogEventProperties_RenderRootCorrect() { // Arrange var xmlLayout = new XmlLayout() { IncludeEventProperties = true, }; var logEventInfo = new LogEventInfo { Message = "message 1" }; logEventInfo.Properties["prop1"] = "a"; logEventInfo.Properties["prop2"] = "b"; logEventInfo.Properties["prop3"] = "c"; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><property key=""prop1"">a</property><property key=""prop2"">b</property><property key=""prop3"">c</property></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_InvalidXmlPropertyName_RenderNameCorrect() { // Arrange var xmlLayout = new XmlLayout() { IncludeEventProperties = true, PropertiesElementName = "{0}", PropertiesElementKeyAttribute = "", }; var logEventInfo = new LogEventInfo { Message = "message 1" }; logEventInfo.Properties["1prop"] = "a"; logEventInfo.Properties["_2prop"] = "b"; logEventInfo.Properties[" 3prop"] = "c"; logEventInfo.Properties["_4 prop"] = "d"; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><_1prop>a</_1prop><_2prop>b</_2prop><_3prop>c</_3prop><_4_prop>d</_4_prop></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_PropertiesAttributeNames_RenderPropertyName() { // Arrange var xmlLayout = new XmlLayout() { IncludeEventProperties = true, PropertiesElementName = "p", PropertiesElementKeyAttribute = "k", PropertiesElementValueAttribute = "v", }; var logEventInfo = new LogEventInfo { Message = "message 1" }; logEventInfo.Properties["prop1"] = "a"; logEventInfo.Properties["prop2"] = "b"; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><p k=""prop1"" v=""a""/><p k=""prop2"" v=""b""/></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_PropertiesElementNameFormat_RenderPropertyName() { // Arrange var xmlLayout = new XmlLayout() { IncludeEventProperties = true, PropertiesElementName = "{0}", PropertiesElementKeyAttribute = "", PropertiesElementValueAttribute = "v", }; var logEventInfo = new LogEventInfo { Message = "message 1" }; logEventInfo.Properties["prop1"] = "a"; logEventInfo.Properties["prop2"] = "b"; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><prop1 v=""a""/><prop2 v=""b""/></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_DoubleNestedElements_RendersAllElements() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") { Elements = { new XmlElement("level", "${level}") }, IncludeEventProperties = true, } }, }; var logEventInfo = new LogEventInfo { Level = LogLevel.Debug, Message = "message 1" }; logEventInfo.Properties["prop1"] = "a"; logEventInfo.Properties["prop2"] = "b"; // Act var result = xmlLayout.Render(logEventInfo); // Assert string expected = @"<logevent><message>message 1<level>Debug</level><property key=""prop1"">a</property><property key=""prop2"">b</property></message></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_PropertiesElementNameDefault_Properties_RenderPropertyDictionary() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, IncludeEventProperties = true, }; var logEventInfo = new LogEventInfo { Message = "Monster massage" }; logEventInfo.Properties["nlogPropertyKey"] = new Dictionary<string, object> { { "Hello", "World" } }; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message>Monster massage</message><property key=""nlogPropertyKey""><property key=""Hello"">World</property></property></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_PropertiesElementNameFormat_RenderPropertyDictionary() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, PropertiesElementName = "{0}", PropertiesElementKeyAttribute = "", IncludeEventProperties = true, }; var logEventInfo = new LogEventInfo { Message = "Monster massage" }; logEventInfo.Properties["nlogPropertyKey"] = new Dictionary<string, object> { { "Hello", "World" } }; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message>Monster massage</message><nlogPropertyKey><Hello>World</Hello></nlogPropertyKey></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_PropertiesElementNameDefault_Properties_RenderPropertyList() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, IncludeEventProperties = true, }; var logEventInfo = new LogEventInfo { Message = "Monster massage" }; logEventInfo.Properties["nlogPropertyKey"] = new [] { "Hello", "World" }; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message>Monster massage</message><property key=""nlogPropertyKey""><item>Hello</item><item>World</item></property></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_PropertiesElementNameFormat_RenderPropertyList() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, PropertiesElementName = "{0}", PropertiesElementKeyAttribute = "", IncludeEventProperties = true, PropertiesCollectionItemName = "node", PropertiesElementValueAttribute = "value", }; var logEventInfo = new LogEventInfo { Message = "Monster massage" }; logEventInfo.Properties["nlogPropertyKey"] = new[] { "Hello", "World" }; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message>Monster massage</message><nlogPropertyKey><node value=""Hello""/><node value=""World""/></nlogPropertyKey></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_PropertiesElementNameDefault_Properties_RenderPropertyObject() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, IncludeEventProperties = true, }; var guid = Guid.NewGuid(); var logEventInfo = new LogEventInfo { Message = "Monster massage" }; logEventInfo.Properties["nlogPropertyKey"] = new { Id = guid, Name = "<NAME>", Elements = new[] { "Earth", "Wind", "Fire" } }; // Act var result = xmlLayout.Render(logEventInfo); // Assert string expected = @"<logevent><message>Monster massage</message><property key=""nlogPropertyKey""><property key=""Id"">" + guid.ToString() + @"</property><property key=""Name"">Hello World</property><property key=""Elements""><item>Earth</item><item>Wind</item><item>Fire</item></property></property></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_PropertiesElementNameFormat_RenderPropertyObject() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, PropertiesElementName = "{0}", PropertiesElementKeyAttribute = "", IncludeEventProperties = true, }; var guid = Guid.NewGuid(); var logEventInfo = new LogEventInfo { Message = "Monster massage" }; logEventInfo.Properties["nlogPropertyKey"] = new { Id = guid, Name = "<NAME>", Elements = new[] { "Earth", "Wind", "Fire" } }; // Act var result = xmlLayout.Render(logEventInfo); // Assert string expected = @"<logevent><message>Monster massage</message><nlogPropertyKey><Id>" + guid.ToString() + @"</Id><Name>Hello World</Name><Elements><item>Earth</item><item>Wind</item><item>Fire</item></Elements></nlogPropertyKey></logevent>"; Assert.Equal(expected, result); } #if !NET35 && !NET40 [Fact] public void XmlLayout_PropertiesElementNameDefault_Properties_RenderPropertyExpando() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, IncludeEventProperties = true, }; dynamic object1 = new System.Dynamic.ExpandoObject(); object1.Id = 123; object1.Name = "<NAME>"; var logEventInfo = new LogEventInfo { Message = "Monster massage" }; logEventInfo.Properties["nlogPropertyKey"] = object1; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message>Monster massage</message><property key=""nlogPropertyKey""><property key=""Id"">123</property><property key=""Name"">test name</property></property></logevent>"; Assert.Equal(expected, result); } #endif [Fact] public void XmlLayout_PropertiesElementNameFormat_RenderInfiniteLoop() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, PropertiesElementName = "{0}", PropertiesElementKeyAttribute = "", IncludeEventProperties = true, MaxRecursionLimit = 10, }; var logEventInfo = new LogEventInfo { Message = "Monster massage" }; logEventInfo.Properties["nlogPropertyKey"] = new TestList(); // Act var result = xmlLayout.Render(logEventInfo); // Assert var cnt = System.Text.RegularExpressions.Regex.Matches(result, "<item>alpha</item><item>bravo</item>").Count; Assert.Equal(10, cnt); } [Fact] public void XmlLayout_PropertiesElementNameFormat_RenderTrickyDictionary() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, PropertiesElementName = "{0}", PropertiesElementKeyAttribute = "", IncludeEventProperties = true, MaxRecursionLimit = 10, }; var logEventInfo = new LogEventInfo { Message = "Monster massage" }; IDictionary<object, object> testDictionary = new Internal.TrickyTestDictionary(); testDictionary.Add("key1", 13); testDictionary.Add("key 2", 1.3m); logEventInfo.Properties["nlogPropertyKey"] = testDictionary; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message>Monster massage</message><nlogPropertyKey><key1>13</key1><key_2>1.3</key_2></nlogPropertyKey></logevent>"; Assert.Equal(expected, result); } private class TestList : IEnumerable<System.Collections.IEnumerable> { static List<int> _list1 = new List<int> { 17, 3 }; static List<string> _list2 = new List<string> { "alpha", "bravo" }; public IEnumerator<System.Collections.IEnumerable> GetEnumerator() { yield return _list1; yield return _list2; yield return new TestList(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public override bool Equals(object obj) { throw new Exception("object.Equals should never be called"); } public override int GetHashCode() { throw new Exception("GetHashCode should never be called"); } } } } <file_sep>--- name: Bug report about: Report any issues found in NLog functionality or source-code to help us improve --- Hi! Thanks for reporting this bug! Please keep / fill in the relevant info from this template so that we can help you as best as possible. **NLog version**: (e.g. 4.4.13) **Platform**: .Net 3.5 / .Net 4.0 / .Net 4.5 / Mono 4 / Xamarin Android / Xamarin iOS / .NET Core / .NET5 / .NET6 **Current NLog config** (xml or C#, if relevant) ```xml <nlog> <targets> </targets> <rules> </rules> </nlog> ``` - What is the current result? - What is the expected result? - Did you checked the [Internal log](https://github.com/NLog/NLog/wiki/Internal-Logging)? - Please post full exception details (message, stacktrace, inner exceptions) - Are there any workarounds? yes/no - Is there a version in which it did work? - Can you help us by writing an unit test? <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Attributes { using System; using System.ComponentModel; using System.Globalization; /// <summary> /// Support <see cref="NLog.LogLevel"/> implementation of <see cref="IConvertible"/> /// </summary> public class LogLevelTypeConverter : TypeConverter { /// <inheritdoc/> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string) || IsNumericType(sourceType) || base.CanConvertFrom(context, sourceType); } /// <inheritdoc/> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { var valueType = value?.GetType(); if (typeof(string).Equals(valueType)) return LogLevel.FromString(value?.ToString()); else if (IsNumericType(valueType)) return LogLevel.FromOrdinal(Convert.ToInt32(value)); else return base.ConvertFrom(context, culture, value); } /// <inheritdoc/> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(string) || IsNumericType(destinationType) || base.CanConvertTo(context, destinationType); } /// <inheritdoc/> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value is LogLevel logLevel) { if (destinationType == typeof(string)) return logLevel.ToString(); else if (IsNumericType(destinationType)) return Convert.ChangeType(logLevel.Ordinal, destinationType, culture); } return base.ConvertTo(context, culture, value, destinationType); } private static bool IsNumericType(Type sourceType) { if (typeof(int).Equals(sourceType)) return true; if (typeof(uint).Equals(sourceType)) return true; if (typeof(long).Equals(sourceType)) return true; if (typeof(ulong).Equals(sourceType)) return true; if (typeof(short).Equals(sourceType)) return true; if (typeof(ushort).Equals(sourceType)) return true; return false; } } }<file_sep>Issue labeling ==== When a new issue is submitted at GitHub, it will be labeled. We use the following guideline: * preferably, each issue has a label, although this isn't a goal. The goals is to get a nice overview where we stand & if there a lot of issues. * Bug-reports, even non-confirmed bugs are labels under `bug`. * Functional changes are labeled under 'feature'. Even small `features`. * Non-functional changes are labeled under `enhancement`. * Issue's that have missing info are labeled under `incomplete info`. If we don't get a response within 14 days, I will **close** the issue. * answered questions are **closed** after 3 days. * Issues which have PR's are labeled under `almost ready` * The rest of the labels should be straightforward ;) <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Text; using System.Threading; internal class StringBuilderPool { private StringBuilder _fastPool; private readonly StringBuilder[] _slowPool; private readonly int _maxBuilderCapacity; /// <summary> /// Constructor /// </summary> /// <param name="poolCapacity">Max number of items</param> /// <param name="initialBuilderCapacity">Initial StringBuilder Size</param> /// <param name="maxBuilderCapacity">Max StringBuilder Size</param> public StringBuilderPool(int poolCapacity, int initialBuilderCapacity = 1024, int maxBuilderCapacity = 512 * 1024) { _fastPool = new StringBuilder(10 * initialBuilderCapacity); _slowPool = new StringBuilder[poolCapacity]; for (int i = 0; i < _slowPool.Length; ++i) { _slowPool[i] = new StringBuilder(initialBuilderCapacity); } _maxBuilderCapacity = maxBuilderCapacity; } /// <summary> /// Takes StringBuilder from pool /// </summary> /// <returns>Allow return to pool</returns> public ItemHolder Acquire() { StringBuilder item = _fastPool; if (item is null || item != Interlocked.CompareExchange(ref _fastPool, null, item)) { for (int i = 0; i < _slowPool.Length; i++) { item = _slowPool[i]; if (item != null && item == Interlocked.CompareExchange(ref _slowPool[i], null, item)) { return new ItemHolder(item, this, i); } } return new ItemHolder(new StringBuilder(), null, 0); } else { return new ItemHolder(item, this, -1); } } /// <summary> /// Releases StringBuilder back to pool at its right place /// </summary> private void Release(StringBuilder stringBuilder, int poolIndex) { if (stringBuilder.Length > _maxBuilderCapacity) { // Avoid high memory usage by not keeping huge StringBuilders alive (Except one StringBuilder) int maxBuilderCapacity = poolIndex == -1 ? _maxBuilderCapacity * 10 : _maxBuilderCapacity; if (stringBuilder.Length > maxBuilderCapacity) { stringBuilder.Remove(0, stringBuilder.Length - 1); // Attempt soft clear that skips re-allocation if (stringBuilder.Capacity > maxBuilderCapacity) { stringBuilder = new StringBuilder(maxBuilderCapacity / 2); } } } stringBuilder.ClearBuilder(); if (poolIndex == -1) { _fastPool = stringBuilder; } else { _slowPool[poolIndex] = stringBuilder; } } /// <summary> /// Keeps track of acquired pool item /// </summary> public struct ItemHolder : IDisposable { public readonly StringBuilder Item; readonly StringBuilderPool _owner; readonly int _poolIndex; public ItemHolder(StringBuilder stringBuilder, StringBuilderPool owner, int poolIndex) { Item = stringBuilder; _owner = owner; _poolIndex = poolIndex; } /// <summary> /// Releases pool item back into pool /// </summary> public void Dispose() { _owner?.Release(Item, _poolIndex); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LayoutRenderers { using System; using System.IO; using System.Linq; using NLog.Config; using NLog.Layouts; using NLog.Targets; using Xunit; public class VariableLayoutRendererTests : NLogTestBase { [Fact] public void Var_from_xml() { // Arrange var logFactory = CreateConfigFromXml(); var logger = logFactory.GetLogger("A"); // Act logger.Debug("msg"); // Assert logFactory.AssertDebugLastMessage("msg and admin=realgoodpassword"); Assert.Equal(2, logFactory.Configuration.Variables.Count); Assert.Equal(2, logFactory.Configuration.Variables.Keys.Count); Assert.Equal(2, logFactory.Configuration.Variables.Values.Count); Assert.True(logFactory.Configuration.Variables.ContainsKey("uSeR")); Assert.True(logFactory.Configuration.Variables.TryGetValue("passWORD", out var _)); } [Fact] public void Var_from_xml_and_edit() { // Arrange var logFactory = CreateConfigFromXml(); var logger = logFactory.GetLogger("A"); // Act logFactory.Configuration.Variables["password"] = "123"; logger.Debug("msg"); // Assert logFactory.AssertDebugLastMessage("msg and admin=123"); } [Fact] public void Var_from_xml_and_clear() { // Arrange var logFactory = CreateConfigFromXml(); var logger = logFactory.GetLogger("A"); // Act logFactory.Configuration.Variables.Clear(); logger.Debug("msg"); // Assert logFactory.AssertDebugLastMessage("msg and ="); } [Fact] public void Var_with_layout_renderers() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <variable name='user' value='logger=${logger}' /> <variable name='password' value='<PASSWORD>' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; logFactory.Configuration.Variables["password"] = "123"; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); var lastMessage = GetDebugLastMessage("debug", logFactory); Assert.Equal("msg and logger=A=123", lastMessage); } [Theory] [InlineData("myJson", "${MyJson}")] [InlineData("myJson", "${var:myJSON}")] public void Var_with_layout(string variableName, string layoutStyle) { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml($@" <nlog throwExceptions='true'> <variable name='{variableName}' > <layout type='JsonLayout'> <attribute name='short date' layout='${{level}}' /> <attribute name='message' layout='${{message}}' /> </layout> </variable> <targets> <target name='debug' type='Debug' layout='{layoutStyle}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); var lastMessage = GetDebugLastMessage("debug", logFactory); Assert.Equal("{ \"short date\": \"Debug\", \"message\": \"msg\" }", lastMessage); } [Fact] public void Var_Layout_Target_CallSite() { var logFactory = new LogFactory().Setup() .LoadConfigurationFromXml(@"<nlog throwExceptions='true'> <variable name='myvar' value='${callsite}' /> <targets> <target name='debug' type='Debug' layout='${var:myvar}' /> </targets> <rules> <logger name='*' minLevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; // Act logFactory.GetCurrentClassLogger().Info("Hello"); // Assert logFactory.AssertDebugLastMessage(GetType().ToString() + "." + nameof(Var_Layout_Target_CallSite)); } [Fact] public void Var_with_other_var() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <variable name='user' value='${var:password}=' /> <variable name='password' value='<PASSWORD>' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; logFactory.Configuration.Variables["password"] = "123"; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); logFactory.AssertDebugLastMessage("msg and 123==123"); } [Fact] public void Var_from_api() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; logFactory.Configuration.Variables["user"] = "admin"; logFactory.Configuration.Variables["password"] = "123"; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); logFactory.AssertDebugLastMessage("msg and admin=123"); } [Fact] public void Var_default() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <variable name='user' value='admin' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password:default=unknown}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); logFactory.AssertDebugLastMessage("msg and admin=unknown"); } [Fact] public void Var_default_after_clear() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <variable name='user' value='admin' /> <variable name='password' value='<PASSWORD>' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password:default=unknown}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logFactory.Configuration.Variables.Remove("password"); logger.Debug("msg"); logFactory.AssertDebugLastMessage("msg and admin=unknown"); } [Fact] public void Var_default_after_set_null() { // Arrange var logFactory = CreateConfigFromXml(); var logger = logFactory.GetLogger("A"); // Act logFactory.Configuration.Variables["password"] = null; logger.Debug("msg"); // Assert logFactory.AssertDebugLastMessage("msg and admin="); } [Fact] public void Var_default_after_set_emptyString() { // Arrange var logFactory = CreateConfigFromXml(); var logger = logFactory.GetLogger("A"); // Act logFactory.Configuration.Variables["password"] = ""; logger.Debug("msg"); // Assert logFactory.AssertDebugLastMessage("msg and admin="); } [Fact] public void Var_default_after_xml_emptyString() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <variable name='user' value='admin' /> <variable name='password' value='' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); logFactory.AssertDebugLastMessage("msg and admin="); } [Fact] public void null_should_be_ok() { Layout l = "${var:var1}"; var config = new LoggingConfiguration(); config.Variables["var1"] = null; l.Initialize(config); var result = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("", result); } [Fact] public void null_should_not_use_default() { Layout l = "${var:var1:default=x}"; var config = new LoggingConfiguration(); config.Variables["var1"] = null; l.Initialize(config); var result = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("", result); } [Fact] public void notset_should_use_default() { Layout l = "${var:var1:default=x}"; var config = new LoggingConfiguration(); l.Initialize(config); var result = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("x", result); } [Fact] public void test_with_mockLogManager() { var logFactory = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(new DebugTarget { Name = "Debug", Layout = "${message}|${var:var1:default=x}" }); builder.Configuration.Variables["var1"] = "my-mocking-manager"; }).LogFactory; var logger = logFactory.GetLogger("A"); logger.Debug("msg"); logFactory.AssertDebugLastMessage("msg|my-mocking-manager"); } private static LogFactory CreateConfigFromXml() { return new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <variable name='user' value='admin' /> <variable name='password' value='<PASSWORD>' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System.IO; using System.Text; using NLog.Config; using NLog.Internal; /// <summary> /// The call site (class name, method name and source information). /// </summary> [LayoutRenderer("callsite")] [ThreadAgnostic] public class CallSiteLayoutRenderer : LayoutRenderer, IUsesStackTrace { /// <summary> /// Gets or sets a value indicating whether to render the class name. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool ClassName { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether to render the include the namespace with <see cref="ClassName"/>. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeNamespace { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether to render the method name. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool MethodName { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether the method name will be cleaned up if it is detected as an anonymous delegate. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool CleanNamesOfAnonymousDelegates { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether the method and class names will be cleaned up if it is detected as an async continuation /// (everything after an await-statement inside of an async method). /// </summary> /// <docgen category='Layout Options' order='10' /> public bool CleanNamesOfAsyncContinuations { get; set; } = true; /// <summary> /// Gets or sets the number of frames to skip. /// </summary> /// <docgen category='Layout Options' order='10' /> public int SkipFrames { get; set; } /// <summary> /// Gets or sets a value indicating whether to render the source file name and line number. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool FileName { get; set; } /// <summary> /// Gets or sets a value indicating whether to include source file path. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeSourcePath { get; set; } = true; /// <summary> /// Logger should capture StackTrace, if it was not provided manually /// </summary> /// <docgen category='Layout Options' order='10' /> public bool CaptureStackTrace { get; set; } = true; /// <inheritdoc/> StackTraceUsage IUsesStackTrace.StackTraceUsage { get { return StackTraceUsageUtils.GetStackTraceUsage( FileName, SkipFrames, CaptureStackTrace) | (ClassName ? StackTraceUsage.WithCallSiteClassName : StackTraceUsage.None); } } /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (logEvent.CallSiteInformation is null) return; if (ClassName || MethodName) { var method = logEvent.CallSiteInformation.GetCallerStackFrameMethod(SkipFrames); if (ClassName) { string className = logEvent.CallSiteInformation.GetCallerClassName(method, IncludeNamespace, CleanNamesOfAsyncContinuations, CleanNamesOfAnonymousDelegates); builder.Append(string.IsNullOrEmpty(className) ? "<no type>" : className); } if (MethodName) { string methodName = logEvent.CallSiteInformation.GetCallerMethodName(method, false, CleanNamesOfAsyncContinuations, CleanNamesOfAnonymousDelegates); if (ClassName) { builder.Append('.'); } builder.Append(string.IsNullOrEmpty(methodName) ? "<no method>" : methodName); } } if (FileName) { string fileName = logEvent.CallSiteInformation.GetCallerFilePath(SkipFrames); if (!string.IsNullOrEmpty(fileName)) { int lineNumber = logEvent.CallSiteInformation.GetCallerLineNumber(SkipFrames); AppendFileName(builder, fileName, lineNumber); } } } private void AppendFileName(StringBuilder builder, string fileName, int lineNumber) { builder.Append('('); if (IncludeSourcePath) { builder.Append(fileName); } else { builder.Append(Path.GetFileName(fileName)); } builder.Append(':'); builder.AppendInvariant(lineNumber); builder.Append(')'); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Conditions { using System; using System.Collections.Generic; using System.Globalization; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; /// <summary> /// Condition parser. Turns a string representation of condition expression /// into an expression tree. /// </summary> public class ConditionParser { private readonly ConditionTokenizer _tokenizer; private readonly ConfigurationItemFactory _configurationItemFactory; /// <summary> /// Initializes a new instance of the <see cref="ConditionParser"/> class. /// </summary> /// <param name="stringReader">The string reader.</param> /// <param name="configurationItemFactory">Instance of <see cref="ConfigurationItemFactory"/> used to resolve references to condition methods and layout renderers.</param> private ConditionParser(SimpleStringReader stringReader, ConfigurationItemFactory configurationItemFactory) { _configurationItemFactory = configurationItemFactory; _tokenizer = new ConditionTokenizer(stringReader); } /// <summary> /// Parses the specified condition string and turns it into /// <see cref="ConditionExpression"/> tree. /// </summary> /// <param name="expressionText">The expression to be parsed.</param> /// <returns>The root of the expression syntax tree which can be used to get the value of the condition in a specified context.</returns> public static ConditionExpression ParseExpression(string expressionText) { return ParseExpression(expressionText, ConfigurationItemFactory.Default); } /// <summary> /// Parses the specified condition string and turns it into /// <see cref="ConditionExpression"/> tree. /// </summary> /// <param name="expressionText">The expression to be parsed.</param> /// <param name="configurationItemFactories">Instance of <see cref="ConfigurationItemFactory"/> used to resolve references to condition methods and layout renderers.</param> /// <returns>The root of the expression syntax tree which can be used to get the value of the condition in a specified context.</returns> public static ConditionExpression ParseExpression(string expressionText, ConfigurationItemFactory configurationItemFactories) { if (expressionText is null) { return null; } var parser = new ConditionParser(new SimpleStringReader(expressionText), configurationItemFactories); ConditionExpression expression = parser.ParseExpression(); if (!parser._tokenizer.IsEOF()) { throw new ConditionParseException($"Unexpected token: {parser._tokenizer.TokenValue}"); } return expression; } /// <summary> /// Parses the specified condition string and turns it into /// <see cref="ConditionExpression"/> tree. /// </summary> /// <param name="stringReader">The string reader.</param> /// <param name="configurationItemFactories">Instance of <see cref="ConfigurationItemFactory"/> used to resolve references to condition methods and layout renderers.</param> /// <returns> /// The root of the expression syntax tree which can be used to get the value of the condition in a specified context. /// </returns> internal static ConditionExpression ParseExpression(SimpleStringReader stringReader, ConfigurationItemFactory configurationItemFactories) { var parser = new ConditionParser(stringReader, configurationItemFactories); ConditionExpression expression = parser.ParseExpression(); return expression; } private ConditionMethodExpression ParseMethodPredicate(string functionName) { var inputParameters = new List<ConditionExpression>(); while (!_tokenizer.IsEOF() && _tokenizer.TokenType != ConditionTokenType.RightParen) { inputParameters.Add(ParseExpression()); if (_tokenizer.TokenType != ConditionTokenType.Comma) { break; } _tokenizer.GetNextToken(); } _tokenizer.Expect(ConditionTokenType.RightParen); try { return CreateMethodExpression(functionName, inputParameters); } catch (Exception exception) { InternalLogger.Warn(exception, "Failed to resolve condition method: '{0}'", functionName); if (exception.MustBeRethrownImmediately()) { throw; } throw new ConditionParseException($"Cannot resolve function '{functionName}'", exception); } } private ConditionMethodExpression CreateMethodExpression(string functionName, List<ConditionExpression> inputParameters) { // Attempt to lookup functionName that can handle the provided number of input-parameters if (inputParameters.Count == 0) { Func<LogEventInfo, object> method = _configurationItemFactory.ConditionMethodFactory.TryCreateInstanceWithNoParameters(functionName); if (method != null) return ConditionMethodExpression.CreateMethodNoParameters(functionName, method); } else if (inputParameters.Count == 1) { Func<LogEventInfo, object, object> method = _configurationItemFactory.ConditionMethodFactory.TryCreateInstanceWithOneParameter(functionName); if (method != null) return ConditionMethodExpression.CreateMethodOneParameter(functionName, method, inputParameters); } else if (inputParameters.Count == 2) { Func<LogEventInfo, object, object, object> method = _configurationItemFactory.ConditionMethodFactory.TryCreateInstanceWithTwoParameters(functionName); if (method != null) return ConditionMethodExpression.CreateMethodTwoParameters(functionName, method, inputParameters); } else if (inputParameters.Count == 3) { Func<LogEventInfo, object, object, object, object> method = _configurationItemFactory.ConditionMethodFactory.TryCreateInstanceWithThreeParameters(functionName); if (method != null) return ConditionMethodExpression.CreateMethodThreeParameters(functionName, method, inputParameters); } Func<object[], object> manyParameterMethod = _configurationItemFactory.ConditionMethodFactory.TryCreateInstanceWithManyParameters(functionName, out var manyParameterMinCount, out var manyParameterMaxCount, out var manyParameterWithLogEvent); if (manyParameterMethod is null) throw new ConditionParseException($"Unknown condition method '{functionName}'"); if (manyParameterMinCount > inputParameters.Count) throw new ConditionParseException($"Condition method '{functionName}' requires minimum {manyParameterMinCount} parameters, but passed {inputParameters.Count}."); if (manyParameterMaxCount < inputParameters.Count) throw new ConditionParseException($"Condition method '{functionName}' requires maximum {manyParameterMaxCount} parameters, but passed {inputParameters.Count}."); return ConditionMethodExpression.CreateMethodManyParameters(functionName, manyParameterMethod, inputParameters, manyParameterWithLogEvent); } private ConditionExpression ParseLiteralExpression() { if (_tokenizer.IsToken(ConditionTokenType.LeftParen)) { _tokenizer.GetNextToken(); ConditionExpression e = ParseExpression(); _tokenizer.Expect(ConditionTokenType.RightParen); return e; } if (_tokenizer.IsToken(ConditionTokenType.Minus)) { _tokenizer.GetNextToken(); if (!_tokenizer.IsNumber()) { throw new ConditionParseException($"Number expected, got {_tokenizer.TokenType}"); } return ParseNumber(true); } if (_tokenizer.IsNumber()) { return ParseNumber(false); } if (_tokenizer.TokenType == ConditionTokenType.String) { var simpleLayout = new SimpleLayout(_tokenizer.StringTokenValue, _configurationItemFactory); _tokenizer.GetNextToken(); if (simpleLayout.IsFixedText) return new ConditionLiteralExpression(simpleLayout.FixedText); else return new ConditionLayoutExpression(simpleLayout); } if (_tokenizer.TokenType == ConditionTokenType.Keyword) { string keyword = _tokenizer.EatKeyword(); if (TryPlainKeywordToExpression(keyword, out var expression)) { return expression; } if (_tokenizer.TokenType == ConditionTokenType.LeftParen) { _tokenizer.GetNextToken(); var conditionMethodExpression = ParseMethodPredicate(keyword); return conditionMethodExpression; } } throw new ConditionParseException("Unexpected token: " + _tokenizer.TokenValue); } /// <summary> /// Try stringed keyword to <see cref="ConditionExpression"/> /// </summary> /// <param name="keyword"></param> /// <param name="expression"></param> /// <returns>success?</returns> private bool TryPlainKeywordToExpression(string keyword, out ConditionExpression expression) { if (string.Equals(keyword, "level", StringComparison.OrdinalIgnoreCase)) { expression = new ConditionLevelExpression(); return true; } if (string.Equals(keyword, "logger", StringComparison.OrdinalIgnoreCase)) { expression = new ConditionLoggerNameExpression(); return true; } if (string.Equals(keyword, "message", StringComparison.OrdinalIgnoreCase)) { expression = new ConditionMessageExpression(); return true; } if (string.Equals(keyword, "exception", StringComparison.OrdinalIgnoreCase)) { expression = new ConditionExceptionExpression(); return true; } if (string.Equals(keyword, "loglevel", StringComparison.OrdinalIgnoreCase)) { _tokenizer.Expect(ConditionTokenType.Dot); expression = new ConditionLiteralExpression(LogLevel.FromString(_tokenizer.EatKeyword())); return true; } if (string.Equals(keyword, "true", StringComparison.OrdinalIgnoreCase)) { expression = new ConditionLiteralExpression(ConditionExpression.BoxedTrue); return true; } if (string.Equals(keyword, "false", StringComparison.OrdinalIgnoreCase)) { expression = new ConditionLiteralExpression(ConditionExpression.BoxedFalse); return true; } if (string.Equals(keyword, "null", StringComparison.OrdinalIgnoreCase)) { expression = new ConditionLiteralExpression(null); return true; } expression = null; return false; } /// <summary> /// Parse number /// </summary> /// <param name="negative">negative number? minus should be parsed first.</param> /// <returns></returns> private ConditionExpression ParseNumber(bool negative) { string numberString = _tokenizer.TokenValue; _tokenizer.GetNextToken(); if (numberString.IndexOf('.') >= 0) { var d = double.Parse(numberString, CultureInfo.InvariantCulture); return new ConditionLiteralExpression(negative ? -d : d); } var i = int.Parse(numberString, CultureInfo.InvariantCulture); return new ConditionLiteralExpression(negative ? -i : i); } private ConditionExpression ParseBooleanRelation() { ConditionExpression e = ParseLiteralExpression(); if (_tokenizer.IsToken(ConditionTokenType.EqualTo)) { _tokenizer.GetNextToken(); return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.Equal); } if (_tokenizer.IsToken(ConditionTokenType.NotEqual)) { _tokenizer.GetNextToken(); return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.NotEqual); } if (_tokenizer.IsToken(ConditionTokenType.LessThan)) { _tokenizer.GetNextToken(); return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.Less); } if (_tokenizer.IsToken(ConditionTokenType.GreaterThan)) { _tokenizer.GetNextToken(); return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.Greater); } if (_tokenizer.IsToken(ConditionTokenType.LessThanOrEqualTo)) { _tokenizer.GetNextToken(); return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.LessOrEqual); } if (_tokenizer.IsToken(ConditionTokenType.GreaterThanOrEqualTo)) { _tokenizer.GetNextToken(); return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.GreaterOrEqual); } return e; } private ConditionExpression ParseBooleanPredicate() { if (_tokenizer.IsKeyword("not") || _tokenizer.IsToken(ConditionTokenType.Not)) { _tokenizer.GetNextToken(); return new ConditionNotExpression(ParseBooleanPredicate()); } return ParseBooleanRelation(); } private ConditionExpression ParseBooleanAnd() { ConditionExpression expression = ParseBooleanPredicate(); while (_tokenizer.IsKeyword("and") || _tokenizer.IsToken(ConditionTokenType.And)) { _tokenizer.GetNextToken(); expression = new ConditionAndExpression(expression, ParseBooleanPredicate()); } return expression; } private ConditionExpression ParseBooleanOr() { ConditionExpression expression = ParseBooleanAnd(); while (_tokenizer.IsKeyword("or") || _tokenizer.IsToken(ConditionTokenType.Or)) { _tokenizer.GetNextToken(); expression = new ConditionOrExpression(expression, ParseBooleanAnd()); } return expression; } private ConditionExpression ParseBooleanExpression() { return ParseBooleanOr(); } private ConditionExpression ParseExpression() { return ParseBooleanExpression(); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using JetBrains.Annotations; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; /// <summary> /// Represents logging target. /// </summary> [NLogConfigurationItem] public abstract class Target : ISupportsInitialize, IInternalLoggerContext, IDisposable { internal string _tostring; private Layout[] _allLayouts = ArrayHelper.Empty<Layout>(); /// <summary> Are all layouts in this target thread-agnostic, if so we don't precalculate the layouts </summary> private bool _allLayoutsAreThreadAgnostic; private bool _oneLayoutIsMutableUnsafe; private bool _scannedForLayouts; private Exception _initializeException; /// <summary> /// The Max StackTraceUsage of all the <see cref="Layout"/> in this Target /// </summary> internal StackTraceUsage StackTraceUsage { get; private set; } internal Exception InitializeException => _initializeException; /// <summary> /// Gets or sets the name of the target. /// </summary> /// <docgen category='General Options' order='1' /> public string Name { get => _name; set { _name = value; _tostring = null; } } private string _name; /// <summary> /// Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers /// Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit /// </summary> /// <docgen category='Performance Tuning Options' order='10' /> [Obsolete("No longer used, and always returns true. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool OptimizeBufferReuse { get => _optimizeBufferReuse ?? true; set => _optimizeBufferReuse = value ? true : (bool?)null; } private bool? _optimizeBufferReuse; /// <summary> /// NLog Layout are by default threadsafe, so multiple threads can be rendering logevents at the same time. /// This ensure high concurrency with no lock-congestion for the application-threads, especially when using <see cref="Wrappers.AsyncTargetWrapper"/> /// or AsyncTaskTarget. /// /// But if using custom <see cref="Layout" /> or <see cref="LayoutRenderers.LayoutRenderer"/> that are not /// threadsafe, then this option can enabled to protect against thread-concurrency-issues. Allowing one /// to update to NLog 5.0 without having to fix custom/external layout-dependencies. /// </summary> /// <docgen category='Performance Tuning Options' order='10' /> [Obsolete("Temporary workaround for broken Layout Renderers that are not threadsafe. Marked obsolete on NLog 5.0")] public bool LayoutWithLock { get => _layoutWithLock ?? false; set => _layoutWithLock = value; } internal bool? _layoutWithLock; /// <summary> /// Gets the object which can be used to synchronize asynchronous operations that must rely on the . /// </summary> protected object SyncRoot { get; } = new object(); /// <summary> /// Gets the logging configuration this target is part of. /// </summary> protected LoggingConfiguration LoggingConfiguration { get; private set; } LogFactory IInternalLoggerContext.LogFactory => LoggingConfiguration?.LogFactory; /// <summary> /// Gets a value indicating whether the target has been initialized. /// </summary> protected bool IsInitialized { get { if (_isInitialized) return true; // Initialization has completed // Lets wait for initialization to complete, and then check again lock (SyncRoot) { return _isInitialized; } } } private volatile bool _isInitialized; internal readonly ReusableBuilderCreator ReusableLayoutBuilder = new ReusableBuilderCreator(); private StringBuilderPool _precalculateStringBuilderPool; /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> void ISupportsInitialize.Initialize(LoggingConfiguration configuration) { lock (SyncRoot) { bool wasInitialized = _isInitialized; Initialize(configuration); if (wasInitialized && configuration != null) { FindAllLayouts(); } } } /// <summary> /// Closes this instance. /// </summary> void ISupportsInitialize.Close() { Close(); } /// <summary> /// Closes the target. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> public void Flush(AsyncContinuation asyncContinuation) { Guard.ThrowIfNull(asyncContinuation); asyncContinuation = AsyncHelpers.PreventMultipleCalls(asyncContinuation); lock (SyncRoot) { if (!IsInitialized) { // In case target was Closed asyncContinuation(null); return; } try { FlushAsync(asyncContinuation); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception)) throw; asyncContinuation(exception); } } } /// <summary> /// Calls the <see cref="Layout.Precalculate"/> on each volatile layout /// used by this target. /// This method won't prerender if all layouts in this target are thread-agnostic. /// </summary> /// <param name="logEvent"> /// The log event. /// </param> public void PrecalculateVolatileLayouts(LogEventInfo logEvent) { if (_allLayoutsAreThreadAgnostic && (!_oneLayoutIsMutableUnsafe || logEvent.IsLogEventMutableSafe())) { return; } if (!IsInitialized) return; if (_layoutWithLock == true) { PrecalculateVolatileLayoutsWithLock(logEvent); } else { PrecalculateVolatileLayoutsConcurrent(logEvent); } } private void PrecalculateVolatileLayoutsConcurrent(LogEventInfo logEvent) { if (_precalculateStringBuilderPool is null) { System.Threading.Interlocked.CompareExchange(ref _precalculateStringBuilderPool, new StringBuilderPool(Environment.ProcessorCount * 2), null); } using (var targetBuilder = _precalculateStringBuilderPool.Acquire()) { foreach (Layout layout in _allLayouts) { targetBuilder.Item.ClearBuilder(); layout.PrecalculateBuilder(logEvent, targetBuilder.Item); } } } private void PrecalculateVolatileLayoutsWithLock(LogEventInfo logEvent) { lock (SyncRoot) { using (var targetBuilder = ReusableLayoutBuilder.Allocate()) { foreach (Layout layout in _allLayouts) { targetBuilder.Result.ClearBuilder(); layout.PrecalculateBuilder(logEvent, targetBuilder.Result); } } } } /// <inheritdoc/> public override string ToString() { return _tostring ?? (_tostring = GenerateTargetToString(false)); } internal string GenerateTargetToString(bool targetWrapper, string targetName = null) { var targetAttribute = GetType().GetFirstCustomAttribute<TargetAttribute>(); string targetType = (targetAttribute?.Name ?? GetType().Name).Trim(); targetWrapper = targetWrapper || targetAttribute?.IsCompound == true || targetAttribute?.IsWrapper == true; if (!targetWrapper && targetType.IndexOf("Target", StringComparison.OrdinalIgnoreCase) < 0) { targetType += "Target"; } targetName = targetName ?? Name; if (string.IsNullOrEmpty(targetName)) return targetWrapper ? targetType : $"{targetType}([unnamed])"; else return $"{targetType}(Name={targetName})"; } /// <summary> /// Writes the log to the target. /// </summary> /// <param name="logEvent">Log event to write.</param> public void WriteAsyncLogEvent(AsyncLogEventInfo logEvent) { if (!IsInitialized) { lock (SyncRoot) { logEvent.Continuation(null); } return; } if (_initializeException != null) { lock (SyncRoot) { WriteFailedNotInitialized(logEvent, _initializeException); } return; } var wrappedContinuation = AsyncHelpers.PreventMultipleCalls(logEvent.Continuation); var wrappedLogEvent = logEvent.LogEvent.WithContinuation(wrappedContinuation); try { WriteAsyncThreadSafe(wrappedLogEvent); } catch (Exception ex) { if (ExceptionMustBeRethrown(ex)) throw; wrappedLogEvent.Continuation(ex); } } /// <summary> /// Writes the array of log events. /// </summary> /// <param name="logEvents">The log events.</param> public void WriteAsyncLogEvents(params AsyncLogEventInfo[] logEvents) { if (logEvents?.Length > 0) { WriteAsyncLogEvents((IList<AsyncLogEventInfo>)logEvents); } } /// <summary> /// Writes the array of log events. /// </summary> /// <param name="logEvents">The log events.</param> public void WriteAsyncLogEvents(IList<AsyncLogEventInfo> logEvents) { if (logEvents is null || logEvents.Count == 0) { return; } if (!IsInitialized) { lock (SyncRoot) { for (int i = 0; i < logEvents.Count; ++i) { logEvents[i].Continuation(null); } } return; } if (_initializeException != null) { lock (SyncRoot) { for (int i = 0; i < logEvents.Count; ++i) { WriteFailedNotInitialized(logEvents[i], _initializeException); } } return; } for (int i = 0; i < logEvents.Count; ++i) { logEvents[i] = logEvents[i].LogEvent.WithContinuation(AsyncHelpers.PreventMultipleCalls(logEvents[i].Continuation)); } try { WriteAsyncThreadSafe(logEvents); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception)) throw; // in case of synchronous failure, assume that nothing is running asynchronously for (int i = 0; i < logEvents.Count; ++i) { logEvents[i].Continuation(exception); } } } /// <summary> /// LogEvent is written to target, but target failed to successfully initialize /// </summary> protected virtual void WriteFailedNotInitialized(AsyncLogEventInfo logEvent, Exception initializeException) { var initializeFailedException = new NLogRuntimeException($"Target {this} failed to initialize.", initializeException); logEvent.Continuation(initializeFailedException); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> internal void Initialize(LoggingConfiguration configuration) { lock (SyncRoot) { LoggingConfiguration = configuration; if (!IsInitialized) { try { PropertyHelper.CheckRequiredParameters(ConfigurationItemFactory.Default, this); InitializeTarget(); _initializeException = null; if (!_scannedForLayouts) { InternalLogger.Debug("{0}: InitializeTarget is done but not scanned For Layouts", this); //this is critical, as we need the layouts. So if base.InitializeTarget() isn't called, we fix the layouts here. FindAllLayouts(); } } catch (NLogDependencyResolveException exception) { // Target is now in disabled state, and cannot be used for writing LogEvents _initializeException = exception; if (ExceptionMustBeRethrown(exception)) throw; } catch (Exception exception) { // Target is now in disabled state, and cannot be used for writing LogEvents _initializeException = exception; if (ExceptionMustBeRethrown(exception)) throw; var logFactory = LoggingConfiguration?.LogFactory ?? LogManager.LogFactory; if ((logFactory.ThrowConfigExceptions ?? logFactory.ThrowExceptions)) { throw new NLogConfigurationException($"Error during initialization of target {this}", exception); } } finally { _isInitialized = true; // Only one attempt, must Close to retry } } } } /// <summary> /// Closes this instance. /// </summary> internal void Close() { lock (SyncRoot) { LoggingConfiguration = null; if (IsInitialized) { _isInitialized = false; try { if (_initializeException is null) { // if Init succeeded, call Close() InternalLogger.Debug("{0}: Closing...", this); CloseTarget(); InternalLogger.Debug("{0}: Closed.", this); } } catch (Exception exception) { if (ExceptionMustBeRethrown(exception)) throw; } } } } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing && _isInitialized) { _isInitialized = false; if (_initializeException is null) { CloseTarget(); } } } /// <summary> /// Initializes the target before writing starts /// </summary> protected virtual void InitializeTarget() { //rescan as amount layouts can be changed. FindAllLayouts(); } private void FindAllLayouts() { var allLayouts = ObjectGraphScanner.FindReachableObjects<Layout>(ConfigurationItemFactory.Default, false, this); InternalLogger.Trace("{0} has {1} layouts", this, allLayouts.Count); _allLayoutsAreThreadAgnostic = allLayouts.All(layout => layout.ThreadAgnostic); _oneLayoutIsMutableUnsafe = _allLayoutsAreThreadAgnostic && allLayouts.Any(layout => layout.MutableUnsafe); var result = allLayouts.Aggregate(StackTraceUsage.None, (agg, layout) => agg | layout.StackTraceUsage); StackTraceUsage = result | ((this as IUsesStackTrace)?.StackTraceUsage ?? StackTraceUsage.None); _allLayouts = allLayouts.Where(l => !l.ThreadAgnostic || l.MutableUnsafe || !(l is SimpleLayout)).Distinct(SingleItemOptimizedHashSet<Layout>.ReferenceEqualityComparer.Default).ToArray(); _scannedForLayouts = true; } /// <summary> /// Closes the target to release any initialized resources /// </summary> protected virtual void CloseTarget() { } /// <summary> /// Flush any pending log messages /// </summary> /// <remarks>The asynchronous continuation parameter must be called on flush completed</remarks> /// <param name="asyncContinuation">The asynchronous continuation to be called on flush completed.</param> protected virtual void FlushAsync(AsyncContinuation asyncContinuation) { asyncContinuation(null); } /// <summary> /// Writes logging event to the target destination /// </summary> /// <param name="logEvent">Logging event to be written out.</param> protected virtual void Write(LogEventInfo logEvent) { // Override to perform the actual write-operation } /// <summary> /// Writes async log event to the log target. /// </summary> /// <param name="logEvent">Async Log event to be written out.</param> protected virtual void Write(AsyncLogEventInfo logEvent) { try { Write(logEvent.LogEvent); logEvent.Continuation(null); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception)) throw; logEvent.Continuation(exception); } } /// <summary> /// Writes a log event to the log target, in a thread safe manner. /// Any override of this method has to provide their own synchronization mechanism. /// /// !WARNING! Custom targets should only override this method if able to provide their /// own synchronization mechanism. <see cref="Layout" />-objects are not guaranteed to be /// thread-safe, so using them without a SyncRoot-object can be dangerous. /// </summary> /// <param name="logEvent">Log event to be written out.</param> protected virtual void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { lock (SyncRoot) { if (!IsInitialized) { // In case target was Closed logEvent.Continuation(null); return; } Write(logEvent); } } /// <summary> /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected virtual void Write(IList<AsyncLogEventInfo> logEvents) { for (int i = 0; i < logEvents.Count; ++i) { Write(logEvents[i]); } } /// <summary> /// Writes an array of logging events to the log target, in a thread safe manner. /// Any override of this method has to provide their own synchronization mechanism. /// /// !WARNING! Custom targets should only override this method if able to provide their /// own synchronization mechanism. <see cref="Layout" />-objects are not guaranteed to be /// thread-safe, so using them without a SyncRoot-object can be dangerous. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected virtual void WriteAsyncThreadSafe(IList<AsyncLogEventInfo> logEvents) { lock (SyncRoot) { if (!IsInitialized) { // In case target was Closed for (int i = 0; i < logEvents.Count; ++i) { logEvents[i].Continuation(null); } return; } Write(logEvents); } } /// <summary> /// Merges (copies) the event context properties from any event info object stored in /// parameters of the given event info object. /// </summary> /// <param name="logEvent">The event info object to perform the merge to.</param> [Obsolete("Logger.Trace(logEvent) now automatically captures the logEvent Properties. Marked obsolete on NLog 4.6")] [EditorBrowsable(EditorBrowsableState.Never)] protected void MergeEventProperties(LogEventInfo logEvent) { if (logEvent.Parameters is null || logEvent.Parameters.Length == 0) { return; } //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < logEvent.Parameters.Length; ++i) { if (logEvent.Parameters[i] is LogEventInfo logEventParameter && logEventParameter.HasProperties) { foreach (var key in logEventParameter.Properties.Keys) { logEvent.Properties.Add(key, logEventParameter.Properties[key]); } logEventParameter.Properties.Clear(); } } } /// <summary> /// Renders the logevent into a string-result using the provided layout /// </summary> /// <param name="layout">The layout.</param> /// <param name="logEvent">The logevent info.</param> /// <returns>String representing log event.</returns> protected string RenderLogEvent([CanBeNull] Layout layout, [CanBeNull] LogEventInfo logEvent) { if (layout is null || logEvent is null) return null; // Signal that input was wrong SimpleLayout simpleLayout = layout as SimpleLayout; if (simpleLayout != null && simpleLayout.IsFixedText) { return simpleLayout.Render(logEvent); } if (TryGetCachedValue(layout, logEvent, out var value)) { return value?.ToString() ?? string.Empty; } if (simpleLayout != null && simpleLayout.IsSimpleStringText) { return simpleLayout.Render(logEvent); } using (var localTarget = ReusableLayoutBuilder.Allocate()) { return layout.RenderAllocateBuilder(logEvent, localTarget.Result); } } /// <summary> /// Renders the logevent into a result-value by using the provided layout /// </summary> /// <typeparam name="T"></typeparam> /// <param name="layout">The layout.</param> /// <param name="logEvent">The logevent info.</param> /// <param name="defaultValue">Fallback value when no value available</param> /// <returns>Result value when available, else fallback to defaultValue</returns> protected T RenderLogEvent<T>([CanBeNull] Layout<T> layout, [CanBeNull] LogEventInfo logEvent, T defaultValue = default(T)) { if (layout is null) return defaultValue; if (layout.IsFixed) return layout.FixedValue; if (logEvent is null) return defaultValue; if (TryGetCachedValue(layout, logEvent, out var value)) { if (value is null) return defaultValue; else return (T)value; } using (var localTarget = ReusableLayoutBuilder.Allocate()) { return layout.RenderTypedValue(logEvent, localTarget.Result, defaultValue); } } /// <summary> /// Resolve from DI <see cref="LogFactory.ServiceRepository"/> /// </summary> /// <remarks>Avoid calling this while handling a LogEvent, since random deadlocks can occur.</remarks> protected T ResolveService<T>() where T : class { return LoggingConfiguration.GetServiceProvider().ResolveService<T>(IsInitialized); } /// <summary> /// Should the exception be rethrown? /// </summary> /// <remarks>Upgrade to private protected when using C# 7.2 </remarks> /// internal bool ExceptionMustBeRethrown(Exception exception, #if !NET35 [System.Runtime.CompilerServices.CallerMemberName] #endif string callerMemberName = null) { return exception.MustBeRethrown(this, callerMemberName); } private static bool TryGetCachedValue(Layout layout, LogEventInfo logEvent, out object value) { if ((!layout.ThreadAgnostic || layout.MutableUnsafe) && logEvent.TryGetCachedLayoutValue(layout, out value)) { return true; } value = null; return false; } /// <summary> /// Register a custom Target. /// </summary> /// <remarks>Short-cut for registering to default <see cref="ConfigurationItemFactory"/></remarks> /// <typeparam name="T">Type of the Target.</typeparam> /// <param name="name">The target type-alias for use in NLog configuration</param> [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public static void Register<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(string name) where T : Target { var layoutRendererType = typeof(T); Register(name, layoutRendererType); } /// <summary> /// Register a custom Target. /// </summary> /// <remarks>Short-cut for registering to default <see cref="ConfigurationItemFactory"/></remarks> /// <param name="targetType">Type of the Target.</param> /// <param name="name">The target type-alias for use in NLog configuration</param> [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] public static void Register(string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type targetType) { ConfigurationItemFactory.Default.GetTargetFactory().RegisterDefinition(name, targetType); } } } <file_sep>namespace DumpApiXml { using System; using System.IO; public class Program { private static int Main(string[] args) { try { var builder = new DocFileBuilder(); string outputFile = null; for (int i = 0; i < args.Length; ++i) { switch (args[i]) { case "-comments": builder.LoadComments(args[++i]); break; case "-assembly": { string assembly = args[++i]; if (File.Exists(assembly)) { builder.LoadAssembly(assembly); string docpath = Path.ChangeExtension(assembly, ".xml"); if (File.Exists(docpath)) { builder.LoadComments(docpath); } } else { Console.WriteLine("Assembly not found - {0}", Path.GetFullPath(assembly)); } } break; case "-nc": builder.DisableComments(); break; case "-output": outputFile = args[++i]; break; case "-?": Usage(); return 0; default: Console.WriteLine("Unknown option '{0}'", args[i]); Usage(); return 1; } } if (outputFile == null) { Usage(); return 1; } outputFile = Path.GetFullPath(outputFile); Console.WriteLine("Generating '{0}'...", outputFile); Directory.CreateDirectory(Path.GetDirectoryName(outputFile)); builder.Build(outputFile); return 0; } catch (Exception ex) { Console.WriteLine("ERROR: {0}", ex.ToString()); return 1; } } private static void Usage() { Console.WriteLine("DumpApiXml [-comments commentFile.xml]+ [-assembly assembly.dll] -output file.xml"); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Config { using System; using System.IO; using System.Text; using NLog.Common; using NLog.Config; using Xunit; public class InternalLoggingTests : NLogTestBase { [Fact] public void InternalLoggingConfigTest1() { InternalLoggingConfigTest(LogLevel.Trace, true, true, LogLevel.Warn, true, true, @"c:\temp\nlog\file.txt", true, true); } [Fact] public void InternalLoggingConfigTest2() { InternalLoggingConfigTest(LogLevel.Error, false, false, LogLevel.Info, false, false, @"c:\temp\nlog\file2.txt", false, false); } [Fact] public void InternalLoggingConfigTes3() { InternalLoggingConfigTest(LogLevel.Info, false, false, LogLevel.Trace, false, null, @"c:\temp\nlog\file3.txt", false, true); } [Fact] public void InternalLoggingConfigTestDefaults() { using (new InternalLoggerScope(true)) { InternalLogger.LogLevel = LogLevel.Error; InternalLogger.LogToConsole = true; InternalLogger.LogToConsoleError = true; LogManager.GlobalThreshold = LogLevel.Fatal; LogManager.ThrowExceptions = true; LogManager.ThrowConfigExceptions = null; LogManager.AutoShutdown = true; InternalLogger.LogToTrace = true; XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> </nlog>"); Assert.Same(LogLevel.Error, InternalLogger.LogLevel); Assert.True(InternalLogger.LogToConsole); Assert.True(InternalLogger.LogToConsoleError); Assert.Same(LogLevel.Fatal, LogManager.GlobalThreshold); Assert.True(LogManager.ThrowExceptions); Assert.Null(LogManager.ThrowConfigExceptions); Assert.True(LogManager.AutoShutdown); Assert.True(InternalLogger.LogToTrace); } } [Fact] public void InternalLoggingConfig_off_should_be_off() { using (new InternalLoggerScope()) { var sb = new StringBuilder(); var stringWriter = new StringWriter(sb); InternalLogger.LogWriter = stringWriter; InternalLogger.LogLevel = LogLevel.Info; string wrongFileName = "WRONG/***[]???////WRONG"; LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString($@"<?xml version='1.0' encoding='utf-8' ?> <nlog internalLogFile='{wrongFileName}' internalLogLevel='Off' throwExceptions='true' > <targets> <target name='logfile' type='File' fileName='WRONG' /> </targets> <rules> <logger name='*' writeTo='logfile' /> </rules> </nlog> "); Assert.Equal("", sb.ToString()); Assert.Equal(LogLevel.Off, InternalLogger.LogLevel); Assert.False(InternalLogger.ExceptionThrowWhenWriting); } } [Fact] public void InternalLoggingInvalidFormatString() { using (new InternalLoggerScope()) { var sb = new StringBuilder(); var stringWriter = new StringWriter(sb); InternalLogger.LogWriter = stringWriter; InternalLogger.LogLevel = LogLevel.Info; var invalidFormatString = "Invalid String.Format({Message})"; InternalLogger.Warn(invalidFormatString, "Oops"); Assert.Contains(invalidFormatString, sb.ToString()); } } private static void InternalLoggingConfigTest(LogLevel logLevel, bool logToConsole, bool logToConsoleError, LogLevel globalThreshold, bool throwExceptions, bool? throwConfigExceptions, string file, bool logToTrace, bool autoShutdown) { var logLevelString = logLevel.ToString(); var internalLogToConsoleString = logToConsole.ToString().ToLower(); var internalLogToConsoleErrorString = logToConsoleError.ToString().ToLower(); var globalThresholdString = globalThreshold.ToString(); var throwExceptionsString = throwExceptions.ToString().ToLower(); var throwConfigExceptionsString = throwConfigExceptions?.ToString().ToLower() ?? string.Empty; var logToTraceString = logToTrace.ToString().ToLower(); var autoShutdownString = autoShutdown.ToString().ToLower(); using (new InternalLoggerScope(true)) { XmlLoggingConfiguration.CreateFromXmlString($@" <nlog internalLogFile='{file}' internalLogLevel='{logLevelString}' internalLogToConsole='{ internalLogToConsoleString }' internalLogToConsoleError='{internalLogToConsoleErrorString}' globalThreshold='{ globalThresholdString }' throwExceptions='{throwExceptionsString}' throwConfigExceptions='{ throwConfigExceptionsString }' internalLogToTrace='{logToTraceString}' autoShutdown='{autoShutdownString}'> </nlog>"); Assert.Same(logLevel, InternalLogger.LogLevel); Assert.Equal(file, InternalLogger.LogFile); Assert.Equal(logToConsole, InternalLogger.LogToConsole); Assert.Equal(logToConsoleError, InternalLogger.LogToConsoleError); Assert.Same(globalThreshold, LogManager.GlobalThreshold); Assert.Equal(throwExceptions, LogManager.ThrowExceptions); Assert.Equal(throwConfigExceptions, LogManager.ThrowConfigExceptions); Assert.Equal(logToTrace, InternalLogger.LogToTrace); Assert.Equal(autoShutdown, LogManager.AutoShutdown); } } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Internal; using Xunit; namespace NLog.UnitTests.Internal { public class MruCacheTests { [Fact] public void SimpleCacheAddAndLookupTest() { MruCache<int, string> mruCache = new MruCache<int, string>(100); for (int i = 0; i < 100; ++i) mruCache.TryAddValue(i, i.ToString()); string value; for (int i = 0; i < 100; ++i) { Assert.True(mruCache.TryGetValue(i, out value)); Assert.Equal(i.ToString(), value); } Assert.False(mruCache.TryGetValue(101, out value)); } [Fact] public void OverflowCacheAndLookupTest() { MruCache<int, string> mruCache = new MruCache<int, string>(100); for (int i = 0; i < 200; ++i) mruCache.TryAddValue(i, i.ToString()); string value; for (int i = 0; i < 100; ++i) { Assert.False(mruCache.TryGetValue(i, out value)); } for (int i = 140; i < 200; ++i) { Assert.True(mruCache.TryGetValue(i, out value)); Assert.Equal(i.ToString(), value); } } [Fact] public void OverflowVersionCacheAndLookupTest() { string value; MruCache<int, string> mruCache = new MruCache<int, string>(100); for (int i = 0; i < 200; ++i) { mruCache.TryAddValue(i, i.ToString()); Assert.True(mruCache.TryGetValue(i, out value)); // No longer a virgin Assert.Equal(i.ToString(), value); } for (int i = 0; i < 90; ++i) { Assert.False(mruCache.TryGetValue(i, out value)); } for (int i = 140; i < 200; ++i) { Assert.True(mruCache.TryGetValue(i, out value)); Assert.Equal(i.ToString(), value); } } [Fact] public void OverflowFreshCacheAndLookupTest() { string value; MruCache<int, string> mruCache = new MruCache<int, string>(100); for (int i = 0; i < 200; ++i) { mruCache.TryAddValue(i, i.ToString()); Assert.True(mruCache.TryGetValue(i, out value)); // No longer a virgin Assert.Equal(i.ToString(), value); } for (int j = 0; j < 2; ++j) { for (int i = 110; i < 200; ++i) { if (!mruCache.TryGetValue(i, out value)) { mruCache.TryAddValue(i, i.ToString()); Assert.True(mruCache.TryGetValue(i, out value)); } } } for (int i = 300; i < 310; ++i) { mruCache.TryAddValue(i, i.ToString()); } int cacheCount = 0; for (int i = 110; i < 200; ++i) { if (mruCache.TryGetValue(i, out value)) ++cacheCount; } Assert.True(cacheCount > 60); // See that old cache was not killed } [Fact] public void RecentlyUsedLookupTest() { string value; MruCache<int, string> mruCache = new MruCache<int, string>(100); for (int i = 0; i < 200; ++i) { mruCache.TryAddValue(i, i.ToString()); for (int j = 0; j < i; j += 10) { Assert.True(mruCache.TryGetValue(j, out value)); Assert.Equal(j.ToString(), value); } } for (int j = 0; j < 100; j += 10) { Assert.True(mruCache.TryGetValue(j, out value)); Assert.Equal(j.ToString(), value); } for (int i = 170; i < 200; ++i) { Assert.True(mruCache.TryGetValue(i, out value)); Assert.Equal(i.ToString(), value); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Internal { using NLog.Layouts; using NLog.Internal; using NLog.Targets; using Xunit; public class FilePathLayoutTests // Not needed as not using NLog-Core -> : NLogTestBase { [Theory] [InlineData(@"", FilePathKind.Unknown)] [InlineData(@" ", FilePathKind.Unknown)] [InlineData(null, FilePathKind.Unknown)] [InlineData(@"/ test\a", FilePathKind.Absolute)] [InlineData(@"test.log", FilePathKind.Relative)] [InlineData(@"test", FilePathKind.Relative)] [InlineData(@" test.log ", FilePathKind.Relative)] [InlineData(@" a/test.log ", FilePathKind.Relative)] [InlineData(@".test.log ", FilePathKind.Relative)] [InlineData(@"..test.log ", FilePathKind.Relative)] [InlineData(@" .. test.log ", FilePathKind.Relative)] [InlineData(@"${basedir}\test.log ", FilePathKind.Absolute)] [InlineData(@"${BASEDIR}\test.log ", FilePathKind.Absolute)] [InlineData(@"${basedir}\test ", FilePathKind.Absolute)] [InlineData(@"${BASEDIR}\test ", FilePathKind.Absolute)] [InlineData(@"${level}\test ", FilePathKind.Unknown)] [InlineData(@"${basedir}/test.log ", FilePathKind.Absolute)] [InlineData(@"${BASEDIR}/test.log ", FilePathKind.Absolute)] [InlineData(@"${specialfolder:applicationdata}/test.log ", FilePathKind.Absolute)] [InlineData(@"${basedir}/test ", FilePathKind.Absolute)] [InlineData(@"${BASEDIR}/test ", FilePathKind.Absolute)] [InlineData(@"${level}/test ", FilePathKind.Unknown)] [InlineData(@" ${level}/test ", FilePathKind.Unknown)] [InlineData(@" ${level}/test ", FilePathKind.Unknown)] [InlineData(@"dir ${level}/test ", FilePathKind.Relative)] [InlineData(@"dir${level}/test ", FilePathKind.Relative)] public void DetectFilePathKind(string path, FilePathKind expected) { SimpleLayout layout = path; var result = FilePathLayout.DetectFilePathKind(layout); Assert.Equal(expected, result); } [Theory] [InlineData(@"d:\test.log", FilePathKind.Absolute)] [InlineData(@"d:\test", FilePathKind.Absolute)] [InlineData(@" d:\test", FilePathKind.Absolute)] [InlineData(@" d:\ test", FilePathKind.Absolute)] [InlineData(@" d:\ test\a", FilePathKind.Absolute)] [InlineData(@"\\test\a", FilePathKind.Absolute)] [InlineData(@"\\test/a", FilePathKind.Absolute)] [InlineData(@"\ test\a", FilePathKind.Absolute)] [InlineData(@" a\test.log ", FilePathKind.Relative)] public void DetectFilePathKindWindowsPath(string path, FilePathKind expected) { if (System.IO.Path.DirectorySeparatorChar != '\\') return; //no backward-slash on linux SimpleLayout layout = path; var result = FilePathLayout.DetectFilePathKind(layout); Assert.Equal(expected, result); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Filters { using System.Linq; using NLog.Config; using NLog.Filters; using Xunit; public class WhenMethodFilterTests : NLogTestBase { [Fact] public void WhenMethodFilterAPITest() { // Stage var logFactory = new LogFactory(); var logger1 = logFactory.GetLogger("Hello"); var logger2 = logFactory.GetLogger("Goodbye"); var config = new LoggingConfiguration(logFactory); var target = new NLog.Targets.DebugTarget() { Layout = "${message}" }; config.AddRuleForAllLevels(target); config.LoggingRules.Last().Filters.Add(new WhenMethodFilter((l) => l.LoggerName == logger1.Name ? FilterResult.Ignore : FilterResult.Log)); logFactory.Configuration = config; // Act 1 logger1.Info("Hello World"); Assert.Empty(target.LastMessage); // Act 2 logger2.Info("Goodbye World"); Assert.Equal("Goodbye World", target.LastMessage); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; using NLog.Config; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class AsyncTargetWrapperTests : NLogTestBase { [Fact] public void AsyncTargetWrapperInitTest() { var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper(myTarget, 300, AsyncTargetWrapperOverflowAction.Grow); Assert.Equal(AsyncTargetWrapperOverflowAction.Grow, targetWrapper.OverflowAction); Assert.Equal(300, targetWrapper.QueueLimit); Assert.Equal(1, targetWrapper.TimeToSleepBetweenBatches); Assert.Equal(200, targetWrapper.BatchSize); } [Fact] public void AsyncTargetWrapperInitTest2() { var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper() { WrappedTarget = myTarget, }; Assert.Equal(AsyncTargetWrapperOverflowAction.Discard, targetWrapper.OverflowAction); Assert.Equal(10000, targetWrapper.QueueLimit); Assert.Equal(1, targetWrapper.TimeToSleepBetweenBatches); Assert.Equal(200, targetWrapper.BatchSize); } [Fact] public void AsyncTargetWrapperSyncTest_WithLock_WhenTimeToSleepBetweenBatchesIsEqualToZero() { AsyncTargetWrapperSyncTest_WhenTimeToSleepBetweenBatchesIsEqualToZero(true); } [Fact] public void AsyncTargetWrapperSyncTest_NoLock_WhenTimeToSleepBetweenBatchesIsEqualToZero() { AsyncTargetWrapperSyncTest_WhenTimeToSleepBetweenBatchesIsEqualToZero(false); } /// <summary> /// Test Fix for https://github.com/NLog/NLog/issues/1069 /// </summary> private static void AsyncTargetWrapperSyncTest_WhenTimeToSleepBetweenBatchesIsEqualToZero(bool forceLockingQueue) { LogManager.ThrowConfigExceptions = true; var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper() { WrappedTarget = myTarget, TimeToSleepBetweenBatches = 0, #if !NET35 && !NET40 ForceLockingQueue = forceLockingQueue, #endif BatchSize = 3, QueueLimit = 5, // Will make it "sleep" between every second write FullBatchSizeWriteLimit = 1, OverflowAction = AsyncTargetWrapperOverflowAction.Block }; targetWrapper.Initialize(null); myTarget.Initialize(null); try { int flushCounter = 0; AsyncContinuation flushHandler = (ex) => { ++flushCounter; }; var itemPrepareList = new List<AsyncLogEventInfo>(500); var itemWrittenList = new List<int>(itemPrepareList.Capacity); for (int i = 0; i < itemPrepareList.Capacity; ++i) { var logEvent = new LogEventInfo(); int sequenceID = logEvent.SequenceID; bool blockConsumer = (itemPrepareList.Capacity / 2) == i; // Force producers to get into blocking-mode itemPrepareList.Add(logEvent.WithContinuation((ex) => { if (blockConsumer) Thread.Sleep(125); itemWrittenList.Add(sequenceID); })); } var eventProducer0 = new ManualResetEvent(false); var eventProducer1 = new ManualResetEvent(false); ParameterizedThreadStart producerMethod = (s) => { var eventProducer = (ManualResetEvent)s; if (eventProducer != null) eventProducer.Set(); // Signal we are ready int partitionNo = ReferenceEquals(eventProducer, eventProducer1) ? 1 : 0; for (int i = 0; i < itemPrepareList.Count; ++i) { if (i % 2 == partitionNo) targetWrapper.WriteAsyncLogEvent(itemPrepareList[i]); } }; Thread producer0 = new Thread(producerMethod); producer0.IsBackground = true; Thread producer1 = new Thread(producerMethod); producer1.IsBackground = true; producer1.Start(eventProducer0); producer0.Start(eventProducer1); Assert.True(eventProducer0.WaitOne(5000), "Producer0 Start Timeout"); Assert.True(eventProducer1.WaitOne(5000), "Producer1 Start Timeout"); long startTicks = Environment.TickCount; Assert.True(producer0.Join(5000), "Producer0 Complete Timeout"); // Wait for producer0 to complete Assert.True(producer1.Join(5000), "Producer1 Complete Timeout"); // Wait for producer1 to complete long elapsedMilliseconds = Environment.TickCount - startTicks; targetWrapper.Flush(flushHandler); for (int i = 0; i < itemPrepareList.Count * 2 && itemWrittenList.Count != itemPrepareList.Count; ++i) Thread.Sleep(1); Assert.Equal(itemPrepareList.Count, itemWrittenList.Count); int producer0sequenceID = 0; int producer1sequenceID = 0; for (int i = 1; i < itemWrittenList.Count; ++i) { if (itemWrittenList[i] % 2 == 0) { Assert.True(producer0sequenceID < itemWrittenList[i], "Producer0 invalid sequence"); producer0sequenceID = itemWrittenList[i]; } else { Assert.True(producer1sequenceID < itemWrittenList[i], "Producer1 invalid sequence"); producer1sequenceID = itemWrittenList[i]; } } #if DEBUG if (!IsAppVeyor()) // Skip timing test when running within OpenCover.Console.exe #endif Assert.InRange(elapsedMilliseconds, 0, 975); targetWrapper.Flush(flushHandler); for (int i = 0; i < 2000 && flushCounter != 2; ++i) Thread.Sleep(1); Assert.Equal(2, flushCounter); } finally { myTarget.Close(); targetWrapper.Close(); } } [Fact] public void AsyncTargetWrapperSyncTest1() { var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper { WrappedTarget = myTarget, Name = "AsyncTargetWrapperSyncTest1_Wrapper", }; targetWrapper.Initialize(null); myTarget.Initialize(null); try { var logEvent = new LogEventInfo(); Exception lastException = null; ManualResetEvent continuationHit = new ManualResetEvent(false); Thread continuationThread = null; AsyncContinuation continuation = ex => { lastException = ex; continuationThread = Thread.CurrentThread; continuationHit.Set(); }; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); // continuation was not hit Assert.True(continuationHit.WaitOne(5000)); Assert.NotSame(continuationThread, Thread.CurrentThread); Assert.Null(lastException); Assert.Equal(1, myTarget.WriteCount); continuationHit.Reset(); targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit.WaitOne(5000)); Assert.NotSame(continuationThread, Thread.CurrentThread); Assert.Null(lastException); Assert.Equal(2, myTarget.WriteCount); } finally { myTarget.Close(); targetWrapper.Close(); } } [Fact] public void AsyncTargetWrapperAsyncTest1() { var myTarget = new MyAsyncTarget(); var targetWrapper = new AsyncTargetWrapper(myTarget) { Name = "AsyncTargetWrapperAsyncTest1_Wrapper" }; targetWrapper.Initialize(null); myTarget.Initialize(null); try { var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit.WaitOne(5000)); Assert.Null(lastException); Assert.Equal(1, myTarget.WriteCount); continuationHit.Reset(); targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit.WaitOne(5000)); Assert.Null(lastException); Assert.Equal(2, myTarget.WriteCount); } finally { myTarget.Close(); targetWrapper.Close(); } } [Fact] public void AsyncTargetWrapperAsyncWithExceptionTest1() { var myTarget = new MyAsyncTarget { ThrowExceptions = true, }; var targetWrapper = new AsyncTargetWrapper(myTarget) {Name = "AsyncTargetWrapperAsyncWithExceptionTest1_Wrapper"}; targetWrapper.Initialize(null); myTarget.Initialize(null); try { var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit.WaitOne(5000)); Assert.NotNull(lastException); Assert.IsType<InvalidOperationException>(lastException); // no flush on exception Assert.Equal(0, myTarget.FlushCount); Assert.Equal(1, myTarget.WriteCount); continuationHit.Reset(); lastException = null; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit.WaitOne(5000)); Assert.NotNull(lastException); Assert.IsType<InvalidOperationException>(lastException); Assert.Equal(0, myTarget.FlushCount); Assert.Equal(2, myTarget.WriteCount); } finally { myTarget.Close(); targetWrapper.Close(); } } [Fact] public void AsyncTargetWrapperFlushTest() { RetryingIntegrationTest(3, () => { var myTarget = new MyAsyncTarget { ThrowExceptions = true }; var targetWrapper = new AsyncTargetWrapper(myTarget) { Name = "AsyncTargetWrapperFlushTest_Wrapper", OverflowAction = AsyncTargetWrapperOverflowAction.Grow }; targetWrapper.Initialize(null); myTarget.Initialize(null); try { List<Exception> exceptions = new List<Exception>(); int eventCount = 5000; for (int i = 0; i < eventCount; ++i) { targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation( ex => { lock (exceptions) { exceptions.Add(ex); } })); } Exception lastException = null; ManualResetEvent mre = new ManualResetEvent(false); string internalLog = RunAndCaptureInternalLog( () => { targetWrapper.Flush( cont => { try { // by this time all continuations should be completed Assert.Equal(eventCount, exceptions.Count); // with just 1 flush of the target Assert.Equal(1, myTarget.FlushCount); // and all writes should be accounted for Assert.Equal(eventCount, myTarget.WriteCount); } catch (Exception ex) { lastException = ex; } finally { mre.Set(); } }); Assert.True(mre.WaitOne(5000), InternalLogger.LogWriter?.ToString() ?? string.Empty); }, LogLevel.Trace); if (lastException != null) { Assert.True(false, lastException.ToString() + "\r\n" + internalLog); } } finally { myTarget.Close(); targetWrapper.Close(); } }); } [Fact] public void AsyncTargetWrapperCloseTest() { var myTarget = new MyAsyncTarget { ThrowExceptions = true }; var targetWrapper = new AsyncTargetWrapper(myTarget) { OverflowAction = AsyncTargetWrapperOverflowAction.Grow, TimeToSleepBetweenBatches = 1000, Name = "AsyncTargetWrapperCloseTest_Wrapper", }; targetWrapper.Initialize(null); myTarget.Initialize(null); var writeOnClose = new ManualResetEvent(false); targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { writeOnClose.Set(); })); // quickly close the target before the timer elapses targetWrapper.Close(); Assert.True(writeOnClose.WaitOne(5000)); } [Fact] public void AsyncTargetWrapperExceptionTest() { var targetWrapper = new AsyncTargetWrapper { OverflowAction = AsyncTargetWrapperOverflowAction.Grow, TimeToSleepBetweenBatches = 500, WrappedTarget = new DebugTarget(), Name = "AsyncTargetWrapperExceptionTest_Wrapper" }; using (new NoThrowNLogExceptions()) { targetWrapper.Initialize(null); // null out wrapped target - will cause exception on the timer thread targetWrapper.WrappedTarget = null; string internalLog = RunAndCaptureInternalLog( () => { targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { })); targetWrapper.Close(); }, LogLevel.Trace); Assert.True(internalLog.Contains("WrappedTarget is NULL"), internalLog); } } [Fact] public void FlushingMultipleTimesSimultaneous() { var asyncTarget = new AsyncTargetWrapper { TimeToSleepBetweenBatches = 1000, WrappedTarget = new DebugTarget(), Name = "FlushingMultipleTimesSimultaneous_Wrapper" }; asyncTarget.Initialize(null); try { asyncTarget.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { })); var firstContinuationCalled = false; var secondContinuationCalled = false; var firstContinuationResetEvent = new ManualResetEvent(false); var secondContinuationResetEvent = new ManualResetEvent(false); asyncTarget.Flush(ex => { firstContinuationCalled = true; firstContinuationResetEvent.Set(); }); asyncTarget.Flush(ex => { secondContinuationCalled = true; secondContinuationResetEvent.Set(); }); Assert.True(firstContinuationResetEvent.WaitOne(5000), nameof(firstContinuationResetEvent)); Assert.True(secondContinuationResetEvent.WaitOne(5000), nameof(secondContinuationResetEvent)); Assert.True(firstContinuationCalled); Assert.True(secondContinuationCalled); } finally { asyncTarget.Close(); } } [Fact] public void LogEventDropped_OnRequestqueueOverflow() { int queueLimit = 2; int loggedEventCount = 5; int eventsCounter = 0; var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper() { WrappedTarget = myTarget, QueueLimit = queueLimit, TimeToSleepBetweenBatches = 500, // Make it slow OverflowAction = AsyncTargetWrapperOverflowAction.Discard, }; var logFactory = new LogFactory(); var loggingConfig = new NLog.Config.LoggingConfiguration(logFactory); loggingConfig.AddRuleForAllLevels(targetWrapper); logFactory.Configuration = loggingConfig; var logger = logFactory.GetLogger("Test"); try { targetWrapper.LogEventDropped += (o, e) => { eventsCounter++; }; for (int i = 0; i < loggedEventCount; i++) { logger.Info("Hello"); } Assert.Equal(loggedEventCount - queueLimit, eventsCounter); } finally { logFactory.Configuration = null; } } [Fact] public void LogEventNotDropped_IfOverflowActionBlock() { int queueLimit = 2; int loggedEventCount = 5; int eventsCounter = 0; var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper() { WrappedTarget = myTarget, QueueLimit = queueLimit, OverflowAction = AsyncTargetWrapperOverflowAction.Block }; var logFactory = new LogFactory(); var loggingConfig = new NLog.Config.LoggingConfiguration(logFactory); loggingConfig.AddRuleForAllLevels(targetWrapper); logFactory.Configuration = loggingConfig; var logger = logFactory.GetLogger("Test"); try { targetWrapper.LogEventDropped += (o, e) => { eventsCounter++; }; for (int i = 0; i < loggedEventCount; i++) { logger.Info("Hello"); } Assert.Equal(0, eventsCounter); } finally { logFactory.Configuration = null; } } [Fact] public void LogEventNotDropped_IfOverflowActionGrow() { int queueLimit = 2; int loggedEventCount = 5; int eventsCounter = 0; var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper() { WrappedTarget = myTarget, QueueLimit = queueLimit, OverflowAction = AsyncTargetWrapperOverflowAction.Grow }; var logFactory = new LogFactory(); var loggingConfig = new NLog.Config.LoggingConfiguration(logFactory); loggingConfig.AddRuleForAllLevels(targetWrapper); logFactory.Configuration = loggingConfig; var logger = logFactory.GetLogger("Test"); try { targetWrapper.LogEventDropped += (o, e) => { eventsCounter++; }; for (int i = 0; i < loggedEventCount; i++) { logger.Info("Hello"); } Assert.Equal(0, eventsCounter); } finally { logFactory.Configuration = null; } } [Fact] public void EventQueueGrow_OnQueueGrow() { int queueLimit = 2; int loggedEventCount = 10; int expectedGrowingNumber = 3; int eventsCounter = 0; var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper() { WrappedTarget = myTarget, QueueLimit = queueLimit, TimeToSleepBetweenBatches = 500, // Make it slow OverflowAction = AsyncTargetWrapperOverflowAction.Grow, }; var logFactory = new LogFactory(); var loggingConfig = new NLog.Config.LoggingConfiguration(logFactory); loggingConfig.AddRuleForAllLevels(targetWrapper); logFactory.Configuration = loggingConfig; var logger = logFactory.GetLogger("Test"); try { targetWrapper.EventQueueGrow += (o, e) => { eventsCounter++; }; for (int i = 0; i < loggedEventCount; i++) { logger.Info("Hello"); } Assert.Equal(expectedGrowingNumber, eventsCounter); } finally { logFactory.Configuration = null; } } [Fact] public void EnqueuQueueBlock_WithLock_OnClose_ReleasesWriters() { EnqueuQueueBlock_OnClose_ReleasesWriters(true); } [Fact] public void EnqueuQueueBlock_NoLock_OnClose_ReleasesWriters() { EnqueuQueueBlock_OnClose_ReleasesWriters(false); } private static void EnqueuQueueBlock_OnClose_ReleasesWriters(bool forceLockingQueue) { // Arrange var slowTarget = new MethodCallTarget("slowTarget", (logEvent, parms) => System.Threading.Thread.Sleep(300)); var targetWrapper = new AsyncTargetWrapper("asynSlowTarget", slowTarget) { OverflowAction = AsyncTargetWrapperOverflowAction.Block, QueueLimit = 3, ForceLockingQueue = forceLockingQueue, }; var logFactory = new LogFactory(); var loggingConfig = new NLog.Config.LoggingConfiguration(logFactory); loggingConfig.AddRuleForAllLevels(targetWrapper); logFactory.Configuration = loggingConfig; var logger = logFactory.GetLogger("Test"); // Act long allTasksCompleted = 0; AsyncHelpers.ForEachItemInParallel(System.Linq.Enumerable.Range(1, 6), (ex) => Interlocked.Exchange(ref allTasksCompleted, 1), (value, cont) => { for (int i = 0; i < 100; ++i) logger.Info("Hello {0}", value); cont(null); }); Thread.Sleep(150); // Let them get stuck Assert.Equal(0, Interlocked.Read(ref allTasksCompleted)); targetWrapper.Close(); // Release those who are stuck, and discard the rest // Assert for (int i = 0; i < 100; i++) { if (Interlocked.Read(ref allTasksCompleted) == 1) break; Thread.Sleep(10); } Assert.Equal(1, Interlocked.Read(ref allTasksCompleted)); } [Fact] public void AsyncTargetWrapper_MissingDependency_EnqueueLogEvents() { using (new NoThrowNLogExceptions()) { // Arrange var logFactory = new LogFactory(); logFactory.ThrowConfigExceptions = true; var logConfig = new LoggingConfiguration(logFactory); var asyncTarget = new MyTarget() { Name = "asynctarget", RequiredDependency = typeof(IMisingDependencyClass) }; logConfig.AddRuleForAllLevels(new AsyncTargetWrapper("wrapper", asyncTarget)); logFactory.Configuration = logConfig; var logger = logFactory.GetLogger(nameof(AsyncTargetWrapper_MissingDependency_EnqueueLogEvents)); // Act logger.Info("Hello World"); Assert.False(asyncTarget.WaitForWriteEvent(50)); logFactory.ServiceRepository.RegisterService(typeof(IMisingDependencyClass), new MisingDependencyClass()); // Assert Assert.True(asyncTarget.WaitForWriteEvent()); } } private interface IMisingDependencyClass { } private class MisingDependencyClass : IMisingDependencyClass { } private class MyAsyncTarget : Target { private readonly NLog.Internal.AsyncOperationCounter pendingWriteCounter = new NLog.Internal.AsyncOperationCounter(); public int FlushCount; public int WriteCount; protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); } protected override void Write(AsyncLogEventInfo logEvent) { Assert.True(FlushCount <= WriteCount); pendingWriteCounter.BeginOperation(); ThreadPool.QueueUserWorkItem( s => { try { Interlocked.Increment(ref WriteCount); if (ThrowExceptions) { logEvent.Continuation(new InvalidOperationException("Some problem!")); logEvent.Continuation(new InvalidOperationException("Some problem!")); } else { logEvent.Continuation(null); logEvent.Continuation(null); } } finally { pendingWriteCounter.CompleteOperation(null); } }); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { Interlocked.Increment(ref FlushCount); var wrappedContinuation = pendingWriteCounter.RegisterCompletionNotification(asyncContinuation); ThreadPool.QueueUserWorkItem( s => { wrappedContinuation(null); }); } public bool ThrowExceptions { get; set; } } private class MyTarget : Target { private readonly AutoResetEvent _writeEvent = new AutoResetEvent(false); public int FlushCount { get; set; } public int WriteCount { get; set; } public Type RequiredDependency { get; set; } public bool WaitForWriteEvent(int timeoutMilliseconds = 1000) { if (_writeEvent.WaitOne(TimeSpan.FromMilliseconds(timeoutMilliseconds))) { Thread.Sleep(25); return true; } return false; } protected override void InitializeTarget() { base.InitializeTarget(); if (RequiredDependency != null) { try { var resolveServiceMethod = typeof(Target).GetMethod(nameof(ResolveService), System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); resolveServiceMethod = resolveServiceMethod.MakeGenericMethod(new[] { RequiredDependency }); resolveServiceMethod.Invoke(this, NLog.Internal.ArrayHelper.Empty<object>()); } catch (System.Reflection.TargetInvocationException ex) { throw ex.InnerException; } } } protected override void Write(LogEventInfo logEvent) { Assert.True(FlushCount <= WriteCount); WriteCount++; _writeEvent.Set(); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { FlushCount++; asyncContinuation(null); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #define DEBUG namespace NLog.UnitTests.Common { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using NLog.Common; using NLog.Config; using Xunit; public class InternalLoggerTests_Trace : NLogTestBase { [Theory] [InlineData(null, null)] [InlineData(false, null)] [InlineData(null, false)] [InlineData(false, false)] public void ShouldNotLogInternalWhenLogToTraceIsDisabled(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Trace, internalLogToTrace, logToTrace); InternalLogger.Trace("Logger1 Hello"); Assert.Empty(mockTraceListener.Messages); } [Theory] [InlineData(null, null)] [InlineData(false, null)] [InlineData(null, false)] [InlineData(false, false)] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldNotLogInternalWhenLogLevelIsOff(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Off, internalLogToTrace, logToTrace); InternalLogger.Trace("Logger1 Hello"); Assert.Empty(mockTraceListener.Messages); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void VerifyInternalLoggerLevelFilter(bool? internalLogToTrace, bool? logToTrace) { foreach (LogLevel logLevelConfig in LogLevel.AllLevels) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(logLevelConfig, internalLogToTrace, logToTrace); List<string> expected = new List<string>(); string input = "Logger1 Hello"; expected.Add(input); InternalLogger.Trace(input); InternalLogger.Debug(input); InternalLogger.Info(input); InternalLogger.Warn(input); InternalLogger.Error(input); InternalLogger.Fatal(input); input += "No.{0}"; expected.Add(string.Format(input, 1)); InternalLogger.Trace(input, 1); InternalLogger.Debug(input, 1); InternalLogger.Info(input, 1); InternalLogger.Warn(input, 1); InternalLogger.Error(input, 1); InternalLogger.Fatal(input, 1); input += ", We come in {1}"; expected.Add(string.Format(input, 1, "Peace")); InternalLogger.Trace(input, 1, "Peace"); InternalLogger.Debug(input, 1, "Peace"); InternalLogger.Info(input, 1, "Peace"); InternalLogger.Warn(input, 1, "Peace"); InternalLogger.Error(input, 1, "Peace"); InternalLogger.Fatal(input, 1, "Peace"); input += " and we are {2} to god"; expected.Add(string.Format(input, 1, "Peace", true)); InternalLogger.Trace(input, 1, "Peace", true); InternalLogger.Debug(input, 1, "Peace", true); InternalLogger.Info(input, 1, "Peace", true); InternalLogger.Warn(input, 1, "Peace", true); InternalLogger.Error(input, 1, "Peace", true); InternalLogger.Fatal(input, 1, "Peace", true); input += ", Please don't {3}"; expected.Add(string.Format(input, 1, "Peace", true, null)); InternalLogger.Trace(input, 1, "Peace", true, null); InternalLogger.Debug(input, 1, "Peace", true, null); InternalLogger.Info(input, 1, "Peace", true, null); InternalLogger.Warn(input, 1, "Peace", true, null); InternalLogger.Error(input, 1, "Peace", true, null); InternalLogger.Fatal(input, 1, "Peace", true, null); input += " the {4}"; expected.Add(string.Format(input, 1, "Peace", true, null, "Messenger")); InternalLogger.Trace(input, 1, "Peace", true, null, "Messenger"); InternalLogger.Debug(input, 1, "Peace", true, null, "Messenger"); InternalLogger.Info(input, 1, "Peace", true, null, "Messenger"); InternalLogger.Warn(input, 1, "Peace", true, null, "Messenger"); InternalLogger.Error(input, 1, "Peace", true, null, "Messenger"); InternalLogger.Fatal(input, 1, "Peace", true, null, "Messenger"); Assert.Equal(expected.Count * (LogLevel.Fatal.Ordinal - logLevelConfig.Ordinal + 1), mockTraceListener.Messages.Count); for (int i = 0; i < expected.Count; ++i) { int msgCount = LogLevel.Fatal.Ordinal - logLevelConfig.Ordinal + 1; for (int j = 0; j < msgCount; ++j) { Assert.Contains(expected[i], mockTraceListener.Messages.First()); mockTraceListener.Messages.RemoveAt(0); } } Assert.Empty(mockTraceListener.Messages); } } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsTrace(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Trace, internalLogToTrace, logToTrace); InternalLogger.Trace("Logger1 Hello"); Assert.Single(mockTraceListener.Messages); Assert.Equal("NLog: Trace Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsDebug(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Debug, internalLogToTrace, logToTrace); InternalLogger.Debug("Logger1 Hello"); Assert.Single(mockTraceListener.Messages); Assert.Equal("NLog: Debug Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsInfo(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Info, internalLogToTrace, logToTrace); InternalLogger.Info("Logger1 Hello"); Assert.Single(mockTraceListener.Messages); Assert.Equal("NLog: Info Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsWarn(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Warn, internalLogToTrace, logToTrace); InternalLogger.Warn("Logger1 Hello"); Assert.Single(mockTraceListener.Messages); Assert.Equal("NLog: Warn Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsError(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Error, internalLogToTrace, logToTrace); InternalLogger.Error("Logger1 Hello"); Assert.Single(mockTraceListener.Messages); Assert.Equal("NLog: Error Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } [Theory] [InlineData(true, null)] [InlineData(null, true)] [InlineData(true, true)] public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsFatal(bool? internalLogToTrace, bool? logToTrace) { var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Fatal, internalLogToTrace, logToTrace); InternalLogger.Fatal("Logger1 Hello"); Assert.Single(mockTraceListener.Messages); Assert.Equal("NLog: Fatal Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First()); } #if !NETSTANDARD1_5 [Fact(Skip = "This test's not working - explenation is in documentation: https://msdn.microsoft.com/pl-pl/library/system.stackoverflowexception(v=vs.110).aspx#Anchor_5. To clarify if StackOverflowException should be thrown.")] public void ShouldThrowStackOverFlowExceptionWhenUsingNLogTraceListener() { SetupTestConfiguration<NLogTraceListener>(LogLevel.Trace, true, null); Assert.Throws<StackOverflowException>(() => Trace.WriteLine("StackOverFlowException")); } #endif /// <summary> /// Helper method to setup tests configuration /// </summary> /// <param name="logLevel">The <see cref="NLog.LogLevel"/> for the log event.</param> /// <param name="internalLogToTrace">internalLogToTrace XML attribute value. If <c>null</c> attribute is omitted.</param> /// <param name="logToTrace">Value of <see cref="InternalLogger.LogToTrace"/> property. If <c>null</c> property is not set.</param> /// <returns><see cref="TraceListener"/> instance.</returns> private static T SetupTestConfiguration<T>(LogLevel logLevel, bool? internalLogToTrace, bool? logToTrace) where T : TraceListener { var internalLogToTraceAttribute = ""; if (internalLogToTrace.HasValue) { internalLogToTraceAttribute = $" internalLogToTrace='{internalLogToTrace.Value}'"; } var xmlConfiguration = string.Format(XmlConfigurationFormat, logLevel, internalLogToTraceAttribute); LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(xmlConfiguration); InternalLogger.IncludeTimestamp = false; if (logToTrace.HasValue) { InternalLogger.LogToTrace = logToTrace.Value; } T traceListener; if (typeof (T) == typeof (MockTraceListener)) { traceListener = CreateMockTraceListener() as T; } else { traceListener = CreateNLogTraceListener() as T; } Trace.Listeners.Clear(); if (traceListener is null) { return null; } Trace.Listeners.Add(traceListener); return traceListener; } private const string XmlConfigurationFormat = @"<nlog internalLogLevel='{0}'{1}> <targets> <target name='debug' type='Debug' layout='${{logger}} ${{level}} ${{message}}'/> </targets> <rules> <logger name='*' level='{0}' writeTo='debug'/> </rules> </nlog>"; /// <summary> /// Creates <see cref="MockTraceListener"/> instance. /// </summary> /// <returns><see cref="MockTraceListener"/> instance.</returns> private static MockTraceListener CreateMockTraceListener() { return new MockTraceListener(); } /// <summary> /// Creates <see cref="NLogTraceListener"/> instance. /// </summary> /// <returns><see cref="NLogTraceListener"/> instance.</returns> private static TraceListener CreateNLogTraceListener() { #if !NETSTANDARD1_5 return new NLogTraceListener {Name = "Logger1", ForceLogLevel = LogLevel.Trace}; #else return null; #endif } private class MockTraceListener : TraceListener { internal readonly List<string> Messages = new List<string>(); /// <summary> /// When overridden in a derived class, writes the specified message to the listener you create in the derived class. /// </summary> /// <param name="message">A message to write. </param> public override void Write(string message) { Messages.Add(message); } /// <summary> /// When overridden in a derived class, writes a message to the listener you create in the derived class, followed by a line terminator. /// </summary> /// <param name="message">A message to write. </param> public override void WriteLine(string message) { Messages.Add(message + Environment.NewLine); } } } } <file_sep>using System; using NLog; using NLog.Targets; using NLog.Layouts; class Example { static void Main(string[] args) { FileTarget target = new FileTarget(); target.FileName = "${basedir}/file.csv"; CsvLayout layout = new CsvLayout(); layout.Columns.Add(new CsvColumn("time", "${longdate}")); layout.Columns.Add(new CsvColumn("message", "${message}")); layout.Columns.Add(new CsvColumn("logger", "${logger}")); layout.Columns.Add(new CsvColumn("level", "${level}")); target.Layout = layout; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); logger.Debug("Message with \"quotes\" and \nnew line characters."); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { /// <summary> /// Property of System.Diagnostics.Process to retrieve. /// </summary> public enum ProcessInfoProperty { /// <summary> /// Base Priority. /// </summary> BasePriority, /// <summary> /// Exit Code. /// </summary> ExitCode, /// <summary> /// Exit Time. /// </summary> ExitTime, /// <summary> /// Process Handle. /// </summary> Handle, /// <summary> /// Handle Count. /// </summary> HandleCount, /// <summary> /// Whether process has exited. /// </summary> HasExited, /// <summary> /// Process ID. /// </summary> Id, /// <summary> /// Machine name. /// </summary> MachineName, /// <summary> /// Handle of the main window. /// </summary> MainWindowHandle, /// <summary> /// Title of the main window. /// </summary> MainWindowTitle, /// <summary> /// Maximum Working Set. /// </summary> MaxWorkingSet, /// <summary> /// Minimum Working Set. /// </summary> MinWorkingSet, /// <summary> /// Non-paged System Memory Size. /// </summary> NonPagedSystemMemorySize, /// <summary> /// Non-paged System Memory Size (64-bit). /// </summary> NonPagedSystemMemorySize64, /// <summary> /// Paged Memory Size. /// </summary> PagedMemorySize, /// <summary> /// Paged Memory Size (64-bit).. /// </summary> PagedMemorySize64, /// <summary> /// Paged System Memory Size. /// </summary> PagedSystemMemorySize, /// <summary> /// Paged System Memory Size (64-bit). /// </summary> PagedSystemMemorySize64, /// <summary> /// Peak Paged Memory Size. /// </summary> PeakPagedMemorySize, /// <summary> /// Peak Paged Memory Size (64-bit). /// </summary> PeakPagedMemorySize64, /// <summary> /// Peak Virtual Memory Size. /// </summary> PeakVirtualMemorySize, /// <summary> /// Peak Virtual Memory Size (64-bit).. /// </summary> PeakVirtualMemorySize64, /// <summary> /// Peak Working Set Size. /// </summary> PeakWorkingSet, /// <summary> /// Peak Working Set Size (64-bit). /// </summary> PeakWorkingSet64, /// <summary> /// Whether priority boost is enabled. /// </summary> PriorityBoostEnabled, /// <summary> /// Priority Class. /// </summary> PriorityClass, /// <summary> /// Private Memory Size. /// </summary> PrivateMemorySize, /// <summary> /// Private Memory Size (64-bit). /// </summary> PrivateMemorySize64, /// <summary> /// Privileged Processor Time. /// </summary> PrivilegedProcessorTime, /// <summary> /// Process Name. /// </summary> ProcessName, /// <summary> /// Whether process is responding. /// </summary> Responding, /// <summary> /// Session ID. /// </summary> SessionId, /// <summary> /// Process Start Time. /// </summary> StartTime, /// <summary> /// Total Processor Time. /// </summary> TotalProcessorTime, /// <summary> /// User Processor Time. /// </summary> UserProcessorTime, /// <summary> /// Virtual Memory Size. /// </summary> VirtualMemorySize, /// <summary> /// Virtual Memory Size (64-bit). /// </summary> VirtualMemorySize64, /// <summary> /// Working Set Size. /// </summary> WorkingSet, /// <summary> /// Working Set Size (64-bit). /// </summary> WorkingSet64, } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.IO; using NLog.Common; using NLog.Config; using NLog.Targets.Wrappers; using Xunit; namespace NLog.UnitTests.Config { public class XmlConfigTests : NLogTestBase { [Fact] public void ParseNLogOptionsDefaultTest() { using (new InternalLoggerScope()) { var xml = "<nlog></nlog>"; var config = XmlLoggingConfiguration.CreateFromXmlString(xml); Assert.False(config.AutoReload); Assert.True(config.InitializeSucceeded); Assert.Equal("", InternalLogger.LogFile); Assert.True(InternalLogger.IncludeTimestamp); Assert.False(InternalLogger.LogToConsole); Assert.False(InternalLogger.LogToConsoleError); Assert.Null(InternalLogger.LogWriter); Assert.Equal(LogLevel.Off, InternalLogger.LogLevel); } } [Fact] public void ParseNLogOptionsTest() { using (new InternalLoggerScope()) { using (new NoThrowNLogExceptions()) { var xml = "<nlog logfile='test.txt' internalLogIncludeTimestamp='false' internalLogToConsole='true' internalLogToConsoleError='true'></nlog>"; var config = XmlLoggingConfiguration.CreateFromXmlString(xml); Assert.False(config.AutoReload); Assert.True(config.InitializeSucceeded); Assert.Equal("", InternalLogger.LogFile); Assert.False(InternalLogger.IncludeTimestamp); Assert.True(InternalLogger.LogToConsole); Assert.True(InternalLogger.LogToConsoleError); Assert.Null(InternalLogger.LogWriter); Assert.Equal(LogLevel.Info, InternalLogger.LogLevel); } } } [Fact] public void ParseNLogInternalLoggerPathTest() { using (new InternalLoggerScope()) { var xml = "<nlog internalLogFile='${CurrentDir}test.txt'></nlog>"; var config = XmlLoggingConfiguration.CreateFromXmlString(xml); Assert.Contains(System.IO.Directory.GetCurrentDirectory(), InternalLogger.LogFile); } using (new InternalLoggerScope()) { var xml = "<nlog internalLogFile='${BaseDir}test.txt'></nlog>"; var config = XmlLoggingConfiguration.CreateFromXmlString(xml); Assert.Contains(AppDomain.CurrentDomain.BaseDirectory, InternalLogger.LogFile); } using (new InternalLoggerScope()) { var xml = "<nlog internalLogFile='${TempDir}test.txt'></nlog>"; var config = XmlLoggingConfiguration.CreateFromXmlString(xml); Assert.Contains(System.IO.Path.GetTempPath(), InternalLogger.LogFile); } #if !NETSTANDARD1_3 using (new InternalLoggerScope()) { var xml = "<nlog internalLogFile='${ProcessDir}test.txt'></nlog>"; var config = XmlLoggingConfiguration.CreateFromXmlString(xml); Assert.Contains(Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess()?.MainModule?.FileName), InternalLogger.LogFile); } #endif #if !NETSTANDARD1_3 && !NETSTANDARD1_5 using (new InternalLoggerScope()) { var xml = "<nlog internalLogFile='${CommonApplicationDataDir}test.txt'></nlog>"; var config = XmlLoggingConfiguration.CreateFromXmlString(xml); Assert.Contains(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), InternalLogger.LogFile); } using (new InternalLoggerScope()) { var xml = "<nlog internalLogFile='${UserApplicationDataDir}test.txt'></nlog>"; var config = XmlLoggingConfiguration.CreateFromXmlString(xml); Assert.Contains(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), InternalLogger.LogFile); } using (new InternalLoggerScope()) { var xml = "<nlog internalLogFile='${UserLocalApplicationDataDir}test.txt'></nlog>"; var config = XmlLoggingConfiguration.CreateFromXmlString(xml); Assert.Contains(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), InternalLogger.LogFile); } #endif using (new InternalLoggerScope()) { var userName = Environment.GetEnvironmentVariable("USERNAME") ?? string.Empty; var xml = "<nlog internalLogFile='%USERNAME%_test.txt'></nlog>"; var config = XmlLoggingConfiguration.CreateFromXmlString(xml); if (!string.IsNullOrEmpty(userName)) Assert.Contains(userName, InternalLogger.LogFile); } } [Theory] [InlineData("0:0:0:1", 1)] [InlineData("0:0:1", 1)] [InlineData("0:1", 60)] //1 minute [InlineData("0:1:0", 60)] [InlineData("00:00:00:1", 1)] [InlineData("000:0000:000:001", 1)] [InlineData("0:0:1:1", 61)] [InlineData("1:0:0", 3600)] // 1 hour [InlineData("2:3:4", 7384)] [InlineData("1:0:0:0", 86400)] //1 day public void SetTimeSpanFromXmlTest(string interval, int seconds) { var config = XmlLoggingConfiguration.CreateFromXmlString($@" <nlog throwExceptions='true'> <targets> <wrapper-target name='limiting' type='LimitingWrapper' messagelimit='5' interval='{interval}'> <target name='debug' type='Debug' layout='${{message}}' /> </wrapper-target> </targets> <rules> <logger name='*' level='Debug' writeTo='limiting' /> </rules> </nlog>"); var target = config.FindTargetByName<LimitingTargetWrapper>("limiting"); Assert.NotNull(target); Assert.Equal(TimeSpan.FromSeconds(seconds), target.Interval); } [Fact] public void InvalidInternalLogLevel_shouldNotSetLevel() { using (new InternalLoggerScope()) using (new NoThrowNLogExceptions()) { // Arrange InternalLogger.LogLevel = LogLevel.Error; var xml = @"<nlog internalLogLevel='bogus' > </nlog>"; // Act XmlLoggingConfiguration.CreateFromXmlString(xml); // Assert Assert.Equal(LogLevel.Error, InternalLogger.LogLevel); } } [Fact] public void InvalidNLogAttributeValues_shouldNotBreakLogging() { using (new InternalLoggerScope()) using (new NoThrowNLogExceptions()) { // Arrange var xml = @"<nlog internalLogLevel='oops' globalThreshold='noooos'> <targets> <target name='debug' type='Debug' layout='${message}' /> </targets> <rules> <logger name='*' minlevel='debug' appendto='debug' /> </rules> </nlog>"; var logFactory = new LogFactory(); var config = XmlLoggingConfiguration.CreateFromXmlString(xml, logFactory); logFactory.Configuration = config; var logger = logFactory.GetLogger("InvalidInternalLogLevel_shouldNotBreakLogging"); // Act logger.Debug("message 1"); // Assert logFactory.AssertDebugLastMessage("message 1"); } } [Fact] public void XmlConfig_ParseUtf8Encoding_WithoutHyphen() { // Arrange var xml = @"<nlog> <targets> <target name='file' type='File' encoding='utf8' layout='${message}' fileName='hello.txt' /> </targets> <rules> <logger name='*' minlevel='debug' appendto='file' /> </rules> </nlog>"; var config = XmlLoggingConfiguration.CreateFromXmlString(xml); Assert.Single(config.AllTargets); Assert.Equal(System.Text.Encoding.UTF8, (config.AllTargets[0] as NLog.Targets.FileTarget)?.Encoding); } [Fact] public void XmlConfig_ParseFilter_WithoutAttributes() { // Arrange var xml = @"<nlog> <targets> <target name='debug' type='Debug' layout='${message}' /> </targets> <rules> <logger name='*' minlevel='debug' appendto='debug' filterDefaultAction='ignore'> <filters defaultAction='log'> <whenContains /> </filters> </logger> </rules> </nlog>"; var config = XmlLoggingConfiguration.CreateFromXmlString(xml); Assert.Single(config.LoggingRules); Assert.Single(config.LoggingRules[0].Filters); } [Theory] [InlineData("xsi", false)] [InlineData("test", false)] [InlineData("xsi", true)] [InlineData("test", true)] public void XmlConfig_attributes_shouldNotLogWarningsToInternalLog(string @namespace, bool nestedConfig) { // Arrange var xml = $@"<?xml version=""1.0"" encoding=""utf-8""?> {(nestedConfig ? "<configuration>" : "")} <nlog xmlns=""http://www.nlog-project.org/schemas/NLog.xsd"" xmlns:{@namespace}=""http://www.w3.org/2001/XMLSchema-instance"" {@namespace}:schemaLocation=""somewhere"" internalLogToConsole=""true"" internalLogLevel=""Warn""> </nlog> {(nestedConfig ? "</configuration>" : "")}"; try { TextWriter textWriter = new StringWriter(); InternalLogger.LogWriter = textWriter; InternalLogger.IncludeTimestamp = false; // Act XmlLoggingConfiguration.CreateFromXmlString(xml); // Assert InternalLogger.LogWriter.Flush(); var warning = textWriter.ToString(); Assert.Equal("", warning); } finally { // cleanup InternalLogger.LogWriter = null; } } [Fact] public void RulesBeforeTargetsTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <rules> <logger name='*' minLevel='Info' writeTo='d1' /> </rules> <targets> <target name='d1' type='Debug' /> </targets> </nlog>"); Assert.Equal(1, c.LoggingRules.Count); var rule = c.LoggingRules[0]; Assert.Equal("*", rule.LoggerNamePattern); Assert.Equal(4, rule.Levels.Count); Assert.Contains(LogLevel.Info, rule.Levels); Assert.Contains(LogLevel.Warn, rule.Levels); Assert.Contains(LogLevel.Error, rule.Levels); Assert.Contains(LogLevel.Fatal, rule.Levels); Assert.Equal(1, rule.Targets.Count); Assert.Same(c.FindTargetByName("d1"), rule.Targets[0]); Assert.False(rule.Final); Assert.Equal(0, rule.Filters.Count); } [Fact] public void LowerCaseParserTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='debug' layout='${level}' /></targets> <rules> <logger name='*' minlevel='info' appendto='debug'> <filters defaultAction='log'> <whencontains layout='${message}' substring='msg' action='ignore' /> </filters> </logger> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Fatal("message"); logFactory.AssertDebugLastMessage(nameof(LogLevel.Fatal)); logger.Error("message"); logFactory.AssertDebugLastMessage(nameof(LogLevel.Error)); logger.Warn("message"); logFactory.AssertDebugLastMessage(nameof(LogLevel.Warn)); logger.Info("message"); logFactory.AssertDebugLastMessage(nameof(LogLevel.Info)); logger.Debug("message"); logger.Debug("msg"); logger.Info("msg"); logger.Warn("msg"); logger.Error("msg"); logger.Fatal("msg"); logFactory.AssertDebugLastMessage(nameof(LogLevel.Info)); } [Fact] public void UpperCaseParserTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <TARGETS><TARGET NAME='DEBUG' TYPE='DEBUG' LAYOUT='${LEVEL}' /></TARGETS> <RULES> <LOGGER NAME='*' MINLEVEL='INFO' APPENDTO='DEBUG'> <FILTERS DEFAULTACTION='LOG'> <WHENCONTAINS LAYOUT='${MESSAGE}' SUBSTRING='msg' ACTION='IGNORE' /> </FILTERS> </LOGGER> </RULES> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); logger.Fatal("message"); logFactory.AssertDebugLastMessage(nameof(LogLevel.Fatal)); logger.Error("message"); logFactory.AssertDebugLastMessage(nameof(LogLevel.Error)); logger.Warn("message"); logFactory.AssertDebugLastMessage(nameof(LogLevel.Warn)); logger.Info("message"); logFactory.AssertDebugLastMessage(nameof(LogLevel.Info)); logger.Debug("message"); logger.Debug("msg"); logger.Info("msg"); logger.Warn("msg"); logger.Error("msg"); logger.Fatal("msg"); logFactory.AssertDebugLastMessage(nameof(LogLevel.Info)); } [Fact] public void ShouldWriteLogsOnDuplicateAttributeTest() { using (new NoThrowNLogExceptions()) { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='info' minLevel='info' appendto='debug'> <filters defaultAction='log'> <whencontains layout='${message}' substring='msg' action='ignore' /> </filters> </logger> </rules> </nlog>").LogFactory; var logger = logFactory.GetLogger("A"); string expectedMesssage = "some message"; logger.Info(expectedMesssage); logFactory.AssertDebugLastMessage(expectedMesssage); } } [Fact] public void ShoudThrowExceptionOnDuplicateAttributeWhenOptionIsEnabledTest() { Assert.Throws<NLogConfigurationException>(() => { new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets><target name='debug' type='debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='info' minLevel='info' appendto='debug'> <filters defaultAction='log'> <whencontains layout='${message}' substring='msg' action='ignore' /> </filters> </logger> </rules> </nlog>"); }); Assert.Throws<NLogConfigurationException>(() => { new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwConfigExceptions='true'> <targets><target name='debug' type='debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='info' minLevel='info' appendto='debug'> <filters defaultAction='log'> <whencontains layout='${message}' substring='msg' action='ignore' /> </filters> </logger> </rules> </nlog>"); }); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; using NLog.Internal; namespace NLog.Targets { /// <summary> /// Default class for serialization of values to JSON format. /// </summary> public class DefaultJsonSerializer : IJsonConverter { private readonly ObjectReflectionCache _objectReflectionCache; private readonly MruCache<Enum, string> _enumCache = new MruCache<Enum, string>(2000); private const int MaxJsonLength = 512 * 1024; private static readonly IEqualityComparer<object> _referenceEqualsComparer = SingleItemOptimizedHashSet<object>.ReferenceEqualityComparer.Default; private static JsonSerializeOptions DefaultSerializerOptions = new JsonSerializeOptions(); private static JsonSerializeOptions DefaultExceptionSerializerOptions = new JsonSerializeOptions() { SanitizeDictionaryKeys = true }; /// <summary> /// Singleton instance of the serializer. /// </summary> [Obsolete("Instead use ResolveService<IJsonConverter>() in Layout / Target. Marked obsolete on NLog 5.0")] public static DefaultJsonSerializer Instance { get; } = new DefaultJsonSerializer(null); /// <summary> /// Private. Use <see cref="Instance"/> /// </summary> internal DefaultJsonSerializer(IServiceProvider serviceProvider) { _objectReflectionCache = new ObjectReflectionCache(serviceProvider); } /// <summary> /// Returns a serialization of an object into JSON format. /// </summary> /// <param name="value">The object to serialize to JSON.</param> /// <returns>Serialized value.</returns> public string SerializeObject(object value) { return SerializeObject(value, DefaultSerializerOptions); } /// <summary> /// Returns a serialization of an object into JSON format. /// </summary> /// <param name="value">The object to serialize to JSON.</param> /// <param name="options">serialization options</param> /// <returns>Serialized value.</returns> public string SerializeObject(object value, JsonSerializeOptions options) { if (value is null) { return "null"; } else if (value is string str) { for (int i = 0; i < str.Length; ++i) { if (RequiresJsonEscape(str[i], options.EscapeUnicode, options.EscapeForwardSlash)) { StringBuilder sb = new StringBuilder(str.Length + 4); sb.Append('"'); AppendStringEscape(sb, str, options); sb.Append('"'); return sb.ToString(); } } return QuoteValue(str); } else { IConvertible convertibleValue = value as IConvertible; TypeCode objTypeCode = convertibleValue?.GetTypeCode() ?? TypeCode.Object; if (objTypeCode != TypeCode.Object && objTypeCode != TypeCode.Char) { Enum enumValue; if (!options.EnumAsInteger && IsNumericTypeCode(objTypeCode, false) && (enumValue = value as Enum) != null) { return QuoteValue(EnumAsString(enumValue)); } else { string xmlStr = XmlHelper.XmlConvertToString(convertibleValue, objTypeCode); if (SkipQuotes(convertibleValue, objTypeCode)) { return xmlStr; } else { return QuoteValue(xmlStr); } } } else { StringBuilder sb = new StringBuilder(); if (!SerializeObject(value, sb, options)) { return null; } return sb.ToString(); } } } /// <summary> /// Serialization of the object in JSON format to the destination StringBuilder /// </summary> /// <param name="value">The object to serialize to JSON.</param> /// <param name="destination">Write the resulting JSON to this destination.</param> /// <returns>Object serialized successfully (true/false).</returns> public bool SerializeObject(object value, StringBuilder destination) { return SerializeObject(value, destination, DefaultSerializerOptions); } /// <summary> /// Serialization of the object in JSON format to the destination StringBuilder /// </summary> /// <param name="value">The object to serialize to JSON.</param> /// <param name="destination">Write the resulting JSON to this destination.</param> /// <param name="options">serialization options</param> /// <returns>Object serialized successfully (true/false).</returns> public bool SerializeObject(object value, StringBuilder destination, JsonSerializeOptions options) { return SerializeObject(value, destination, options, default(SingleItemOptimizedHashSet<object>), 0); } /// <summary> /// Serialization of the object in JSON format to the destination StringBuilder /// </summary> /// <param name="value">The object to serialize to JSON.</param> /// <param name="destination">Write the resulting JSON to this destination.</param> /// <param name="options">serialization options</param> /// <param name="objectsInPath">The objects in path (Avoid cyclic reference loop).</param> /// <param name="depth">The current depth (level) of recursion.</param> /// <returns>Object serialized successfully (true/false).</returns> private bool SerializeObject(object value, StringBuilder destination, JsonSerializeOptions options, SingleItemOptimizedHashSet<object> objectsInPath, int depth) { int originalLength = destination.Length; try { if (SerializeSimpleObjectValue(value, destination, options)) { return true; } return SerializeObjectWithReflection(value, destination, options, ref objectsInPath, depth); } catch { destination.Length = originalLength; return false; } } private bool SerializeObjectWithReflection(object value, StringBuilder destination, JsonSerializeOptions options, ref SingleItemOptimizedHashSet<object> objectsInPath, int depth) { int originalLength = destination.Length; if (originalLength > MaxJsonLength) { return false; } if (objectsInPath.Contains(value)) { return false; } if (value is IDictionary dict) { using (StartCollectionScope(ref objectsInPath, dict)) { SerializeDictionaryObject(dict, destination, options, objectsInPath, depth); return true; } } if (value is IEnumerable enumerable) { if (_objectReflectionCache.TryLookupExpandoObject(value, out var objectPropertyList)) { return SerializeObjectPropertyList(value, ref objectPropertyList, destination, options, ref objectsInPath, depth); } else { using (StartCollectionScope(ref objectsInPath, value)) { SerializeCollectionObject(enumerable, destination, options, objectsInPath, depth); return true; } } } else { var objectPropertyList = _objectReflectionCache.LookupObjectProperties(value); return SerializeObjectPropertyList(value, ref objectPropertyList, destination, options, ref objectsInPath, depth); } } private bool SerializeSimpleObjectValue(object value, StringBuilder destination, JsonSerializeOptions options, bool forceToString = false) { var convertibleValue = value as IConvertible; var objTypeCode = convertibleValue?.GetTypeCode() ?? (value is null ? TypeCode.Empty : TypeCode.Object); if (objTypeCode != TypeCode.Object) { SerializeSimpleTypeCodeValue(convertibleValue, objTypeCode, destination, options, forceToString); return true; } if (value is IFormattable formattable) { if (value is DateTimeOffset dateTimeOffset) { QuoteValue(destination, dateTimeOffset.ToString("yyyy-MM-dd HH:mm:ss zzz", CultureInfo.InvariantCulture)); return true; } destination.Append('"'); #if NETSTANDARD int startPos = destination.Length; destination.AppendFormat(CultureInfo.InvariantCulture, "{0}", formattable); // Support ISpanFormattable PerformJsonEscapeWhenNeeded(destination, startPos, options.EscapeUnicode, options.EscapeForwardSlash); #else var str = formattable.ToString(null, CultureInfo.InvariantCulture); AppendStringEscape(destination, str, options); #endif destination.Append('"'); return true; } return false; // Not simple } private static SingleItemOptimizedHashSet<object>.SingleItemScopedInsert StartCollectionScope(ref SingleItemOptimizedHashSet<object> objectsInPath, object value) { return new SingleItemOptimizedHashSet<object>.SingleItemScopedInsert(value, ref objectsInPath, true, _referenceEqualsComparer); } private void SerializeDictionaryObject(IDictionary dictionary, StringBuilder destination, JsonSerializeOptions options, SingleItemOptimizedHashSet<object> objectsInPath, int depth) { bool first = true; int nextDepth = objectsInPath.Count <= 1 ? depth : (depth + 1); if (nextDepth > options.MaxRecursionLimit) { destination.Append("{}"); return; } destination.Append('{'); foreach (var item in new DictionaryEntryEnumerable(dictionary)) { var originalLength = destination.Length; if (originalLength > MaxJsonLength) { break; } if (!first) { destination.Append(','); } var itemKey = item.Key; if (!SerializeObjectAsString(itemKey, destination, options)) { destination.Length = originalLength; continue; } if (options.SanitizeDictionaryKeys) { int keyEndIndex = destination.Length - 1; int keyStartIndex = originalLength + (first ? 0 : 1) + 1; if (!SanitizeDictionaryKey(destination, keyStartIndex, keyEndIndex - keyStartIndex)) { destination.Length = originalLength; // Empty keys are not allowed continue; } } destination.Append(':'); //only serialize, if key and value are serialized without error (e.g. due to reference loop) var itemValue = item.Value; if (!SerializeObject(itemValue, destination, options, objectsInPath, nextDepth)) { destination.Length = originalLength; } else { first = false; } } destination.Append('}'); } private static bool SanitizeDictionaryKey(StringBuilder destination, int keyStartIndex, int keyLength) { if (keyLength == 0) { return false; // Empty keys are not allowed } int keyEndIndex = keyStartIndex + keyLength; for (int i = keyStartIndex; i < keyEndIndex; ++i) { char keyChar = destination[i]; if (keyChar == '_' || char.IsLetterOrDigit(keyChar)) continue; destination[i] = '_'; } return true; } private void SerializeCollectionObject(IEnumerable value, StringBuilder destination, JsonSerializeOptions options, SingleItemOptimizedHashSet<object> objectsInPath, int depth) { bool first = true; int nextDepth = objectsInPath.Count <= 1 ? depth : (depth + 1); // Allow serialization of list-items if (nextDepth > options.MaxRecursionLimit) { destination.Append("[]"); return; } int originalLength; destination.Append('['); foreach (var val in value) { originalLength = destination.Length; if (originalLength > MaxJsonLength) { break; } if (!first) { destination.Append(','); } if (!SerializeObject(val, destination, options, objectsInPath, nextDepth)) { destination.Length = originalLength; } else { first = false; } } destination.Append(']'); } private bool SerializeObjectPropertyList(object value, ref ObjectReflectionCache.ObjectPropertyList objectPropertyList, StringBuilder destination, JsonSerializeOptions options, ref SingleItemOptimizedHashSet<object> objectsInPath, int depth) { if (objectPropertyList.IsSimpleValue) { value = objectPropertyList.ObjectValue; if (SerializeSimpleObjectValue(value, destination, options)) { return true; } } else if (depth < options.MaxRecursionLimit) { if (ReferenceEquals(options, DefaultSerializerOptions) && value is Exception) { // Exceptions are seldom under control, and can include random Data-Dictionary-keys, so we sanitize by default options = DefaultExceptionSerializerOptions; } using (new SingleItemOptimizedHashSet<object>.SingleItemScopedInsert(value, ref objectsInPath, false, _referenceEqualsComparer)) { return SerializeObjectProperties(objectPropertyList, destination, options, objectsInPath, depth); } } return SerializeObjectAsString(value, destination, options); } private void SerializeSimpleTypeCodeValue(IConvertible value, TypeCode objTypeCode, StringBuilder destination, JsonSerializeOptions options, bool forceToString = false) { if (objTypeCode == TypeCode.Empty || value is null) { destination.Append(forceToString ? "\"\"" : "null"); } else if (objTypeCode == TypeCode.String || objTypeCode == TypeCode.Char) { destination.Append('"'); AppendStringEscape(destination, value.ToString(), options); destination.Append('"'); } else { SerializeSimpleTypeCodeValueNoEscape(value, objTypeCode, destination, options, forceToString); } } private void SerializeSimpleTypeCodeValueNoEscape(IConvertible value, TypeCode objTypeCode, StringBuilder destination, JsonSerializeOptions options, bool forceToString) { if (IsNumericTypeCode(objTypeCode, false)) { if (!options.EnumAsInteger && value is Enum enumValue) { QuoteValue(destination, EnumAsString(enumValue)); } else { SerializeNumericValue(value, objTypeCode, destination, forceToString); } } else if (objTypeCode == TypeCode.DateTime) { destination.Append('"'); destination.AppendXmlDateTimeUtcRoundTrip(value.ToDateTime(CultureInfo.InvariantCulture)); destination.Append('"'); } else if (IsNumericTypeCode(objTypeCode, true) && SkipQuotes(value, objTypeCode)) { SerializeNumericValue(value, objTypeCode, destination, forceToString); } else { string str = XmlHelper.XmlConvertToString(value, objTypeCode); if (!forceToString && !string.IsNullOrEmpty(str) && SkipQuotes(value, objTypeCode)) { destination.Append(str); } else { QuoteValue(destination, str); } } } private void SerializeNumericValue(IConvertible value, TypeCode objTypeCode, StringBuilder destination, bool forceToString) { if (forceToString) destination.Append('"'); destination.AppendNumericInvariant(value, objTypeCode); if (forceToString) destination.Append('"'); } private static string QuoteValue(string value) { return string.Concat("\"", value, "\""); } private static void QuoteValue(StringBuilder destination, string value) { destination.Append('"'); destination.Append(value); destination.Append('"'); } private string EnumAsString(Enum value) { string textValue; if (!_enumCache.TryGetValue(value, out textValue)) { textValue = Convert.ToString(value, CultureInfo.InvariantCulture); _enumCache.TryAddValue(value, textValue); } return textValue; } /// <summary> /// No quotes needed for this type? /// </summary> private static bool SkipQuotes(IConvertible value, TypeCode objTypeCode) { switch (objTypeCode) { case TypeCode.String: return false; case TypeCode.Char: return false; case TypeCode.DateTime: return false; case TypeCode.Empty: return true; case TypeCode.Boolean: return true; case TypeCode.Decimal: return true; case TypeCode.Double: { double dblValue = value.ToDouble(CultureInfo.InvariantCulture); return !double.IsNaN(dblValue) && !double.IsInfinity(dblValue); } case TypeCode.Single: { float floatValue = value.ToSingle(CultureInfo.InvariantCulture); return !float.IsNaN(floatValue) && !float.IsInfinity(floatValue); } default: return IsNumericTypeCode(objTypeCode, false); } } /// <summary> /// Checks the object <see cref="TypeCode" /> if it is numeric /// </summary> /// <param name="objTypeCode">TypeCode for the object</param> /// <param name="includeDecimals">Accept fractional types as numeric type.</param> /// <returns></returns> private static bool IsNumericTypeCode(TypeCode objTypeCode, bool includeDecimals) { switch (objTypeCode) { case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return true; case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return includeDecimals; } return false; } /// <summary> /// Checks input string if it needs JSON escaping, and makes necessary conversion /// </summary> /// <param name="destination">Destination Builder</param> /// <param name="text">Input string</param> /// <param name="options">all options</param> /// <returns>JSON escaped string</returns> private static void AppendStringEscape(StringBuilder destination, string text, JsonSerializeOptions options) { AppendStringEscape(destination, text, options.EscapeUnicode, options.EscapeForwardSlash); } /// <summary> /// Checks input string if it needs JSON escaping, and makes necessary conversion /// </summary> /// <param name="destination">Destination Builder</param> /// <param name="text">Input string</param> /// <param name="escapeUnicode">Should non-ASCII characters be encoded</param> /// <param name="escapeForwardSlash"></param> /// <returns>JSON escaped string</returns> internal static void AppendStringEscape(StringBuilder destination, string text, bool escapeUnicode, bool escapeForwardSlash) { if (string.IsNullOrEmpty(text)) return; int i = 0; for (; i < text.Length; ++i) { if (RequiresJsonEscape(text[i], escapeUnicode, escapeForwardSlash)) { destination.Append(text, 0, i); break; } } if (i == text.Length) { destination.Append(text); return; } for (; i < text.Length; ++i) { char ch = text[i]; if (!RequiresJsonEscape(ch, escapeUnicode, escapeForwardSlash)) { destination.Append(ch); continue; } switch (ch) { case '"': destination.Append("\\\""); break; case '\\': destination.Append("\\\\"); break; case '\b': destination.Append("\\b"); break; case '/': if (escapeForwardSlash) { destination.Append("\\/"); } else { destination.Append(ch); } break; case '\r': destination.Append("\\r"); break; case '\n': destination.Append("\\n"); break; case '\f': destination.Append("\\f"); break; case '\t': destination.Append("\\t"); break; default: destination.AppendFormat(CultureInfo.InvariantCulture, "\\u{0:x4}", (int)ch); break; } } } internal static void PerformJsonEscapeWhenNeeded(StringBuilder builder, int startPos, bool escapeUnicode, bool escapeForwardSlash) { var builderLength = builder.Length; for (int i = startPos; i < builderLength; ++i) { if (RequiresJsonEscape(builder[i], escapeUnicode, escapeForwardSlash)) { var str = builder.ToString(startPos, builder.Length - startPos); builder.Length = startPos; Targets.DefaultJsonSerializer.AppendStringEscape(builder, str, escapeUnicode, escapeForwardSlash); break; } } } internal static bool RequiresJsonEscape(char ch, bool escapeUnicode, bool escapeForwardSlash) { if (ch < 32) return true; if (ch > 127) return escapeUnicode; if (ch == '/') return escapeForwardSlash; return ch == '"' || ch == '\\'; } private bool SerializeObjectProperties(ObjectReflectionCache.ObjectPropertyList objectPropertyList, StringBuilder destination, JsonSerializeOptions options, SingleItemOptimizedHashSet<object> objectsInPath, int depth) { destination.Append('{'); bool first = true; foreach (var propertyValue in objectPropertyList) { var originalLength = destination.Length; try { if (!propertyValue.HasNameAndValue) continue; if (!first) { destination.Append(", "); } QuoteValue(destination, propertyValue.Name); destination.Append(':'); var objTypeCode = propertyValue.TypeCode; if (objTypeCode != TypeCode.Object) { SerializeSimpleTypeCodeValue((IConvertible)propertyValue.Value, objTypeCode, destination, options); first = false; } else { if (!SerializeObject(propertyValue.Value, destination, options, objectsInPath, depth + 1)) { destination.Length = originalLength; } else { first = false; } } } catch { // skip single property destination.Length = originalLength; } } destination.Append('}'); return true; } private bool SerializeObjectAsString(object value, StringBuilder destination, JsonSerializeOptions options) { var originalLength = destination.Length; try { if (SerializeSimpleObjectValue(value, destination, options, true)) { return true; } var str = Convert.ToString(value, CultureInfo.InvariantCulture); destination.Append('"'); AppendStringEscape(destination, str, options); destination.Append('"'); return true; } catch { // skip bad object destination.Length = originalLength; return false; } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LayoutRenderers { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Threading; using System.Xml; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using Xunit; public class Log4JXmlTests : NLogTestBase { [Fact] public void Log4JXmlTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout='${log4jxmlevent:includeCallSite=true:includeSourceInfo=true:includeNdlc=true:includeMdc=true:IncludeNdc=true:includeMdlc=true:IncludeAllProperties=true:ndcItemSeparator=\:\::includenlogdata=true:loggerName=${logger}}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; ScopeContext.Clear(); ScopeContext.PushProperty("foo1", "bar1"); ScopeContext.PushProperty("foo2", "bar2"); ScopeContext.PushProperty("foo3", "bar3"); ScopeContext.PushNestedState("baz1"); ScopeContext.PushNestedState("baz2"); ScopeContext.PushNestedState("baz3"); var logger = logFactory.GetLogger("A"); var logEventInfo = LogEventInfo.Create(LogLevel.Debug, "A", new Exception("Hello Exception", new Exception("Goodbye Exception")), null, "some message \u0014"); logEventInfo.Properties["nlogPropertyKey"] = "nlogPropertyValue"; logger.Log(logEventInfo); string result = GetDebugLastMessage("debug", logFactory); Assert.DoesNotContain("dummy", result); string wrappedResult = "<log4j:dummyRoot xmlns:log4j='http://log4j' xmlns:nlog='http://nlog'>" + result + "</log4j:dummyRoot>"; Assert.NotEqual("", result); // make sure the XML can be read back and verify some fields StringReader stringReader = new StringReader(wrappedResult); var foundsChilds = new Dictionary<string, int>(); var requiredChilds = new List<string> { "log4j.event", "log4j.message", "log4j.NDC", "log4j.locationInfo", "nlog.locationInfo", "log4j.properties", "nlog.properties", "log4j.throwable", "log4j.data", "nlog.data", }; using (XmlReader reader = XmlReader.Create(stringReader)) { while (reader.Read()) { var key = reader.LocalName; var fullKey = reader.Prefix + "." + key; if (!foundsChilds.ContainsKey(fullKey)) { foundsChilds[fullKey] = 0; } foundsChilds[fullKey]++; if (reader.NodeType == XmlNodeType.Element && reader.Prefix == "log4j") { switch (reader.LocalName) { case "dummyRoot": break; case "event": Assert.Equal("DEBUG", reader.GetAttribute("level")); Assert.Equal("A", reader.GetAttribute("logger")); var epochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); long timestamp = Convert.ToInt64(reader.GetAttribute("timestamp")); var time = epochStart.AddMilliseconds(timestamp); var now = DateTime.UtcNow; Assert.True(now.Ticks - time.Ticks < TimeSpan.FromSeconds(3).Ticks); Assert.Equal(Thread.CurrentThread.ManagedThreadId.ToString(), reader.GetAttribute("thread")); break; case "message": reader.Read(); Assert.Equal("some message ", reader.Value); break; case "NDC": reader.Read(); Assert.Equal("baz1::baz2::baz3", reader.Value); break; case "locationInfo": Assert.Equal(MethodBase.GetCurrentMethod().DeclaringType.FullName, reader.GetAttribute("class")); Assert.Equal(MethodBase.GetCurrentMethod().ToString(), reader.GetAttribute("method")); break; case "properties": break; case "throwable": reader.Read(); Assert.Contains("Hello Exception", reader.Value); Assert.Contains("Goodbye Exception", reader.Value); break; case "data": string name = reader.GetAttribute("name"); string value = reader.GetAttribute("value"); switch (name) { case "log4japp": Assert.Equal(AppDomain.CurrentDomain.FriendlyName + "(" + Process.GetCurrentProcess().Id + ")", value); break; case "log4jmachinename": Assert.Equal(Environment.MachineName, value); break; case "foo1": Assert.Equal("bar1", value); break; case "foo2": Assert.Equal("bar2", value); break; case "foo3": Assert.Equal("bar3", value); break; case "nlogPropertyKey": Assert.Equal("nlogPropertyValue", value); break; default: Assert.True(false, "Unknown <log4j:data>: " + name); break; } break; default: throw new NotSupportedException("Unknown element: " + key); } continue; } if (reader.NodeType == XmlNodeType.Element && reader.Prefix == "nlog") { switch (key) { case "eventSequenceNumber": break; case "locationInfo": Assert.Equal(GetType().Assembly.FullName, reader.GetAttribute("assembly")); break; case "properties": break; case "data": var name = reader.GetAttribute("name"); var value = reader.GetAttribute("value"); Assert.Equal("nlogPropertyKey", name); Assert.Equal("nlogPropertyValue", value); break; default: throw new NotSupportedException("Unknown element: " + key); } } } } foreach (var required in requiredChilds) { Assert.True(foundsChilds.ContainsKey(required), $"{required} not found!"); } } [Fact] public void Log4JXmlEventLayoutParameterTest() { var log4jLayout = new Log4JXmlEventLayout() { Parameters = { new NLogViewerParameterInfo { Name = "mt", Layout = "${message:raw=true}", } }, }; log4jLayout.Renderer.AppInfo = "MyApp"; var logEventInfo = new LogEventInfo { LoggerName = "MyLOgger", TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56, DateTimeKind.Utc), Level = LogLevel.Info, Message = "hello, <{0}>", Parameters = new[] { "world" }, }; var threadid = Environment.CurrentManagedThreadId; var machinename = Environment.MachineName; Assert.Equal($"<log4j:event logger=\"MyLOgger\" level=\"INFO\" timestamp=\"1262349296000\" thread=\"{threadid}\"><log4j:message>hello, &lt;world&gt;</log4j:message><log4j:properties><log4j:data name=\"mt\" value=\"hello, &lt;{{0}}&gt;\" /><log4j:data name=\"log4japp\" value=\"MyApp\" /><log4j:data name=\"log4jmachinename\" value=\"{machinename}\" /></log4j:properties></log4j:event>", log4jLayout.Render(logEventInfo)); } [Fact] public void BadXmlValueTest() { var sb = new System.Text.StringBuilder(); var forbidden = new HashSet<int>(); int start = 64976; int end = 65007; for (int i = start; i <= end; i++) { forbidden.Add(i); } forbidden.Add(0xFFFE); forbidden.Add(0xFFFF); for (int i = char.MinValue; i <= char.MaxValue; i++) { char c = Convert.ToChar(i); if (char.IsSurrogate(c)) { continue; // skip surrogates } if (forbidden.Contains(c)) { continue; } sb.Append(c); } var badString = sb.ToString(); var settings = new XmlWriterSettings { Indent = true, ConformanceLevel = ConformanceLevel.Fragment, IndentChars = " ", }; sb.Length = 0; using (XmlWriter xtw = XmlWriter.Create(sb, settings)) { xtw.WriteStartElement("log4j", "event", "http:://hello/"); xtw.WriteElementSafeString("log4j", "message", "http:://hello/", badString); xtw.WriteEndElement(); xtw.Flush(); } string goodString = null; using (XmlReader reader = XmlReader.Create(new StringReader(sb.ToString()))) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Text) { if (reader.Value.Contains("abc")) goodString = reader.Value; } } } Assert.NotNull(goodString); Assert.NotEqual(badString.Length, goodString.Length); Assert.Contains("abc", badString); Assert.Contains("abc", goodString); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using System.Collections.Generic; using System.Threading; using NLog.Common; /// <summary> /// Provides fallback-on-error. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/FallbackGroup-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/FallbackGroup-target">Documentation on NLog Wiki</seealso> /// <example> /// <p>This example causes the messages to be written to server1, /// and if it fails, messages go to server2.</p> /// <p> /// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/FallbackGroup/NLog.config" /> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/FallbackGroup/Simple/Example.cs" /> /// </example> [Target("FallbackGroup", IsCompound = true)] public class FallbackGroupTarget : CompoundTargetBase { private long _currentTarget; /// <summary> /// Initializes a new instance of the <see cref="FallbackGroupTarget"/> class. /// </summary> public FallbackGroupTarget() : this(NLog.Internal.ArrayHelper.Empty<Target>()) { } /// <summary> /// Initializes a new instance of the <see cref="FallbackGroupTarget"/> class. /// </summary> /// <param name="name">Name of the target.</param> /// <param name="targets">The targets.</param> public FallbackGroupTarget(string name, params Target[] targets) : this(targets) { Name = name; } /// <summary> /// Initializes a new instance of the <see cref="FallbackGroupTarget" /> class. /// </summary> /// <param name="targets">The targets.</param> public FallbackGroupTarget(params Target[] targets) : base(targets) { } /// <summary> /// Gets or sets a value indicating whether to return to the first target after any successful write. /// </summary> /// <docgen category='Fallback Options' order='10' /> public bool ReturnToFirstOnSuccess { get; set; } /// <summary> /// Gets or sets whether to enable batching, but fallback will be handled individually /// </summary> /// <docgen category='Fallback Options' order='50' /> public bool EnableBatchWrite { get; set; } = true; /// <summary> /// Forwards the log event to the sub-targets until one of them succeeds. /// </summary> /// <param name="logEvents">The log event.</param> protected override void WriteAsyncThreadSafe(IList<AsyncLogEventInfo> logEvents) { if (logEvents.Count == 1) { WriteAsyncThreadSafe(logEvents[0]); } else if (EnableBatchWrite) { var targetToInvoke = (int)Interlocked.Read(ref _currentTarget); for (int i = 0; i < logEvents.Count; ++i) { logEvents[i] = WrapWithFallback(logEvents[i], targetToInvoke); } Targets[targetToInvoke].WriteAsyncLogEvents(logEvents); } else { for (int i = 0; i < logEvents.Count; ++i) { WriteAsyncThreadSafe(logEvents[i]); } } } /// <inheritdoc/> protected override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { Write(logEvent); } /// <summary> /// Forwards the log event to the sub-targets until one of them succeeds. /// </summary> protected override void Write(AsyncLogEventInfo logEvent) { var targetToInvoke = (int)Interlocked.Read(ref _currentTarget); var result = WrapWithFallback(logEvent, targetToInvoke); Targets[targetToInvoke].WriteAsyncLogEvent(result); } private AsyncLogEventInfo WrapWithFallback(AsyncLogEventInfo logEvent, int targetToInvoke) { for (int i = 0; i < Targets.Count; ++i) { if (i != targetToInvoke) { Targets[i].PrecalculateVolatileLayouts(logEvent.LogEvent); } } AsyncContinuation continuation = null; int tryCounter = 0; continuation = ex => { if (ex is null) { // success if (ReturnToFirstOnSuccess && Interlocked.Read(ref _currentTarget) != 0) { InternalLogger.Debug("{0}: Target '{1}' succeeded. Returning to the first one.", this, Targets[targetToInvoke]); Interlocked.Exchange(ref _currentTarget, 0); } logEvent.Continuation(null); return; } // error while writing, fallback to next one tryCounter++; int nextTarget = (targetToInvoke + 1) % Targets.Count; Interlocked.CompareExchange(ref _currentTarget, nextTarget, targetToInvoke); if (tryCounter < Targets.Count) { InternalLogger.Warn(ex, "{0}: Target '{1}' failed. Fallback to next: `{2}`", this, Targets[targetToInvoke], Targets[nextTarget]); targetToInvoke = nextTarget; Targets[targetToInvoke].WriteAsyncLogEvent(logEvent.LogEvent.WithContinuation(continuation)); } else { InternalLogger.Warn(ex, "{0}: Target '{1}' failed. Fallback not possible", this, Targets[targetToInvoke]); logEvent.Continuation(ex); } }; return logEvent.LogEvent.WithContinuation(continuation); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Common; using Xunit; namespace NLog.UnitTests.Internal { public class AsyncLogEventInfoTests : NLogTestBase { [Fact] public void TestEquals() { var logEvent1 = new LogEventInfo(LogLevel.Debug, "logger1", "message1"); AsyncContinuation cont1 = new AsyncContinuation(exception => { }); var async1 = new AsyncLogEventInfo(logEvent1, cont1); var async2 = new AsyncLogEventInfo(logEvent1, cont1); Assert.True(async1.Equals(async2)); Assert.True(async1 == async2); Assert.False(async1 != async2); Assert.Equal(async1.GetHashCode(), async2.GetHashCode()); } [Fact] public void TestNotEquals() { var logEvent1 = new LogEventInfo(LogLevel.Debug, "logger1", "message1"); AsyncContinuation cont1 = new AsyncContinuation(exception => { }); AsyncContinuation cont2 = new AsyncContinuation(exception => { InternalLogger.Debug("test"); }); var async1 = new AsyncLogEventInfo(logEvent1, cont1); var async2 = new AsyncLogEventInfo(logEvent1, cont2); Assert.False(async1.Equals(async2)); Assert.False(async1 == async2); Assert.True(async1 != async2); //2 delegates will return the same hashcode, https://stackoverflow.com/questions/6624151/why-do-2-delegate-instances-return-the-same-hashcode //and that isn't really bad, so ignore this // Assert.NotEqual(async1.GetHashCode(), async2.GetHashCode()); } [Fact] public void TestNotEquals2() { var logEvent1 = new LogEventInfo(LogLevel.Debug, "logger1", "message1"); var logEvent2 = new LogEventInfo(LogLevel.Debug, "logger1", "message1"); AsyncContinuation cont = new AsyncContinuation(exception => { }); var async1 = new AsyncLogEventInfo(logEvent1, cont); var async2 = new AsyncLogEventInfo(logEvent2, cont); Assert.False(async1.Equals(async2)); Assert.False(async1 == async2); Assert.True(async1 != async2); Assert.NotEqual(async1.GetHashCode(), async2.GetHashCode()); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using NLog.Common; namespace NLog.Targets.FileArchiveModes { static class FileArchiveModeFactory { public static IFileArchiveMode CreateArchiveStyle(string archiveFilePath, ArchiveNumberingMode archiveNumbering, string dateFormat, bool customArchiveFileName, bool archiveCleanupEnabled) { if (ContainsFileNamePattern(archiveFilePath)) { IFileArchiveMode archiveHelper = CreateStrictFileArchiveMode(archiveNumbering, dateFormat, archiveCleanupEnabled); if (archiveHelper != null) return archiveHelper; } if (archiveNumbering != ArchiveNumberingMode.Sequence) { if (!customArchiveFileName) { IFileArchiveMode archiveHelper = CreateStrictFileArchiveMode(archiveNumbering, dateFormat, archiveCleanupEnabled); if (archiveHelper != null) return new FileArchiveModeDynamicTemplate(archiveHelper); } else { InternalLogger.Info("FileTarget: Pattern {{#}} is missing in ArchiveFileName `{0}` (Fallback to dynamic wildcard)", archiveFilePath); } } return new FileArchiveModeDynamicSequence(archiveNumbering, dateFormat, customArchiveFileName, archiveCleanupEnabled); } private static IFileArchiveMode CreateStrictFileArchiveMode(ArchiveNumberingMode archiveNumbering, string dateFormat, bool archiveCleanupEnabled) { switch (archiveNumbering) { case ArchiveNumberingMode.Rolling: return new FileArchiveModeRolling(); case ArchiveNumberingMode.Sequence: return new FileArchiveModeSequence(dateFormat, archiveCleanupEnabled); case ArchiveNumberingMode.Date: return new FileArchiveModeDate(dateFormat, archiveCleanupEnabled); case ArchiveNumberingMode.DateAndSequence: return new FileArchiveModeDateAndSequence(dateFormat, archiveCleanupEnabled); } return null; } /// <summary> /// Determines if the file name as <see cref="String"/> contains a numeric pattern i.e. {#} in it. /// /// Example: /// trace{#}.log Contains the numeric pattern. /// trace{###}.log Contains the numeric pattern. /// trace{#X#}.log Contains the numeric pattern (See remarks). /// trace.log Does not contain the pattern. /// </summary> /// <remarks>Occasionally, this method can identify the existence of the {#} pattern incorrectly.</remarks> /// <param name="fileName">File name to be checked.</param> /// <returns><see langword="true"/> when the pattern is found; <see langword="false"/> otherwise.</returns> public static bool ContainsFileNamePattern(string fileName) { int startingIndex = fileName.IndexOf("{#", StringComparison.Ordinal); int endingIndex = fileName.IndexOf("#}", StringComparison.Ordinal); return (startingIndex != -1 && endingIndex != -1 && startingIndex < endingIndex); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal.NetworkSenders { using System; /// <summary> /// Network sender which uses HTTP or HTTPS POST. /// </summary> internal class HttpNetworkSender : QueuedNetworkSender { private readonly Uri _addressUri; internal IWebRequestFactory HttpRequestFactory { get; set; } = WebRequestFactory.Instance; /// <summary> /// Initializes a new instance of the <see cref="HttpNetworkSender"/> class. /// </summary> /// <param name="url">The network URL.</param> public HttpNetworkSender(string url) : base(url) { _addressUri = new Uri(Address); } protected override void BeginRequest(NetworkRequestArgs eventArgs) { var asyncContinuation = eventArgs.AsyncContinuation; var bytes = eventArgs.RequestBuffer; var offset = eventArgs.RequestBufferOffset; var length = eventArgs.RequestBufferLength; var webRequest = HttpRequestFactory.CreateWebRequest(_addressUri); webRequest.Method = "POST"; AsyncCallback onResponse = r => { try { using (var response = webRequest.EndGetResponse(r)) { // Response successfully read } // completed fine CompleteRequest(asyncContinuation); } catch (Exception ex) { #if DEBUG if (ex.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } #endif CompleteRequest(_ => asyncContinuation(ex)); } }; AsyncCallback onRequestStream = r => { try { using (var stream = webRequest.EndGetRequestStream(r)) { stream.Write(bytes, offset, length); } webRequest.BeginGetResponse(onResponse, null); } catch (Exception ex) { #if DEBUG if (ex.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } #endif CompleteRequest(_ => asyncContinuation(ex)); } }; webRequest.BeginGetRequestStream(onRequestStream, null); } private void CompleteRequest(Common.AsyncContinuation asyncContinuation) { var nextRequest = base.EndRequest(asyncContinuation, null); // pendingException = null to keep sender alive if (nextRequest.HasValue) { BeginRequest(nextRequest.Value); } } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using NLog.Internal; namespace NLog.Targets.FileArchiveModes { /// <summary> /// Archives the log-files using the provided base-archive-filename. If the base-archive-filename causes /// duplicate archive filenames, then sequence-style is automatically enforced. /// /// Example: /// Base Filename trace.log /// Next Filename trace.0.log /// /// The most recent archive has the highest number. /// /// When the number of archive files exceed <see cref="FileTarget.MaxArchiveFiles"/> the obsolete archives are deleted. /// When the age of archive files exceed <see cref="FileTarget.MaxArchiveDays"/> the obsolete archives are deleted. /// </summary> internal sealed class FileArchiveModeDynamicSequence : FileArchiveModeBase { private readonly ArchiveNumberingMode _archiveNumbering; private readonly string _archiveDateFormat; private readonly bool _customArchiveFileName; public FileArchiveModeDynamicSequence(ArchiveNumberingMode archiveNumbering, string archiveDateFormat, bool customArchiveFileName, bool archiveCleanupEnabled) :base(archiveCleanupEnabled) { _archiveNumbering = archiveNumbering; _archiveDateFormat = archiveDateFormat; _customArchiveFileName = customArchiveFileName; } private static bool RemoveNonLetters(string fileName, int startPosition, StringBuilder sb, out int digitsRemoved) { digitsRemoved = 0; sb.ClearBuilder(); for (int i = 0; i < startPosition; i++) { sb.Append(fileName[i]); } bool? wildCardActive = null; for (int i = startPosition; i < fileName.Length; i++) { char nameChar = fileName[i]; if (char.IsDigit(nameChar)) { if (!wildCardActive.HasValue) { wildCardActive = true; digitsRemoved = 1; sb.Append('{'); sb.Append('#'); sb.Append('}'); } else if (!wildCardActive.Value) { sb.Append(nameChar); } else { ++digitsRemoved; } } else if (!char.IsLetter(nameChar)) { if (!wildCardActive.HasValue || !wildCardActive.Value) sb.Append(nameChar); } else { if (wildCardActive.HasValue) wildCardActive = false; sb.Append(nameChar); } } return wildCardActive.HasValue; } protected override FileNameTemplate GenerateFileNameTemplate(string archiveFilePath) { string currentFileName = Path.GetFileNameWithoutExtension(archiveFilePath); int digitsRemoved; // Find the most optimal location to place the wildcard-mask StringBuilder sb = new StringBuilder(); int optimalStartPosition = 0; int optimalLength = int.MaxValue; for (int i = 0; i < currentFileName.Length; i++) { if (!RemoveNonLetters(currentFileName, i, sb, out digitsRemoved) && i == 0) break; if (digitsRemoved <= 1) continue; if (sb.Length < optimalLength) { optimalStartPosition = i; optimalLength = sb.Length; } } RemoveNonLetters(currentFileName, optimalStartPosition, sb, out digitsRemoved); if (digitsRemoved <= 1) { sb.ClearBuilder(); sb.Append(currentFileName); } switch (_archiveNumbering) { case ArchiveNumberingMode.Sequence: case ArchiveNumberingMode.Rolling: case ArchiveNumberingMode.DateAndSequence: { // Force sequence-number into template (Just before extension) if (sb.Length < 3 || (sb[sb.Length - 3] != '{' && sb[sb.Length - 2] != '#' && sb[sb.Length - 1] != '}')) { if (digitsRemoved <= 1) { sb.Append('{'); sb.Append('#'); sb.Append('}'); } else { sb.Append('*'); } } } break; } sb.Append(Path.GetExtension(archiveFilePath)); return base.GenerateFileNameTemplate(sb.ToString()); } protected override DateAndSequenceArchive GenerateArchiveFileInfo(FileInfo archiveFile, FileNameTemplate fileTemplate) { if (fileTemplate?.EndAt > 0 && !FileNameMatchesTemplate(archiveFile.Name, fileTemplate)) { return null; } int sequenceNumber = ExtractArchiveNumberFromFileName(archiveFile.FullName); var creationTimeUtc = archiveFile.LookupValidFileCreationTimeUtc(); var creationTime = creationTimeUtc > DateTime.MinValue ? NLog.Time.TimeSource.Current.FromSystemTime(creationTimeUtc) : DateTime.MinValue; return new DateAndSequenceArchive(archiveFile.FullName, creationTime, _archiveDateFormat, sequenceNumber > 0 ? sequenceNumber : 0); } private static bool FileNameMatchesTemplate(string filename, FileNameTemplate fileTemplate) { int templatePos = 0; for (int i = 0; i < filename.Length; ++i) { char fileNameChar = filename[i]; if (templatePos >= fileTemplate.Template.Length) { if (char.IsLetter(fileNameChar)) return false; // reached end of template, but still letters break; } char templateChar; if (templatePos < fileTemplate.EndAt && i >= fileTemplate.BeginAt) { // Inside wildcard, skip validation of non-letters if (char.IsLetter(fileNameChar)) { templatePos = fileTemplate.EndAt; do { if (templatePos >= fileTemplate.Template.Length) return false; // reached end of template, but still letters templateChar = fileTemplate.Template[templatePos]; ++templatePos; } while (!char.IsLetter(templateChar)); } else { continue; } } else { templateChar = fileTemplate.Template[templatePos]; ++templatePos; } if (fileNameChar == templateChar || char.ToUpperInvariant(fileNameChar) == char.ToUpperInvariant(templateChar)) { continue; } if (templateChar == '*' && !char.IsLetter(fileNameChar)) { break; // Reached archive-seq-no, lets call it a day } return false; // filename is not matching file-template } return true; } private static int ExtractArchiveNumberFromFileName(string archiveFileName) { archiveFileName = Path.GetFileName(archiveFileName); int lastDotIdx = archiveFileName.LastIndexOf('.'); if (lastDotIdx == -1) return 0; int previousToLastDotIdx = archiveFileName.LastIndexOf('.', lastDotIdx - 1); string numberPart = previousToLastDotIdx == -1 ? archiveFileName.Substring(lastDotIdx + 1) : archiveFileName.Substring(previousToLastDotIdx + 1, lastDotIdx - previousToLastDotIdx - 1); int archiveNumber; return int.TryParse(numberPart, out archiveNumber) ? archiveNumber : 0; } public override DateAndSequenceArchive GenerateArchiveFileName(string archiveFilePath, DateTime archiveDate, List<DateAndSequenceArchive> existingArchiveFiles) { int nextSequenceNumber = GetStartSequenceNo() - 1; string initialFileName = Path.GetFileName(archiveFilePath); foreach (var existingFile in existingArchiveFiles) { string existingFileName = Path.GetFileName(existingFile.FileName); if (string.Equals(existingFileName, initialFileName, StringComparison.OrdinalIgnoreCase)) { nextSequenceNumber = Math.Max(nextSequenceNumber, existingFile.Sequence + GetStartSequenceNo()); } else { string existingExtension = Path.GetExtension(existingFileName); existingFileName = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(existingFileName)) + existingExtension; if (string.Equals(existingFileName, initialFileName, StringComparison.OrdinalIgnoreCase)) { nextSequenceNumber = Math.Max(nextSequenceNumber, existingFile.Sequence + 1); } } } archiveFilePath = Path.GetFullPath(archiveFilePath); // Rebuild to fix non-standard path-format if (nextSequenceNumber >= GetStartSequenceNo()) { archiveFilePath = Path.Combine(Path.GetDirectoryName(archiveFilePath), string.Concat(Path.GetFileNameWithoutExtension(initialFileName), ".", nextSequenceNumber.ToString(CultureInfo.InvariantCulture), Path.GetExtension(initialFileName))); } return new DateAndSequenceArchive(archiveFilePath, archiveDate, _archiveDateFormat, nextSequenceNumber); } private int GetStartSequenceNo() { // For historic reasons, then the sequence-number starts at 1, when having specified FileTarget.ArchiveFileName return _customArchiveFileName ? 1 : 0; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.IO; namespace NLog.Targets.FileArchiveModes { /// <summary> /// Dynamically converts a non-template archiveFilePath into a correct archiveFilePattern. /// Before called the original IFileArchiveMode, that has been wrapped by this /// </summary> internal sealed class FileArchiveModeDynamicTemplate : IFileArchiveMode { private readonly IFileArchiveMode _archiveHelper; public bool IsArchiveCleanupEnabled => _archiveHelper.IsArchiveCleanupEnabled; private static string CreateDynamicTemplate(string archiveFilePath) { string ext = Path.GetExtension(archiveFilePath); return Path.ChangeExtension(archiveFilePath, ".{#}" + ext); } public FileArchiveModeDynamicTemplate(IFileArchiveMode archiveHelper) { _archiveHelper = archiveHelper; } public bool AttemptCleanupOnInitializeFile(string archiveFilePath, int maxArchiveFiles, int maxArchiveDays) { return _archiveHelper.AttemptCleanupOnInitializeFile(archiveFilePath, maxArchiveFiles, maxArchiveDays); } public IEnumerable<DateAndSequenceArchive> CheckArchiveCleanup(string archiveFilePath, List<DateAndSequenceArchive> existingArchiveFiles, int maxArchiveFiles, int maxArchiveDays) { return _archiveHelper.CheckArchiveCleanup(CreateDynamicTemplate(archiveFilePath), existingArchiveFiles, maxArchiveFiles, maxArchiveDays); } public DateAndSequenceArchive GenerateArchiveFileName(string archiveFilePath, DateTime archiveDate, List<DateAndSequenceArchive> existingArchiveFiles) { return _archiveHelper.GenerateArchiveFileName(CreateDynamicTemplate(archiveFilePath), archiveDate, existingArchiveFiles); } public string GenerateFileNameMask(string archiveFilePath) { return _archiveHelper.GenerateFileNameMask(CreateDynamicTemplate(archiveFilePath)); } public List<DateAndSequenceArchive> GetExistingArchiveFiles(string archiveFilePath) { return _archiveHelper.GetExistingArchiveFiles(CreateDynamicTemplate(archiveFilePath)); } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Text; using NLog.Common; using NLog.Config; using NLog.Internal; /// <summary> /// The host name that the process is running on. /// </summary> [LayoutRenderer("hostname")] [AppDomainFixedOutput] [ThreadAgnostic] public class HostNameLayoutRenderer : LayoutRenderer { private string _hostName; /// <inheritdoc/> protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); try { _hostName = GetHostName(); if (string.IsNullOrEmpty(_hostName)) { InternalLogger.Info("HostName is not available."); } } catch (Exception exception) { InternalLogger.Error(exception, "Error getting host name."); if (exception.MustBeRethrown()) { throw; } _hostName = string.Empty; } } /// <summary> /// Gets the host name and falls back to computer name if not available /// </summary> private static string GetHostName() { return TryLookupValue(() => Environment.GetEnvironmentVariable("HOSTNAME"), "HOSTNAME") ?? TryLookupValue(() => System.Net.Dns.GetHostName(), "DnsHostName") #if !NETSTANDARD1_3 ?? TryLookupValue(() => Environment.MachineName, "MachineName") #endif ?? TryLookupValue(() => Environment.GetEnvironmentVariable("MACHINENAME"), "MachineName"); } /// <summary> /// Tries the lookup value. /// </summary> /// <param name="lookupFunc">The lookup function.</param> /// <param name="lookupType">Type of the lookup.</param> /// <returns></returns> private static string TryLookupValue(Func<string> lookupFunc, string lookupType) { try { string lookupValue = lookupFunc()?.Trim(); return string.IsNullOrEmpty(lookupValue) ? null : lookupValue; } catch (Exception ex) { InternalLogger.Warn(ex, "Failed to lookup {0}", lookupType); return null; } } /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(_hostName); } } }<file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 && !NETSTANDARD1_5 namespace NLog { using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Text; using System.Xml; using NLog.Internal; /// <summary> /// TraceListener which routes all messages through NLog. /// </summary> public class NLogTraceListener : TraceListener { private LogFactory _logFactory; private LogLevel _defaultLogLevel = LogLevel.Debug; private bool _attributesLoaded; private bool _autoLoggerName; private LogLevel _forceLogLevel; private bool _disableFlush; /// <summary> /// Initializes a new instance of the <see cref="NLogTraceListener"/> class. /// </summary> public NLogTraceListener() { } /// <summary> /// Gets or sets the log factory to use when outputting messages (null - use LogManager). /// </summary> public LogFactory LogFactory { get { InitAttributes(); return _logFactory; } set { _logFactory = value; _attributesLoaded = true; } } /// <summary> /// Gets or sets the default log level. /// </summary> public LogLevel DefaultLogLevel { get { InitAttributes(); return _defaultLogLevel; } set { _defaultLogLevel = value; _attributesLoaded = true; } } /// <summary> /// Gets or sets the log which should be always used regardless of source level. /// </summary> public LogLevel ForceLogLevel { get { InitAttributes(); return _forceLogLevel; } set { _forceLogLevel = value; _attributesLoaded = true; } } /// <summary> /// Gets or sets a value indicating whether flush calls from trace sources should be ignored. /// </summary> public bool DisableFlush { get { InitAttributes(); return _disableFlush; } set { _disableFlush = value; _attributesLoaded = true; } } /// <summary> /// Gets a value indicating whether the trace listener is thread safe. /// </summary> /// <value></value> /// <returns>true if the trace listener is thread safe; otherwise, false. The default is false.</returns> public override bool IsThreadSafe => true; /// <summary> /// Gets or sets a value indicating whether to use auto logger name detected from the stack trace. /// </summary> public bool AutoLoggerName { get { InitAttributes(); return _autoLoggerName; } set { _autoLoggerName = value; _attributesLoaded = true; } } /// <summary> /// When overridden in a derived class, writes the specified message to the listener you create in the derived class. /// </summary> /// <param name="message">A message to write.</param> public override void Write(string message) { ProcessLogEventInfo(DefaultLogLevel, null, message, null, null, TraceEventType.Resume, null); } /// <summary> /// When overridden in a derived class, writes a message to the listener you create in the derived class, followed by a line terminator. /// </summary> /// <param name="message">A message to write.</param> public override void WriteLine(string message) { ProcessLogEventInfo(DefaultLogLevel, null, message, null, null, TraceEventType.Resume, null); } /// <summary> /// When overridden in a derived class, closes the output stream so it no longer receives tracing or debugging output. /// </summary> public override void Close() { //nothing to do in this case, but maybe in derived. } /// <summary> /// Emits an error message. /// </summary> /// <param name="message">A message to emit.</param> public override void Fail(string message) { ProcessLogEventInfo(LogLevel.Error, null, message, null, null, TraceEventType.Error, null); } /// <summary> /// Emits an error message and a detailed error message. /// </summary> /// <param name="message">A message to emit.</param> /// <param name="detailMessage">A detailed message to emit.</param> public override void Fail(string message, string detailMessage) { ProcessLogEventInfo(LogLevel.Error, null, string.Concat(message, " ", detailMessage), null, null, TraceEventType.Error, null); } /// <summary> /// Flushes the output (if <see cref="DisableFlush"/> is not <c>true</c>) buffer with the default timeout of 15 seconds. /// </summary> public override void Flush() { if (!DisableFlush) { if (LogFactory != null) { LogFactory.Flush(); } else { LogManager.Flush(); } } } /// <summary> /// Writes trace information, a data object and event information to the listener specific output. /// </summary> /// <param name="eventCache">A <see cref="System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="eventType">One of the <see cref="System.Diagnostics.TraceEventType"/> values specifying the type of event that has caused the trace.</param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="data">The trace data to emit.</param> public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) { TraceData(eventCache, source, eventType, id, new object[] { data }); } /// <summary> /// Writes trace information, an array of data objects and event information to the listener specific output. /// </summary> /// <param name="eventCache">A <see cref="System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="eventType">One of the <see cref="System.Diagnostics.TraceEventType"/> values specifying the type of event that has caused the trace.</param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="data">An array of objects to emit as data.</param> public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, params object[] data) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, string.Empty, null, null, data)) return; string message = string.Empty; if (data?.Length > 0) { if (data.Length == 1) { message = "{0}"; } else { var sb = new StringBuilder(data.Length * 5 - 2); for (int i = 0; i < data.Length; ++i) { if (i > 0) { sb.Append(", "); } sb.Append('{'); sb.AppendInvariant(i); sb.Append('}'); } message = sb.ToString(); } } ProcessLogEventInfo(TranslateLogLevel(eventType), source, message, data, id, eventType, null); } /// <summary> /// Writes trace and event information to the listener specific output. /// </summary> /// <param name="eventCache">A <see cref="System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="eventType">One of the <see cref="System.Diagnostics.TraceEventType"/> values specifying the type of event that has caused the trace.</param> /// <param name="id">A numeric identifier for the event.</param> public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, string.Empty, null, null, null)) return; ProcessLogEventInfo(TranslateLogLevel(eventType), source, string.Empty, null, id, eventType, null); } /// <summary> /// Writes trace information, a formatted array of objects and event information to the listener specific output. /// </summary> /// <param name="eventCache">A <see cref="System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="eventType">One of the <see cref="System.Diagnostics.TraceEventType"/> values specifying the type of event that has caused the trace.</param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="format">A format string that contains zero or more format items, which correspond to objects in the <paramref name="args"/> array.</param> /// <param name="args">An object array containing zero or more objects to format.</param> public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null)) return; ProcessLogEventInfo(TranslateLogLevel(eventType), source, format, args, id, eventType, null); } /// <summary> /// Writes trace information, a message, and event information to the listener specific output. /// </summary> /// <param name="eventCache">A <see cref="System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="eventType">One of the <see cref="System.Diagnostics.TraceEventType"/> values specifying the type of event that has caused the trace.</param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="message">A message to write.</param> public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null)) return; ProcessLogEventInfo(TranslateLogLevel(eventType), source, message, null, id, eventType, null); } /// <summary> /// Writes trace information, a message, a related activity identity and event information to the listener specific output. /// </summary> /// <param name="eventCache">A <see cref="System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="message">A message to write.</param> /// <param name="relatedActivityId">A <see cref="System.Guid"/> object identifying a related activity.</param> public override void TraceTransfer(TraceEventCache eventCache, string source, int id, string message, Guid relatedActivityId) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, TraceEventType.Transfer, id, message, null, null, null)) return; ProcessLogEventInfo(LogLevel.Debug, source, message, null, id, TraceEventType.Transfer, relatedActivityId); } /// <summary> /// Gets the custom attributes supported by the trace listener. /// </summary> /// <returns> /// A string array naming the custom attributes supported by the trace listener, or null if there are no custom attributes. /// </returns> protected override string[] GetSupportedAttributes() { return new[] { "defaultLogLevel", "autoLoggerName", "forceLogLevel", "disableFlush" }; } /// <summary> /// Translates the event type to level from <see cref="TraceEventType"/>. /// </summary> /// <param name="eventType">Type of the event.</param> /// <returns>Translated log level.</returns> private static LogLevel TranslateLogLevel(TraceEventType eventType) { switch (eventType) { case TraceEventType.Verbose: return LogLevel.Trace; case TraceEventType.Information: return LogLevel.Info; case TraceEventType.Warning: return LogLevel.Warn; case TraceEventType.Error: return LogLevel.Error; case TraceEventType.Critical: return LogLevel.Fatal; default: return LogLevel.Debug; } } /// <summary> /// Process the log event /// <param name="logLevel">The log level.</param> /// <param name="loggerName">The name of the logger.</param> /// <param name="message">The log message.</param> /// <param name="arguments">The log parameters.</param> /// <param name="eventId">The event id.</param> /// <param name="eventType">The event type.</param> /// <param name="relatedActivityId">The related activity id.</param> /// </summary> protected virtual void ProcessLogEventInfo(LogLevel logLevel, string loggerName, [Localizable(false)] string message, object[] arguments, int? eventId, TraceEventType? eventType, Guid? relatedActivityId) { StackTrace stackTrace = AutoLoggerName ? new StackTrace() : null; var logger = GetLogger(loggerName, stackTrace, out int userFrameIndex); logLevel = _forceLogLevel ?? logLevel; if (!logger.IsEnabled(logLevel)) { return; // We are done } var ev = new LogEventInfo(); ev.LoggerName = logger.Name; ev.Level = logLevel; if (eventType.HasValue) { ev.Properties.Add("EventType", eventType.Value); } if (relatedActivityId.HasValue) { ev.Properties.Add("RelatedActivityID", relatedActivityId.Value); } ev.Message = message; ev.Parameters = arguments; ev.Level = _forceLogLevel ?? logLevel; if (eventId.HasValue) { ev.Properties.Add("EventID", eventId.Value); } if (stackTrace != null && userFrameIndex >= 0) { ev.SetStackTrace(stackTrace, userFrameIndex); } logger.Log(ev); } private Logger GetLogger(string loggerName, StackTrace stackTrace, out int userFrameIndex) { loggerName = (loggerName ?? Name) ?? string.Empty; userFrameIndex = -1; if (stackTrace != null) { for (int i = 0; i < stackTrace.FrameCount; ++i) { var frame = stackTrace.GetFrame(i); loggerName = StackTraceUsageUtils.LookupClassNameFromStackFrame(frame); if (!string.IsNullOrEmpty(loggerName)) { userFrameIndex = i; break; } } } if (LogFactory != null) { return LogFactory.GetLogger(loggerName); } else { return LogManager.GetLogger(loggerName); } } private void InitAttributes() { if (!_attributesLoaded) { _attributesLoaded = true; if (Trace.AutoFlush) { // Avoid a world of hurt, by not constantly spawning new flush threads // Also timeout exceptions thrown by Flush() will not break diagnostic Trace-logic _disableFlush = true; } foreach (DictionaryEntry de in Attributes) { var key = (string)de.Key; var value = (string)de.Value; switch (key.ToUpperInvariant()) { case "DEFAULTLOGLEVEL": _defaultLogLevel = LogLevel.FromString(value); break; case "FORCELOGLEVEL": _forceLogLevel = LogLevel.FromString(value); break; case "AUTOLOGGERNAME": AutoLoggerName = XmlConvert.ToBoolean(value); break; case "DISABLEFLUSH": _disableFlush = bool.Parse(value); break; } } } } } } #endif <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Reflection; using System.Threading; using JetBrains.Annotations; using NLog.Common; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using NLog.Targets.Wrappers; /// <summary> /// Keeps logging configuration and provides simple API to modify it. /// </summary> ///<remarks>This class is thread-safe.<c>.ToList()</c> is used for that purpose.</remarks> public class LoggingConfiguration { private readonly IDictionary<string, Target> _targets = new Dictionary<string, Target>(StringComparer.OrdinalIgnoreCase); private List<object> _configItems = new List<object>(); private bool _missingServiceTypes; private readonly ConfigVariablesDictionary _variables; /// <summary> /// Gets the factory that will be configured /// </summary> public LogFactory LogFactory { get; } /// <summary> /// Initializes a new instance of the <see cref="LoggingConfiguration" /> class. /// </summary> public LoggingConfiguration() : this(LogManager.LogFactory) { } /// <summary> /// Initializes a new instance of the <see cref="LoggingConfiguration" /> class. /// </summary> public LoggingConfiguration(LogFactory logFactory) { LogFactory = logFactory ?? LogManager.LogFactory; _variables = new ConfigVariablesDictionary(this); DefaultCultureInfo = LogFactory._defaultCultureInfo; } /// <summary> /// Gets the variables defined in the configuration or assigned from API /// </summary> /// <remarks>Name is case insensitive.</remarks> public IDictionary<string, Layout> Variables => _variables; /// <summary> /// Gets a collection of named targets specified in the configuration. /// </summary> /// <returns> /// A list of named targets. /// </returns> /// <remarks> /// Unnamed targets (such as those wrapped by other targets) are not returned. /// </remarks> public ReadOnlyCollection<Target> ConfiguredNamedTargets => GetAllTargetsThreadSafe().AsReadOnly(); /// <summary> /// Gets the collection of file names which should be watched for changes by NLog. /// </summary> public virtual IEnumerable<string> FileNamesToWatch => ArrayHelper.Empty<string>(); /// <summary> /// Gets the collection of logging rules. /// </summary> public IList<LoggingRule> LoggingRules { get; } = new List<LoggingRule>(); internal List<LoggingRule> GetLoggingRulesThreadSafe() { lock (LoggingRules) return LoggingRules.ToList(); } private void AddLoggingRulesThreadSafe(LoggingRule rule) { lock (LoggingRules) LoggingRules.Add(rule); } private bool TryGetTargetThreadSafe(string name, out Target target) { lock (_targets) return _targets.TryGetValue(name, out target); } private List<Target> GetAllTargetsThreadSafe() { lock (_targets) return _targets.Values.ToList(); } private Target RemoveTargetThreadSafe(string name) { Target target; lock (_targets) { if (_targets.TryGetValue(name, out target)) { _targets.Remove(name); } } if (target != null) { InternalLogger.Debug("Unregistered target {0}(Name={1})", target.GetType(), target.Name); } return target; } private void AddTargetThreadSafe(Target target, string targetAlias = null) { if (string.IsNullOrEmpty(target.Name) && string.IsNullOrEmpty(targetAlias)) return; lock (_targets) { if (string.IsNullOrEmpty(targetAlias)) { if (_targets.ContainsKey(target.Name)) return; targetAlias = target.Name; } if (_targets.TryGetValue(targetAlias, out var oldTarget) && ReferenceEquals(oldTarget, target)) return; _targets[targetAlias] = target; } if (!string.IsNullOrEmpty(target.Name) && !string.Equals(target.Name, targetAlias, StringComparison.OrdinalIgnoreCase)) { InternalLogger.Info("Registered target {0}(Name={1}) (Extra alias={2})", target.GetType(), target.Name, targetAlias); } else { InternalLogger.Info("Registered target {0}(Name={1})", target.GetType(), target.Name); } } /// <summary> /// Gets or sets the default culture info to use as <see cref="LogEventInfo.FormatProvider"/>. /// </summary> /// <value> /// Specific culture info or null to use <see cref="CultureInfo.CurrentCulture"/> /// </value> [CanBeNull] public CultureInfo DefaultCultureInfo { get; set; } /// <summary> /// Gets all targets. /// </summary> public ReadOnlyCollection<Target> AllTargets { get { var configTargets = new HashSet<Target>(_configItems.OfType<Target>().Concat(GetAllTargetsThreadSafe()), SingleItemOptimizedHashSet<Target>.ReferenceEqualityComparer.Default); return configTargets.ToList().AsReadOnly(); } } /// <summary> /// Inserts NLog Config Variable without overriding NLog Config Variable assigned from API /// </summary> internal void InsertParsedConfigVariable(string key, Layout value) { _variables.InsertParsedConfigVariable(key, value, LogFactory.KeepVariablesOnReload); } /// <summary> /// Lookup NLog Config Variable Layout /// </summary> internal bool TryLookupDynamicVariable(string key, out Layout value) { return _variables.TryLookupDynamicVariable(key, out value); } /// <summary> /// Registers the specified target object. The name of the target is read from <see cref="Target.Name"/>. /// </summary> /// <param name="target"> /// The target object with a non <see langword="null"/> <see cref="Target.Name"/> /// </param> /// <exception cref="ArgumentNullException">when <paramref name="target"/> is <see langword="null"/></exception> public void AddTarget([NotNull] Target target) { Guard.ThrowIfNull(target); InternalLogger.Debug("Adding target {0}(Name={1})", target.GetType(), target.Name); if (string.IsNullOrEmpty(target.Name)) { throw new ArgumentException(nameof(target) + ".Name cannot be empty", nameof(target)); } AddTargetThreadSafe(target, target.Name); } /// <summary> /// Registers the specified target object under a given name. /// </summary> /// <param name="name">Name of the target.</param> /// <param name="target">The target object.</param> /// <exception cref="ArgumentException">when <paramref name="name"/> is <see langword="null"/></exception> /// <exception cref="ArgumentNullException">when <paramref name="target"/> is <see langword="null"/></exception> public void AddTarget(string name, [NotNull] Target target) { Guard.ThrowIfNull(name); Guard.ThrowIfNull(target); InternalLogger.Debug("Adding target {0}(Name={1})", target.GetType(), string.IsNullOrEmpty(name) ? target.Name : name); if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Target name cannot be empty", nameof(name)); } AddTargetThreadSafe(target, name); } /// <summary> /// Finds the target with the specified name. /// </summary> /// <param name="name"> /// The name of the target to be found. /// </param> /// <returns> /// Found target or <see langword="null"/> when the target is not found. /// </returns> public Target FindTargetByName(string name) { Target value; if (!TryGetTargetThreadSafe(name, out value)) { return null; } return value; } /// <summary> /// Finds the target with the specified name and specified type. /// </summary> /// <param name="name"> /// The name of the target to be found. /// </param> /// <typeparam name="TTarget">Type of the target</typeparam> /// <returns> /// Found target or <see langword="null"/> when the target is not found of not of type <typeparamref name="TTarget"/> /// </returns> public TTarget FindTargetByName<TTarget>(string name) where TTarget : Target { var target = FindTargetByName(name); if (target is TTarget specificTarget) { return specificTarget; } else if (target is WrapperTargetBase wrapperTarget) { if (wrapperTarget.WrappedTarget is TTarget wrappedTarget) return wrappedTarget; else if (wrapperTarget.WrappedTarget is WrapperTargetBase nestedWrapperTarget && nestedWrapperTarget.WrappedTarget is TTarget nestedTarget) return nestedTarget; } return null; } /// <summary> /// Add a rule with min- and maxLevel. /// </summary> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> /// <param name="targetName">Name of the target to be written when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRule(LogLevel minLevel, LogLevel maxLevel, string targetName, string loggerNamePattern = "*") { var target = FindTargetByName(targetName); if (target is null) { throw new NLogRuntimeException($"Target '{targetName}' not found"); } AddRule(minLevel, maxLevel, target, loggerNamePattern, false); } /// <summary> /// Add a rule with min- and maxLevel. /// </summary> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRule(LogLevel minLevel, LogLevel maxLevel, Target target, string loggerNamePattern = "*") { Guard.ThrowIfNull(target); AddRule(minLevel, maxLevel, target, loggerNamePattern, false); } /// <summary> /// Add a rule with min- and maxLevel. /// </summary> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> /// <param name="final">Gets or sets a value indicating whether to quit processing any further rule when this one matches.</param> public void AddRule(LogLevel minLevel, LogLevel maxLevel, Target target, string loggerNamePattern, bool final) { Guard.ThrowIfNull(target); AddLoggingRulesThreadSafe(new LoggingRule(loggerNamePattern, minLevel, maxLevel, target) { Final = final }); AddTargetThreadSafe(target); } /// <summary> /// Add a rule object. /// </summary> /// <param name="rule">rule object to add</param> public void AddRule(LoggingRule rule) { AddLoggingRulesThreadSafe(rule); } /// <summary> /// Add a rule for one loglevel. /// </summary> /// <param name="level">log level needed to trigger this rule. </param> /// <param name="targetName">Name of the target to be written when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRuleForOneLevel(LogLevel level, string targetName, string loggerNamePattern = "*") { var target = FindTargetByName(targetName); if (target is null) { throw new NLogConfigurationException($"Target '{targetName}' not found"); } AddRuleForOneLevel(level, target, loggerNamePattern, false); } /// <summary> /// Add a rule for one loglevel. /// </summary> /// <param name="level">log level needed to trigger this rule. </param> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRuleForOneLevel(LogLevel level, Target target, string loggerNamePattern = "*") { Guard.ThrowIfNull(target); AddRuleForOneLevel(level, target, loggerNamePattern, false); } /// <summary> /// Add a rule for one loglevel. /// </summary> /// <param name="level">log level needed to trigger this rule. </param> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> /// <param name="final">Gets or sets a value indicating whether to quit processing any further rule when this one matches.</param> public void AddRuleForOneLevel(LogLevel level, Target target, string loggerNamePattern, bool final) { Guard.ThrowIfNull(target); var loggingRule = new LoggingRule(loggerNamePattern, target) { Final = final }; loggingRule.EnableLoggingForLevel(level); AddLoggingRulesThreadSafe(loggingRule); AddTargetThreadSafe(target); } /// <summary> /// Add a rule for all loglevels. /// </summary> /// <param name="targetName">Name of the target to be written when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRuleForAllLevels(string targetName, string loggerNamePattern = "*") { var target = FindTargetByName(targetName); if (target is null) { throw new NLogRuntimeException($"Target '{targetName}' not found"); } AddRuleForAllLevels(target, loggerNamePattern, false); } /// <summary> /// Add a rule for all loglevels. /// </summary> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRuleForAllLevels(Target target, string loggerNamePattern = "*") { Guard.ThrowIfNull(target); AddRuleForAllLevels(target, loggerNamePattern, false); } /// <summary> /// Add a rule for all loglevels. /// </summary> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> /// <param name="final">Gets or sets a value indicating whether to quit processing any further rule when this one matches.</param> public void AddRuleForAllLevels(Target target, string loggerNamePattern, bool final) { Guard.ThrowIfNull(target); var loggingRule = new LoggingRule(loggerNamePattern, target) { Final = final }; loggingRule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); AddLoggingRulesThreadSafe(loggingRule); AddTargetThreadSafe(target); } /// <summary> /// Lookup the logging rule with matching <see cref="LoggingRule.RuleName"/> /// </summary> /// <param name="ruleName">The name of the logging rule to be found.</param> /// <returns>Found logging rule or <see langword="null"/> when not found.</returns> public LoggingRule FindRuleByName(string ruleName) { if (ruleName is null) return null; var loggingRules = GetLoggingRulesThreadSafe(); for (int i = loggingRules.Count - 1; i >= 0; i--) { if (string.Equals(loggingRules[i].RuleName, ruleName, StringComparison.OrdinalIgnoreCase)) { return loggingRules[i]; } } return null; } /// <summary> /// Removes the specified named logging rule with matching <see cref="LoggingRule.RuleName"/> /// </summary> /// <param name="ruleName">The name of the logging rule to be removed.</param> /// <returns>Found one or more logging rule to remove, or <see langword="false"/> when not found.</returns> public bool RemoveRuleByName(string ruleName) { if (ruleName is null) return false; HashSet<LoggingRule> removedRules = new HashSet<LoggingRule>(); var loggingRules = GetLoggingRulesThreadSafe(); foreach (var loggingRule in loggingRules) { if (string.Equals(loggingRule.RuleName, ruleName, StringComparison.OrdinalIgnoreCase)) { removedRules.Add(loggingRule); } } if (removedRules.Count > 0) { lock (LoggingRules) { for (int i = LoggingRules.Count - 1; i >= 0; i--) { if (removedRules.Contains(LoggingRules[i])) { LoggingRules.RemoveAt(i); } } } } return removedRules.Count > 0; } /// <summary> /// Called by LogManager when one of the log configuration files changes. /// </summary> /// <returns> /// A new instance of <see cref="LoggingConfiguration"/> that represents the updated configuration. /// </returns> public virtual LoggingConfiguration Reload() { return this; } /// <summary> /// Allow this new configuration to capture state from the old configuration /// </summary> /// <param name="oldConfig">Old config that is about to be replaced</param> /// <remarks>Checks KeepVariablesOnReload and copies all NLog Config Variables assigned from API into the new config</remarks> protected void PrepareForReload(LoggingConfiguration oldConfig) { if (LogFactory.KeepVariablesOnReload) { _variables.PrepareForReload(oldConfig._variables); } } /// <summary> /// Removes the specified named target. /// </summary> /// <param name="name">Name of the target.</param> public void RemoveTarget(string name) { HashSet<Target> removedTargets = new HashSet<Target>(); Target removedTarget = RemoveTargetThreadSafe(name); if (removedTarget != null) { removedTargets.Add(removedTarget); } if (!string.IsNullOrEmpty(name) || removedTarget != null) { CleanupRulesForRemovedTarget(name, removedTarget, removedTargets); } if (removedTargets.Count > 0) { // Refresh active logger-objects, so they stop using the removed target // - Can be called even if no LoggingConfiguration is loaded (will not trigger a config load) LogFactory.ReconfigExistingLoggers(); // Perform flush and close after having stopped logger-objects from using the target ManualResetEvent flushCompleted = new ManualResetEvent(false); foreach (var target in removedTargets) { flushCompleted.Reset(); target.Flush((ex) => flushCompleted.Set()); flushCompleted.WaitOne(TimeSpan.FromSeconds(15)); target.Close(); } } } private void CleanupRulesForRemovedTarget(string name, Target removedTarget, HashSet<Target> removedTargets) { var loggingRules = GetLoggingRulesThreadSafe(); foreach (var rule in loggingRules) { var targetList = rule.GetTargetsThreadSafe(); foreach (var target in targetList) { if (ReferenceEquals(removedTarget, target) || (!string.IsNullOrEmpty(name) && target.Name == name)) { removedTargets.Add(target); rule.RemoveTargetThreadSafe(target); } } } } /// <summary> /// Installs target-specific objects on current system. /// </summary> /// <param name="installationContext">The installation context.</param> /// <remarks> /// Installation typically runs with administrative permissions. /// </remarks> public void Install(InstallationContext installationContext) { Guard.ThrowIfNull(installationContext); InitializeAll(); var configItemsList = GetInstallableItems(); foreach (IInstallable installable in configItemsList) { installationContext.Info("Installing '{0}'", installable); try { installable.Install(installationContext); installationContext.Info("Finished installing '{0}'.", installable); } catch (Exception exception) { InternalLogger.Error(exception, "Install of '{0}' failed.", installable); if (exception.MustBeRethrownImmediately() || installationContext.ThrowExceptions) { throw; } installationContext.Error("Install of '{0}' failed: {1}.", installable, exception); } } } /// <summary> /// Uninstalls target-specific objects from current system. /// </summary> /// <param name="installationContext">The installation context.</param> /// <remarks> /// Uninstallation typically runs with administrative permissions. /// </remarks> public void Uninstall(InstallationContext installationContext) { Guard.ThrowIfNull(installationContext); InitializeAll(); var configItemsList = GetInstallableItems(); foreach (IInstallable installable in configItemsList) { installationContext.Info("Uninstalling '{0}'", installable); try { installable.Uninstall(installationContext); installationContext.Info("Finished uninstalling '{0}'.", installable); } catch (Exception exception) { InternalLogger.Error(exception, "Uninstall of '{0}' failed.", installable); if (exception.MustBeRethrownImmediately()) { throw; } installationContext.Error("Uninstall of '{0}' failed: {1}.", installable, exception); } } } /// <summary> /// Closes all targets and releases any unmanaged resources. /// </summary> internal void Close() { InternalLogger.Debug("Closing logging configuration..."); var supportsInitializesList = GetSupportsInitializes(); foreach (ISupportsInitialize initialize in supportsInitializesList) { InternalLogger.Trace("Closing {0}", initialize); try { initialize.Close(); } catch (Exception exception) { InternalLogger.Warn(exception, "Exception while closing."); if (exception.MustBeRethrown()) { throw; } } } InternalLogger.Debug("Finished closing logging configuration."); } /// <summary> /// Log to the internal (NLog) logger the information about the <see cref="Target"/> and <see /// cref="LoggingRule"/> associated with this <see cref="LoggingConfiguration"/> instance. /// </summary> /// <remarks> /// The information are only recorded in the internal logger if Debug level is enabled, otherwise nothing is /// recorded. /// </remarks> internal void Dump() { if (!InternalLogger.IsDebugEnabled) { return; } InternalLogger.Debug("--- NLog configuration dump ---"); InternalLogger.Debug("Targets:"); var targetList = GetAllTargetsThreadSafe(); foreach (Target target in targetList) { InternalLogger.Debug("{0}", target); } InternalLogger.Debug("Rules:"); foreach (LoggingRule rule in GetLoggingRulesThreadSafe()) { InternalLogger.Debug("{0}", rule); } InternalLogger.Debug("--- End of NLog configuration dump ---"); } internal HashSet<Target> GetAllTargetsToFlush() { var uniqueTargets = new HashSet<Target>(SingleItemOptimizedHashSet<Target>.ReferenceEqualityComparer.Default); foreach (var rule in GetLoggingRulesThreadSafe()) { var targetList = rule.GetTargetsThreadSafe(); foreach (var target in targetList) { uniqueTargets.Add(target); } } return uniqueTargets; } /// <summary> /// Validates the configuration. /// </summary> internal void ValidateConfig() { var roots = new List<object>(); foreach (LoggingRule rule in GetLoggingRulesThreadSafe()) { roots.Add(rule); } var targetList = GetAllTargetsThreadSafe(); foreach (Target target in targetList) { roots.Add(target); } _configItems = ObjectGraphScanner.FindReachableObjects<object>(ConfigurationItemFactory.Default, true, roots.ToArray()); InternalLogger.Info("Validating config: {0}", this); foreach (object o in _configItems) { try { if (o is ISupportsInitialize) continue; // Target + Layout + LayoutRenderer validate on Initialize() PropertyHelper.CheckRequiredParameters(ConfigurationItemFactory.Default, o); } catch (Exception ex) { if (ex.MustBeRethrown()) throw; } } } internal void InitializeAll() { bool firstInitializeAll = _configItems.Count == 0; if (firstInitializeAll && (LogFactory.ThrowExceptions || LogManager.ThrowExceptions)) { InternalLogger.Info("LogManager.ThrowExceptions = true can crash the application! Use only for unit-testing and last resort troubleshooting."); } ValidateConfig(); if (firstInitializeAll && _targets.Count > 0) { CheckUnusedTargets(); } // initialize all config items starting from most nested first // so that whenever the container is initialized its children have already been var supportsInitializes = GetSupportsInitializes(true); foreach (ISupportsInitialize initialize in supportsInitializes) { InternalLogger.Trace("Initializing {0}", initialize); try { initialize.Initialize(this); } catch (Exception exception) { if (exception.MustBeRethrown(initialize as IInternalLoggerContext)) { throw; } } if (initialize is Target target && target.InitializeException is NLogDependencyResolveException) { _missingServiceTypes = true; } } } internal void CheckForMissingServiceTypes(Type serviceType) { if (_missingServiceTypes) { bool missingServiceTypes = false; var allTargets = AllTargets; foreach (var target in allTargets) { if (target.InitializeException is NLogDependencyResolveException resolveException) { missingServiceTypes = true; if (typeof(IServiceProvider).IsAssignableFrom(serviceType) || IsMissingServiceType(resolveException, serviceType)) { target.Close(); // Close Target to allow re-initialize } } } _missingServiceTypes = missingServiceTypes; if (missingServiceTypes) { InitializeAll(); } } } private static bool IsMissingServiceType(NLogDependencyResolveException resolveException, Type serviceType) { if (resolveException.ServiceType.IsAssignableFrom(serviceType)) return true; resolveException = resolveException.InnerException as NLogDependencyResolveException; if (resolveException != null) { return IsMissingServiceType(resolveException, serviceType); } return false; } private List<IInstallable> GetInstallableItems() { return _configItems.OfType<IInstallable>().ToList(); } private List<ISupportsInitialize> GetSupportsInitializes(bool reverse = false) { var items = _configItems.OfType<ISupportsInitialize>(); if (reverse) { items = items.Reverse(); } return items.ToList(); } /// <summary> /// Replace a simple variable with a value. The original value is removed and thus we cannot redo this in a later stage. /// </summary> /// <param name="input"></param> /// <returns></returns> [NotNull] internal string ExpandSimpleVariables(string input) { return ExpandSimpleVariables(input, out var _); } [NotNull] internal string ExpandSimpleVariables(string input, out string matchingVariableName) { string output = input; var culture = StringComparison.OrdinalIgnoreCase; matchingVariableName = null; if (Variables.Count > 0 && output?.IndexOf('$') >= 0) { foreach (var kvp in _variables) { var layout = kvp.Value; if (layout is null) { continue; } var layoutText = string.Concat("${", kvp.Key, "}"); if (output.IndexOf(layoutText, culture) < 0) { continue; } //this value is set from xml and that's a string. Because of that, we can use SimpleLayout here. if (layout is SimpleLayout simpleLayout) { output = StringHelpers.Replace(output, layoutText, simpleLayout.OriginalText, culture); matchingVariableName = null; } else { if (string.Equals(layoutText, input.Trim(), culture)) { matchingVariableName = kvp.Key; } } } } return output ?? string.Empty; } /// <summary> /// Checks whether unused targets exist. If found any, just write an internal log at Warn level. /// <remarks>If initializing not started or failed, then checking process will be canceled</remarks> /// </summary> internal void CheckUnusedTargets() { if (!InternalLogger.IsWarnEnabled) return; var configuredNamedTargets = GetAllTargetsThreadSafe(); //assign to variable because `GetAllTargetsThreadSafe` computes a new list every time. InternalLogger.Debug("Unused target checking is started... Rule Count: {0}, Target Count: {1}", LoggingRules.Count, configuredNamedTargets.Count); var targetNamesAtRules = new HashSet<string>(GetLoggingRulesThreadSafe().SelectMany(r => r.Targets).Select(t => t.Name)); var allTargets = AllTargets; var wrappedTargets = allTargets.OfType<WrapperTargetBase>().ToLookup(wt => wt.WrappedTarget, wt => wt); var compoundTargets = allTargets.OfType<CompoundTargetBase>().SelectMany(wt => wt.Targets.Select(t => new KeyValuePair<Target, Target>(t, wt))).ToLookup(p => p.Key, p => p.Value); bool IsUnusedInList<T>(Target target1, ILookup<Target, T> targets) where T : Target { if (targets.Contains(target1)) { foreach (var wrapperTarget in targets[target1]) { if (targetNamesAtRules.Contains(wrapperTarget.Name)) return false; if (wrappedTargets.Contains(wrapperTarget)) return false; if (compoundTargets.Contains(wrapperTarget)) return false; } } return true; } int unusedCount = configuredNamedTargets.Count((target) => { if (targetNamesAtRules.Contains(target.Name)) return false; if (!IsUnusedInList(target, wrappedTargets)) return false; if (!IsUnusedInList(target, compoundTargets)) return false; InternalLogger.Warn("Unused target detected. Add a rule for this target to the configuration. TargetName: {0}", target.Name); return true; }); InternalLogger.Debug("Unused target checking is completed. Total Rule Count: {0}, Total Target Count: {1}, Unused Target Count: {2}", LoggingRules.Count, configuredNamedTargets.Count, unusedCount); } /// <inheritdoc/> public override string ToString() { ICollection<Target> targets = GetAllTargetsToFlush(); if (targets.Count == 0) targets = GetAllTargetsThreadSafe(); if (targets.Count == 0) targets = AllTargets; if (targets.Count > 0 && targets.Count < 5) return $"TargetNames={string.Join(", ", targets.Select(t => t.Name).Where(n => !string.IsNullOrEmpty(n)).ToArray())}, ConfigItems={_configItems.Count}"; else return $"Targets={targets.Count}, ConfigItems={_configItems.Count}"; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Xml; using JetBrains.Annotations; using NLog.Common; using NLog.Internal; using NLog.Layouts; /// <summary> /// A class for configuring NLog through an XML configuration file /// (App.config style or App.nlog style). /// /// Parsing of the XML file is also implemented in this class. /// </summary> ///<remarks> /// - This class is thread-safe.<c>.ToList()</c> is used for that purpose. /// - Update TemplateXSD.xml for changes outside targets /// </remarks> public class XmlLoggingConfiguration : LoggingConfigurationParser, IInitializeSucceeded { private readonly Dictionary<string, bool> _fileMustAutoReloadLookup = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase); private string _originalFileName; private readonly Stack<string> _currentFilePath = new Stack<string>(); internal XmlLoggingConfiguration(LogFactory logFactory) : base(logFactory) { } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> public XmlLoggingConfiguration([NotNull] string fileName) : this(fileName, LogManager.LogFactory) { } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> /// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param> public XmlLoggingConfiguration([NotNull] string fileName, LogFactory logFactory) : base(logFactory) { LoadFromXmlFile(fileName); } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> [Obsolete("Constructor with parameter ignoreErrors has limited effect. Instead use LogManager.ThrowConfigExceptions. Marked obsolete in NLog 4.7")] [EditorBrowsable(EditorBrowsableState.Never)] public XmlLoggingConfiguration([NotNull] string fileName, bool ignoreErrors) : this(fileName, ignoreErrors, LogManager.LogFactory) { } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> /// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param> [Obsolete("Constructor with parameter ignoreErrors has limited effect. Instead use LogManager.ThrowConfigExceptions. Marked obsolete in NLog 4.7")] [EditorBrowsable(EditorBrowsableState.Never)] public XmlLoggingConfiguration([NotNull] string fileName, bool ignoreErrors, LogFactory logFactory) : base(logFactory) { using (XmlReader reader = CreateFileReader(fileName)) { Initialize(reader, fileName, ignoreErrors); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader">XML reader to read from.</param> public XmlLoggingConfiguration([NotNull] XmlReader reader) : this(reader, null) { } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files). <c>null</c> is allowed.</param> public XmlLoggingConfiguration([NotNull] XmlReader reader, [CanBeNull] string fileName) : this(reader, fileName, LogManager.LogFactory) { } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files). <c>null</c> is allowed.</param> /// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param> public XmlLoggingConfiguration([NotNull] XmlReader reader, [CanBeNull] string fileName, LogFactory logFactory) : base(logFactory) { Initialize(reader, fileName); } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files). <c>null</c> is allowed.</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> [Obsolete("Constructor with parameter ignoreErrors has limited effect. Instead use LogManager.ThrowConfigExceptions. Marked obsolete in NLog 4.7")] [EditorBrowsable(EditorBrowsableState.Never)] public XmlLoggingConfiguration([NotNull] XmlReader reader, [CanBeNull] string fileName, bool ignoreErrors) : this(reader, fileName, ignoreErrors, LogManager.LogFactory) { } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files). <c>null</c> is allowed.</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> /// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param> [Obsolete("Constructor with parameter ignoreErrors has limited effect. Instead use LogManager.ThrowConfigExceptions. Marked obsolete in NLog 4.7")] [EditorBrowsable(EditorBrowsableState.Never)] public XmlLoggingConfiguration([NotNull] XmlReader reader, [CanBeNull] string fileName, bool ignoreErrors, LogFactory logFactory) : base(logFactory) { Initialize(reader, fileName, ignoreErrors); } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="xmlContents">NLog configuration as XML string.</param> /// <param name="fileName">Name of the XML file.</param> /// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param> internal XmlLoggingConfiguration([NotNull] string xmlContents, [CanBeNull] string fileName, LogFactory logFactory) : base(logFactory) { LoadFromXmlContent(xmlContents, fileName); } /// <summary> /// Parse XML string as NLog configuration /// </summary> /// <param name="xml">NLog configuration in XML to be parsed</param> public static XmlLoggingConfiguration CreateFromXmlString(string xml) { return CreateFromXmlString(xml, LogManager.LogFactory); } /// <summary> /// Parse XML string as NLog configuration /// </summary> /// <param name="xml">NLog configuration in XML to be parsed</param> /// <param name="logFactory">NLog LogFactory</param> public static XmlLoggingConfiguration CreateFromXmlString(string xml, LogFactory logFactory) { return new XmlLoggingConfiguration(xml, string.Empty, logFactory); } #if !NETSTANDARD /// <summary> /// Gets the default <see cref="LoggingConfiguration" /> object by parsing /// the application configuration file (<c>app.exe.config</c>). /// </summary> public static LoggingConfiguration AppConfig { get { object o = System.Configuration.ConfigurationManager.GetSection("nlog"); return o as LoggingConfiguration; } } #endif /// <summary> /// Did the <see cref="Initialize"/> Succeeded? <c>true</c>= success, <c>false</c>= error, <c>null</c> = initialize not started yet. /// </summary> public bool? InitializeSucceeded { get; private set; } /// <summary> /// Gets or sets a value indicating whether all of the configuration files /// should be watched for changes and reloaded automatically when changed. /// </summary> public bool AutoReload { get { if (_fileMustAutoReloadLookup.Count == 0) return false; else return _fileMustAutoReloadLookup.Values.All(mustAutoReload => mustAutoReload); } set { var autoReloadFiles = _fileMustAutoReloadLookup.Keys.ToList(); foreach (string nextFile in autoReloadFiles) _fileMustAutoReloadLookup[nextFile] = value; } } /// <summary> /// Gets the collection of file names which should be watched for changes by NLog. /// This is the list of configuration files processed. /// If the <c>autoReload</c> attribute is not set it returns empty collection. /// </summary> public override IEnumerable<string> FileNamesToWatch { get { return _fileMustAutoReloadLookup.Where(entry => entry.Value).Select(entry => entry.Key); } } /// <summary> /// Re-reads the original configuration file and returns the new <see cref="LoggingConfiguration" /> object. /// </summary> /// <returns>The new <see cref="XmlLoggingConfiguration" /> object.</returns> public override LoggingConfiguration Reload() { if (!string.IsNullOrEmpty(_originalFileName)) { var newConfig = new XmlLoggingConfiguration(LogFactory); newConfig.PrepareForReload(this); newConfig.LoadFromXmlFile(_originalFileName); return newConfig; } return base.Reload(); } /// <summary> /// Get file paths (including filename) for the possible NLog config files. /// </summary> /// <returns>The file paths to the possible config file</returns> [Obsolete("Replaced by chaining LogManager.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] public static IEnumerable<string> GetCandidateConfigFilePaths() { return LogManager.LogFactory.GetCandidateConfigFilePaths(); } /// <summary> /// Overwrite the paths (including filename) for the possible NLog config files. /// </summary> /// <param name="filePaths">The file paths to the possible config file</param> [Obsolete("Replaced by chaining LogManager.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] public static void SetCandidateConfigFilePaths(IEnumerable<string> filePaths) { LogManager.LogFactory.SetCandidateConfigFilePaths(filePaths); } /// <summary> /// Clear the candidate file paths and return to the defaults. /// </summary> [Obsolete("Replaced by chaining LogManager.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] public static void ResetCandidateConfigFilePath() { LogManager.LogFactory.ResetCandidateConfigFilePath(); } private void LoadFromXmlFile(string fileName) { using (XmlReader reader = CreateFileReader(fileName)) { Initialize(reader, fileName); } } internal void LoadFromXmlContent(string xmlContent, string fileName) { using (var stringReader = new StringReader(xmlContent)) { using (XmlReader reader = XmlReader.Create(stringReader)) { Initialize(reader, fileName); } } } /// <summary> /// Create XML reader for (xml config) file. /// </summary> /// <param name="fileName">filepath</param> /// <returns>reader or <c>null</c> if filename is empty.</returns> private XmlReader CreateFileReader(string fileName) { if (!string.IsNullOrEmpty(fileName)) { fileName = fileName.Trim(); return LogFactory.CurrentAppEnvironment.LoadXmlFile(fileName); } return null; } /// <summary> /// Initializes the configuration. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files). <c>null</c> is allowed.</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> private void Initialize([NotNull] XmlReader reader, [CanBeNull] string fileName, bool ignoreErrors = false) { try { InitializeSucceeded = null; _originalFileName = string.IsNullOrEmpty(fileName) ? fileName : GetFileLookupKey(fileName); reader.MoveToContent(); var content = new NLogXmlElement(reader); if (!string.IsNullOrEmpty(_originalFileName)) { InternalLogger.Info("Loading NLog config from XML file: {0}", _originalFileName); ParseTopLevel(content, fileName, autoReloadDefault: false); } else { ParseTopLevel(content, null, autoReloadDefault: false); } InitializeSucceeded = true; } catch (Exception exception) { InitializeSucceeded = false; if (exception.MustBeRethrownImmediately()) { throw; } var configurationException = new NLogConfigurationException($"Exception when loading configuration {fileName}", exception); InternalLogger.Error(exception, configurationException.Message); if (!ignoreErrors && (LogFactory.ThrowConfigExceptions ?? LogFactory.ThrowExceptions || configurationException.MustBeRethrown())) throw configurationException; } } /// <summary> /// Add a file with configuration. Check if not already included. /// </summary> /// <param name="fileName"></param> /// <param name="autoReloadDefault"></param> private void ConfigureFromFile([NotNull] string fileName, bool autoReloadDefault) { if (!_fileMustAutoReloadLookup.ContainsKey(GetFileLookupKey(fileName))) { using (var reader = LogFactory.CurrentAppEnvironment.LoadXmlFile(fileName)) { reader.MoveToContent(); ParseTopLevel(new NLogXmlElement(reader, false), fileName, autoReloadDefault); } } } /// <summary> /// Parse the root /// </summary> /// <param name="content"></param> /// <param name="filePath">path to config file.</param> /// <param name="autoReloadDefault">The default value for the autoReload option.</param> private void ParseTopLevel(NLogXmlElement content, [CanBeNull] string filePath, bool autoReloadDefault) { content.AssertName("nlog", "configuration"); switch (content.LocalName.ToUpperInvariant()) { case "CONFIGURATION": ParseConfigurationElement(content, filePath, autoReloadDefault); break; case "NLOG": ParseNLogElement(content, filePath, autoReloadDefault); break; } } /// <summary> /// Parse {configuration} xml element. /// </summary> /// <param name="configurationElement"></param> /// <param name="filePath">path to config file.</param> /// <param name="autoReloadDefault">The default value for the autoReload option.</param> private void ParseConfigurationElement(NLogXmlElement configurationElement, [CanBeNull] string filePath, bool autoReloadDefault) { InternalLogger.Trace("ParseConfigurationElement"); configurationElement.AssertName("configuration"); var nlogElements = configurationElement.FilterChildren("nlog"); foreach (var nlogElement in nlogElements) { ParseNLogElement(nlogElement, filePath, autoReloadDefault); } } /// <summary> /// Parse {NLog} xml element. /// </summary> /// <param name="nlogElement"></param> /// <param name="filePath">path to config file.</param> /// <param name="autoReloadDefault">The default value for the autoReload option.</param> private void ParseNLogElement(ILoggingConfigurationElement nlogElement, [CanBeNull] string filePath, bool autoReloadDefault) { InternalLogger.Trace("ParseNLogElement"); nlogElement.AssertName("nlog"); bool autoReload = nlogElement.GetOptionalBooleanValue("autoReload", autoReloadDefault); try { string baseDirectory = null; if (!string.IsNullOrEmpty(filePath)) { _fileMustAutoReloadLookup[GetFileLookupKey(filePath)] = autoReload; _currentFilePath.Push(filePath); baseDirectory = Path.GetDirectoryName(filePath); } base.LoadConfig(nlogElement, baseDirectory); } finally { if (!string.IsNullOrEmpty(filePath)) _currentFilePath.Pop(); } } /// <summary> /// Parses a single config section within the NLog-config /// </summary> /// <param name="configSection"></param> /// <returns>Section was recognized</returns> protected override bool ParseNLogSection(ILoggingConfigurationElement configSection) { if (configSection.MatchesName("include")) { string filePath = _currentFilePath.Peek(); bool autoLoad = !string.IsNullOrEmpty(filePath) && _fileMustAutoReloadLookup[GetFileLookupKey(filePath)]; ParseIncludeElement(configSection, !string.IsNullOrEmpty(filePath) ? Path.GetDirectoryName(filePath) : null, autoLoad); return true; } else { return base.ParseNLogSection(configSection); } } private void ParseIncludeElement(ILoggingConfigurationElement includeElement, string baseDirectory, bool autoReloadDefault) { includeElement.AssertName("include"); string newFileName = includeElement.GetRequiredValue("file", "nlog"); var ignoreErrors = includeElement.GetOptionalBooleanValue("ignoreErrors", false); try { newFileName = ExpandSimpleVariables(newFileName); newFileName = SimpleLayout.Evaluate(newFileName); var fullNewFileName = newFileName; if (baseDirectory != null) { fullNewFileName = Path.Combine(baseDirectory, newFileName); } if (File.Exists(fullNewFileName)) { InternalLogger.Debug("Including file '{0}'", fullNewFileName); ConfigureFromFile(fullNewFileName, autoReloadDefault); } else { //is mask? if (newFileName.Contains("*")) { ConfigureFromFilesByMask(baseDirectory, newFileName, autoReloadDefault); } else { if (ignoreErrors) { //quick stop for performances InternalLogger.Debug("Skipping included file '{0}' as it can't be found", fullNewFileName); return; } throw new FileNotFoundException("Included file not found: " + fullNewFileName); } } } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } var configurationException = new NLogConfigurationException($"Error when including '{newFileName}'.", exception); InternalLogger.Error(exception, configurationException.Message); if (!ignoreErrors) throw configurationException; } } /// <summary> /// Include (multiple) files by filemask, e.g. *.nlog /// </summary> /// <param name="baseDirectory">base directory in case if <paramref name="fileMask"/> is relative</param> /// <param name="fileMask">relative or absolute fileMask</param> /// <param name="autoReloadDefault"></param> private void ConfigureFromFilesByMask(string baseDirectory, string fileMask, bool autoReloadDefault) { var directory = baseDirectory; //if absolute, split to file mask and directory. if (Path.IsPathRooted(fileMask)) { directory = Path.GetDirectoryName(fileMask); if (directory is null) { InternalLogger.Warn("directory is empty for include of '{0}'", fileMask); return; } var filename = Path.GetFileName(fileMask); if (filename is null) { InternalLogger.Warn("filename is empty for include of '{0}'", fileMask); return; } fileMask = filename; } var files = Directory.GetFiles(directory, fileMask); foreach (var file in files) { //note we exclude our self in ConfigureFromFile ConfigureFromFile(file, autoReloadDefault); } } private static string GetFileLookupKey([NotNull] string fileName) { return Path.GetFullPath(fileName); } /// <inheritdoc/> public override string ToString() { return $"{base.ToString()}, FilePath={_originalFileName}"; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Threading; using System.Threading.Tasks; using NLog.Common; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class AutoFlushTargetWrapperTests : NLogTestBase { [Fact] public void AutoFlushTargetWrapperSyncTest1() { var myTarget = new MyTarget(); var wrapper = new AutoFlushTargetWrapper { WrappedTarget = myTarget, }; myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; bool continuationHit = false; AsyncContinuation continuation = ex => { lastException = ex; continuationHit = true; }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit); Assert.Null(lastException); Assert.Equal(1, myTarget.FlushCount); Assert.Equal(1, myTarget.WriteCount); continuationHit = false; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit); Assert.Null(lastException); Assert.Equal(2, myTarget.WriteCount); Assert.Equal(2, myTarget.FlushCount); } [Fact] public void AutoFlushTargetWrapperAsyncTest1() { var myTarget = new MyAsyncTarget(); var wrapper = new AutoFlushTargetWrapper(myTarget); myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit.WaitOne(5000)); Assert.Null(lastException); Assert.Equal(1, myTarget.FlushCount); Assert.Equal(1, myTarget.WriteCount); continuationHit.Reset(); wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit.WaitOne(5000)); Assert.Null(lastException); Assert.Equal(2, myTarget.WriteCount); Assert.Equal(2, myTarget.FlushCount); } [Fact] public void AutoFlushTargetWrapperAsyncTest2() { var myTarget = new MyAsyncTarget(); var wrapper = new AutoFlushTargetWrapper(myTarget); myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; // Schedule 100 writes, where each write on completion schedules followup-flush (in random order) const int expectedWriteCount = 100; const int expectedFlushCount = expectedWriteCount + 3; for (int i = 0; i < expectedWriteCount; ++i) { wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(ex => lastException = ex)); } var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { continuationHit.Set(); }; // Schedule 1st flush (can complete before follow-flushes) wrapper.Flush(ex => { }); Assert.Null(lastException); // Schedule 2nd flush (can complete before follow-flushes) wrapper.Flush(continuation); Assert.Null(lastException); Assert.True(continuationHit.WaitOne(5000)); Assert.Null(lastException); // Schedule 3rd flush (can complete before follow-flushes) wrapper.Flush(ex => { }); Assert.Null(lastException); for (int i = 0; i < 500; ++i) { if (myTarget.WriteCount == expectedWriteCount && myTarget.FlushCount == expectedFlushCount) break; Thread.Sleep(10); } Assert.Equal(expectedWriteCount, myTarget.WriteCount); Assert.Equal(expectedFlushCount, myTarget.FlushCount); } [Fact] public void AutoFlushTargetWrapperAsyncTest3() { var myTarget = new MyAsyncTarget(); var wrapper = new AutoFlushTargetWrapper(myTarget) { AsyncFlush = false }; myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; for (int i = 0; i < 100; ++i) { wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(ex => lastException = ex)); } var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { continuationHit.Set(); }; wrapper.Flush(ex => { }); Assert.Null(lastException); wrapper.Flush(continuation); Assert.Null(lastException); Assert.True(continuationHit.WaitOne(5000)); Assert.Null(lastException); wrapper.Flush(ex => { }); // Executed right away Assert.Null(lastException); Assert.Equal(100, myTarget.WriteCount); Assert.Equal(103, myTarget.FlushCount); } [Fact] public void AutoFlushTargetWrapperAsyncWithExceptionTest1() { var myTarget = new MyAsyncTarget { ThrowExceptions = true, }; var wrapper = new AutoFlushTargetWrapper(myTarget); myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit.WaitOne(5000)); Assert.NotNull(lastException); Assert.IsType<InvalidOperationException>(lastException); // no flush on exception Assert.Equal(0, myTarget.FlushCount); Assert.Equal(1, myTarget.WriteCount); continuationHit.Reset(); lastException = null; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit.WaitOne(5000)); Assert.NotNull(lastException); Assert.IsType<InvalidOperationException>(lastException); Assert.Equal(0, myTarget.FlushCount); Assert.Equal(2, myTarget.WriteCount); } [Fact] public void AutoFlushConditionConfigurationTest() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"<nlog> <targets> <target type='AutoFlushWrapper' condition='level >= LogLevel.Debug' name='FlushOnError'> <target name='d2' type='Debug' /> </target> </targets> <rules> <logger name='*' level='Warn' writeTo='FlushOnError'> </logger> </rules> </nlog>").LogFactory; var target = logFactory.Configuration.FindTargetByName("FlushOnError") as AutoFlushTargetWrapper; Assert.NotNull(target); Assert.NotNull(target.Condition); Assert.Equal("(level >= Debug)", target.Condition.ToString()); Assert.Equal("d2", target.WrappedTarget.Name); } [Fact] public void AutoFlushOnConditionTest() { var testTarget = new MyTarget(); var autoFlushWrapper = new AutoFlushTargetWrapper(testTarget); autoFlushWrapper.Condition = "level > LogLevel.Info"; testTarget.Initialize(null); autoFlushWrapper.Initialize(null); AsyncContinuation continuation = ex => { }; autoFlushWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Info, "*", "test").WithContinuation(continuation)); autoFlushWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "test").WithContinuation(continuation)); Assert.Equal(2, testTarget.WriteCount); Assert.Equal(0, testTarget.FlushCount); autoFlushWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Warn, "*", "test").WithContinuation(continuation)); autoFlushWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Error, "*", "test").WithContinuation(continuation)); Assert.Equal(4, testTarget.WriteCount); Assert.Equal(2, testTarget.FlushCount); } [Fact] public void MultipleConditionalAutoFlushWrappersTest() { var testTarget = new MyTarget(); var autoFlushOnLevelWrapper = new AutoFlushTargetWrapper(testTarget); autoFlushOnLevelWrapper.Condition = "level > LogLevel.Info"; var autoFlushOnMessageWrapper = new AutoFlushTargetWrapper(autoFlushOnLevelWrapper); autoFlushOnMessageWrapper.Condition = "contains('${message}','FlushThis')"; testTarget.Initialize(null); autoFlushOnLevelWrapper.Initialize(null); autoFlushOnMessageWrapper.Initialize(null); AsyncContinuation continuation = ex => { }; autoFlushOnMessageWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "test").WithContinuation(continuation)); Assert.Equal(1, testTarget.WriteCount); Assert.Equal(0, testTarget.FlushCount); autoFlushOnMessageWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Fatal, "*", "test").WithContinuation(continuation)); Assert.Equal(2, testTarget.WriteCount); Assert.Equal(1, testTarget.FlushCount); autoFlushOnMessageWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "Please FlushThis").WithContinuation(continuation)); Assert.Equal(3, testTarget.WriteCount); Assert.Equal(2, testTarget.FlushCount); } [Fact] public void BufferingAutoFlushWrapperTest() { var testTarget = new MyTarget(); var bufferingTargetWrapper = new BufferingTargetWrapper(testTarget, 100); var autoFlushOnLevelWrapper = new AutoFlushTargetWrapper(bufferingTargetWrapper); autoFlushOnLevelWrapper.Condition = "level > LogLevel.Info"; testTarget.Initialize(null); bufferingTargetWrapper.Initialize(null); autoFlushOnLevelWrapper.Initialize(null); AsyncContinuation continuation = ex => { }; autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "test").WithContinuation(continuation)); Assert.Equal(0, testTarget.WriteCount); Assert.Equal(0, testTarget.FlushCount); autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Fatal, "*", "test").WithContinuation(continuation)); Assert.Equal(2, testTarget.WriteCount); Assert.Equal(1, testTarget.FlushCount); autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "Please do not FlushThis").WithContinuation(continuation)); Assert.Equal(2, testTarget.WriteCount); Assert.Equal(1, testTarget.FlushCount); autoFlushOnLevelWrapper.Flush(continuation); Assert.Equal(3, testTarget.WriteCount); Assert.Equal(2, testTarget.FlushCount); } [Fact] public void IgnoreExplicitAutoFlushWrapperTest() { var testTarget = new MyTarget(); var bufferingTargetWrapper = new BufferingTargetWrapper(testTarget, 100); var autoFlushOnLevelWrapper = new AutoFlushTargetWrapper(bufferingTargetWrapper); autoFlushOnLevelWrapper.Condition = "level > LogLevel.Info"; autoFlushOnLevelWrapper.FlushOnConditionOnly = true; testTarget.Initialize(null); bufferingTargetWrapper.Initialize(null); autoFlushOnLevelWrapper.Initialize(null); AsyncContinuation continuation = ex => { }; autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "test").WithContinuation(continuation)); Assert.Equal(0, testTarget.WriteCount); Assert.Equal(0, testTarget.FlushCount); autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Fatal, "*", "test").WithContinuation(continuation)); Assert.Equal(2, testTarget.WriteCount); Assert.Equal(1, testTarget.FlushCount); autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "Ignore on Explict Flush").WithContinuation(continuation)); Assert.Equal(2, testTarget.WriteCount); Assert.Equal(1, testTarget.FlushCount); autoFlushOnLevelWrapper.Flush(continuation); Assert.Equal(2, testTarget.WriteCount); Assert.Equal(1, testTarget.FlushCount); } [Fact] public void ExplicitFlushWaitsForAutoFlushWrapperCompletionTest() { var testTarget = new MyTarget(); var bufferingTargetWrapper = new BufferingTargetWrapper(testTarget, 100); var autoFlushOnLevelWrapper = new AutoFlushTargetWrapper(bufferingTargetWrapper); autoFlushOnLevelWrapper.Condition = "level > LogLevel.Info"; autoFlushOnLevelWrapper.FlushOnConditionOnly = true; testTarget.Initialize(null); bufferingTargetWrapper.Initialize(null); autoFlushOnLevelWrapper.Initialize(null); AsyncContinuation continuation = ex => { }; var flushCompleted = false; autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "test").WithContinuation(continuation)); Assert.Equal(0, testTarget.WriteCount); Assert.Equal(0, testTarget.FlushCount); autoFlushOnLevelWrapper.Flush((ex) => flushCompleted = true); Assert.True(flushCompleted); Assert.Equal(0, testTarget.WriteCount); Assert.Equal(0, testTarget.FlushCount); flushCompleted = false; var manualResetEvent = new ManualResetEvent(false); testTarget.FlushEvent = (arg) => { Task.Run(() => manualResetEvent.WaitOne(10000)).ContinueWith(t => arg(null)); }; autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Error, "*", "test").WithContinuation(continuation)); Assert.Equal(2, testTarget.WriteCount); Assert.Equal(0, testTarget.FlushCount); autoFlushOnLevelWrapper.Flush((ex) => flushCompleted = true); Assert.False(flushCompleted); Assert.Equal(0, testTarget.FlushCount); manualResetEvent.Set(); for (int i = 0; i < 500; ++i) { if (flushCompleted && testTarget.FlushCount > 0) break; Thread.Sleep(10); } Assert.Equal(2, testTarget.WriteCount); Assert.Equal(1, testTarget.FlushCount); } class MyAsyncTarget : Target { public int FlushCount { get; private set; } public int WriteCount { get; private set; } protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); } protected override void Write(AsyncLogEventInfo logEvent) { Assert.True(FlushCount <= WriteCount); WriteCount++; ThreadPool.QueueUserWorkItem( s => { if (ThrowExceptions) { logEvent.Continuation(new InvalidOperationException("Some problem!")); logEvent.Continuation(new InvalidOperationException("Some problem!")); } else { logEvent.Continuation(null); logEvent.Continuation(null); } }); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { InternalLogger.Trace("Flush Started"); FlushCount++; ThreadPool.QueueUserWorkItem( s => { asyncContinuation(null); InternalLogger.Trace("Flush Completed"); }); } public bool ThrowExceptions { get; set; } } class MyTarget : Target { public int FlushCount { get; set; } public int WriteCount { get; set; } public Action<AsyncContinuation> FlushEvent { get; set; } = (arg) => arg(null); protected override void Write(LogEventInfo logEvent) { Assert.True(FlushCount <= WriteCount); WriteCount++; } protected override void FlushAsync(AsyncContinuation asyncContinuation) { FlushEvent((ex) => { asyncContinuation(ex); FlushCount++; }); } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.ComponentModel; using System.Diagnostics; using JetBrains.Annotations; /// <content> /// Logging methods which only are executed when the DEBUG conditional compilation symbol is set. /// /// Remarks: /// The DEBUG conditional compilation symbol is default enabled (only) in a debug build. /// /// If the DEBUG conditional compilation symbol isn't set in the calling library, the compiler will remove all the invocations to these methods. /// This could lead to better performance. /// /// See: https://msdn.microsoft.com/en-us/library/4xssyw96%28v=vs.90%29.aspx /// </content> public partial class Logger { #region ConditionalDebug /// <overloads> /// Writes the diagnostic message at the <c>Debug</c> level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="value">The value to be written.</param> [Conditional("DEBUG")] public void ConditionalDebug<T>(T value) { Debug(value); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> [Conditional("DEBUG")] public void ConditionalDebug<T>(IFormatProvider formatProvider, T value) { Debug(formatProvider, value); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> [Conditional("DEBUG")] public void ConditionalDebug(LogMessageGenerator messageFunc) { Debug(messageFunc); } /// <summary> /// Writes the diagnostic message and exception at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(Exception exception, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { Debug(exception, message, args); } /// <summary> /// Writes the diagnostic message and exception at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(Exception exception, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { Debug(exception, formatProvider, message, args); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters and formatting them with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { Debug(formatProvider, message, args); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">Log message.</param> [Conditional("DEBUG")] public void ConditionalDebug([Localizable(false)] string message) { Debug(message); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { Debug(message, args); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug<TArgument>(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument argument) { Debug(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug<TArgument>([Localizable(false)][StructuredMessageTemplate] string message, TArgument argument) { Debug(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified arguments formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug<TArgument1, TArgument2>(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2) { Debug(formatProvider, message, argument1, argument2); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug<TArgument1, TArgument2>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2) { Debug(message, argument1, argument2); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified arguments formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug<TArgument1, TArgument2, TArgument3>(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3) { Debug(formatProvider, message, argument1, argument2, argument3); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug<TArgument1, TArgument2, TArgument3>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3) { Debug(message, argument1, argument2, argument3); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="value">A <see langword="object" /> to be written.</param> [Conditional("DEBUG")] public void ConditionalDebug(object value) { Debug(value); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">A <see langword="object" /> to be written.</param> [Conditional("DEBUG")] public void ConditionalDebug(IFormatProvider formatProvider, object value) { Debug(formatProvider, value); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2) { Debug(message, arg1, arg2); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> /// <param name="arg3">Third argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2, object arg3) { Debug(message, arg1, arg2, arg3); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { Debug(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, bool argument) { Debug(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { Debug(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, char argument) { Debug(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { Debug(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, byte argument) { Debug(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string argument) { Debug(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, string argument) { Debug(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument) { Debug(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, int argument) { Debug(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { Debug(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, long argument) { Debug(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { Debug(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, float argument) { Debug(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { Debug(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, double argument) { Debug(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { Debug(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { Debug(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object argument) { Debug(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, object argument) { Debug(message, argument); } #endregion #region ConditionalTrace /// <overloads> /// Writes the diagnostic message at the <c>Trace</c> level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="value">The value to be written.</param> [Conditional("DEBUG")] public void ConditionalTrace<T>(T value) { Trace(value); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> [Conditional("DEBUG")] public void ConditionalTrace<T>(IFormatProvider formatProvider, T value) { Trace(formatProvider, value); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> [Conditional("DEBUG")] public void ConditionalTrace(LogMessageGenerator messageFunc) { Trace(messageFunc); } /// <summary> /// Writes the diagnostic message and exception at the <c>Trace</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(Exception exception, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { Trace(exception, message, args); } /// <summary> /// Writes the diagnostic message and exception at the <c>Trace</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(Exception exception, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { Trace(exception, formatProvider, message, args); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified parameters and formatting them with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { Trace(formatProvider, message, args); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">Log message.</param> [Conditional("DEBUG")] public void ConditionalTrace([Localizable(false)] string message) { Trace(message); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, params object[] args) { Trace(message, args); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace<TArgument>(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument argument) { Trace(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace<TArgument>([Localizable(false)][StructuredMessageTemplate] string message, TArgument argument) { Trace(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified arguments formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace<TArgument1, TArgument2>(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2) { Trace(formatProvider, message, argument1, argument2); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace<TArgument1, TArgument2>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2) { Trace(message, argument1, argument2); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified arguments formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace<TArgument1, TArgument2, TArgument3>(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3) { Trace(formatProvider, message, argument1, argument2, argument3); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace<TArgument1, TArgument2, TArgument3>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3) { Trace(message, argument1, argument2, argument3); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="value">A <see langword="object" /> to be written.</param> [Conditional("DEBUG")] public void ConditionalTrace(object value) { Trace(value); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">A <see langword="object" /> to be written.</param> [Conditional("DEBUG")] public void ConditionalTrace(IFormatProvider formatProvider, object value) { Trace(formatProvider, value); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2) { Trace(message, arg1, arg2); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified parameters. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="arg1">First argument to format.</param> /// <param name="arg2">Second argument to format.</param> /// <param name="arg3">Third argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, object arg1, object arg2, object arg3) { Trace(message, arg1, arg2, arg3); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { Trace(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, bool argument) { Trace(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { Trace(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, char argument) { Trace(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { Trace(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, byte argument) { Trace(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string argument) { Trace(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, string argument) { Trace(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument) { Trace(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, int argument) { Trace(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { Trace(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, long argument) { Trace(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { Trace(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, float argument) { Trace(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { Trace(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, double argument) { Trace(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { Trace(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { Trace(message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter and formatting it with the supplied format provider. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object argument) { Trace(formatProvider, message, argument); } /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified value as a parameter. /// Only executed when the DEBUG conditional compilation symbol is set.</summary> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, object argument) { Trace(message, argument); } #endregion } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using NLog.Config; using NLog.Internal; using NLog.Layouts; /// <summary> /// Represents target that supports context capture of <see cref="ScopeContext"/> Properties + Nested-states /// </summary> /// <remarks> /// <a href="https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target-for-structured-logging">See NLog Wiki</a> /// </remarks> /// <example><code> /// [Target("MyFirst")] /// public sealed class MyFirstTarget : TargetWithContext /// { /// public MyFirstTarget() /// { /// this.Host = "localhost"; /// } /// /// [RequiredParameter] /// public Layout Host { get; set; } /// /// protected override void Write(LogEventInfo logEvent) /// { /// string logMessage = this.RenderLogEvent(this.Layout, logEvent); /// string hostName = this.RenderLogEvent(this.Host, logEvent); /// return SendTheMessageToRemoteHost(hostName, logMessage); /// } /// /// private void SendTheMessageToRemoteHost(string hostName, string message) /// { /// // To be implemented /// } /// } /// </code></example> /// <seealso href="https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target-for-structured-logging">Documentation on NLog Wiki</seealso> public abstract class TargetWithContext : TargetWithLayout, IIncludeContext { /// <inheritdoc/> /// <docgen category='Layout Options' order='1' /> public sealed override Layout Layout { get => _contextLayout; set { if (_contextLayout is null) _contextLayout = new TargetWithContextLayout(this, value); else _contextLayout.TargetLayout = value; } } private TargetWithContextLayout _contextLayout; /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeEventProperties { get => _contextLayout.IncludeEventProperties; set => _contextLayout.IncludeEventProperties = value; } /// <summary> /// Gets or sets whether to include the contents of the <see cref="ScopeContext"/> properties-dictionary. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeScopeProperties { get => _contextLayout.IncludeScopeProperties; set => _contextLayout.IncludeScopeProperties = value; } /// <summary> /// Gets or sets whether to include the contents of the <see cref="ScopeContext"/> nested-state-stack. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeScopeNested { get => _contextLayout.IncludeScopeNested; set => _contextLayout.IncludeScopeNested = value; } /// <inheritdoc/> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeMdc { get => _contextLayout.IncludeMdc; set => _contextLayout.IncludeMdc = value; } /// <inheritdoc/> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeScopeNested. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeNdc { get => _contextLayout.IncludeNdc; set => _contextLayout.IncludeNdc = value; } /// <inheritdoc/> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeMdlc { get => _contextLayout.IncludeMdlc; set => _contextLayout.IncludeMdlc = value; } /// <inheritdoc/> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeScopeNested. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeNdlc { get => _contextLayout.IncludeNdlc; set => _contextLayout.IncludeNdlc = value; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="GlobalDiagnosticsContext"/> dictionary /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeGdc { get; set; } /// <summary> /// Gets or sets a value indicating whether to include call site (class and method name) in the <see cref="LogEventInfo" /> /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeCallSite { get => _contextLayout.IncludeCallSite; set => _contextLayout.IncludeCallSite = value; } /// <summary> /// Gets or sets a value indicating whether to include source info (file name and line number) in the <see cref="LogEventInfo" /> /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeCallSiteStackTrace { get => _contextLayout.IncludeCallSiteStackTrace; set => _contextLayout.IncludeCallSiteStackTrace = value; } /// <summary> /// Gets the array of custom attributes to be passed into the logevent context /// </summary> /// <docgen category='Layout Options' order='10' /> [ArrayParameter(typeof(TargetPropertyWithContext), "contextproperty")] public virtual IList<TargetPropertyWithContext> ContextProperties { get; } = new List<TargetPropertyWithContext>(); /// <summary> /// List of property names to exclude when <see cref="IncludeEventProperties"/> is true /// </summary> /// <docgen category='Layout Options' order='50' /> #if !NET35 public ISet<string> ExcludeProperties { get; set; } #else public HashSet<string> ExcludeProperties { get; set; } #endif /// <summary> /// Constructor /// </summary> protected TargetWithContext() { _contextLayout = _contextLayout ?? new TargetWithContextLayout(this, base.Layout); ExcludeProperties = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Check if logevent has properties (or context properties) /// </summary> /// <param name="logEvent"></param> /// <returns>True if properties should be included</returns> protected bool ShouldIncludeProperties(LogEventInfo logEvent) { return IncludeGdc || IncludeScopeProperties || (IncludeEventProperties && (logEvent?.HasProperties ?? false)); } /// <summary> /// Checks if any context properties, and if any returns them as a single dictionary /// </summary> /// <param name="logEvent"></param> /// <returns>Dictionary with any context properties for the logEvent (Null if none found)</returns> protected IDictionary<string, object> GetContextProperties(LogEventInfo logEvent) { return GetContextProperties(logEvent, null); } /// <summary> /// Checks if any context properties, and if any returns them as a single dictionary /// </summary> /// <param name="logEvent"></param> /// <param name="combinedProperties">Optional prefilled dictionary</param> /// <returns>Dictionary with any context properties for the logEvent (Null if none found)</returns> protected IDictionary<string, object> GetContextProperties(LogEventInfo logEvent, IDictionary<string, object> combinedProperties) { if (ContextProperties?.Count > 0) { combinedProperties = CaptureContextProperties(logEvent, combinedProperties); } if (IncludeScopeProperties && !CombineProperties(logEvent, _contextLayout.ScopeContextPropertiesLayout, ref combinedProperties)) { combinedProperties = CaptureScopeContextProperties(logEvent, combinedProperties); } if (IncludeGdc) { combinedProperties = CaptureContextGdc(logEvent, combinedProperties); } return combinedProperties; } /// <summary> /// Creates combined dictionary of all configured properties for logEvent /// </summary> /// <param name="logEvent"></param> /// <returns>Dictionary with all collected properties for logEvent</returns> protected IDictionary<string, object> GetAllProperties(LogEventInfo logEvent) { return GetAllProperties(logEvent, null); } /// <summary> /// Creates combined dictionary of all configured properties for logEvent /// </summary> /// <param name="logEvent"></param> /// <param name="combinedProperties">Optional prefilled dictionary</param> /// <returns>Dictionary with all collected properties for logEvent</returns> protected IDictionary<string, object> GetAllProperties(LogEventInfo logEvent, IDictionary<string, object> combinedProperties) { if (IncludeEventProperties && logEvent.HasProperties) { // TODO Make Dictionary-Lazy-adapter for PropertiesDictionary to skip extra Dictionary-allocation combinedProperties = combinedProperties ?? CreateNewDictionary(logEvent.Properties.Count + (ContextProperties?.Count ?? 0)); bool checkForDuplicates = combinedProperties.Count > 0; bool checkExcludeProperties = ExcludeProperties.Count > 0; foreach (var property in logEvent.Properties) { string propertyName = property.Key.ToString(); if (string.IsNullOrEmpty(propertyName)) continue; if (checkExcludeProperties && ExcludeProperties.Contains(propertyName)) continue; AddContextProperty(logEvent, propertyName, property.Value, checkForDuplicates, combinedProperties); } } combinedProperties = GetContextProperties(logEvent, combinedProperties); return combinedProperties ?? new Dictionary<string, object>(StringComparer.Ordinal); } private static IDictionary<string, object> CreateNewDictionary(int initialCapacity) { return new Dictionary<string, object>(Math.Max(initialCapacity, 3), StringComparer.Ordinal); } /// <summary> /// Generates a new unique name, when duplicate names are detected /// </summary> /// <param name="logEvent">LogEvent that triggered the duplicate name</param> /// <param name="itemName">Duplicate item name</param> /// <param name="itemValue">Item Value</param> /// <param name="combinedProperties">Dictionary of context values</param> /// <returns>New (unique) value (or null to skip value). If the same value is used then the item will be overwritten</returns> protected virtual string GenerateUniqueItemName(LogEventInfo logEvent, string itemName, object itemValue, IDictionary<string, object> combinedProperties) { return PropertiesDictionary.GenerateUniquePropertyName(itemName, combinedProperties, (newKey, props) => props.ContainsKey(newKey)); } private bool CombineProperties(LogEventInfo logEvent, Layout contextLayout, ref IDictionary<string, object> combinedProperties) { if (!logEvent.TryGetCachedLayoutValue(contextLayout, out object value)) { return false; } if (value is IDictionary<string, object> contextProperties) { if (combinedProperties != null) { bool checkForDuplicates = combinedProperties.Count > 0; foreach (var property in contextProperties) { AddContextProperty(logEvent, property.Key, property.Value, checkForDuplicates, combinedProperties); } } else { combinedProperties = contextProperties; } } return true; } private void AddContextProperty(LogEventInfo logEvent, string propertyName, object propertyValue, bool checkForDuplicates, IDictionary<string, object> combinedProperties) { if (checkForDuplicates && combinedProperties.ContainsKey(propertyName)) { propertyName = GenerateUniqueItemName(logEvent, propertyName, propertyValue, combinedProperties); if (propertyName is null) return; } combinedProperties[propertyName] = propertyValue; } /// <summary> /// Returns the captured snapshot of <see cref="MappedDiagnosticsContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <returns>Dictionary with MDC context if any, else null</returns> [Obsolete("Replaced by GetScopeContextProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected IDictionary<string, object> GetContextMdc(LogEventInfo logEvent) { if (logEvent.TryGetCachedLayoutValue(_contextLayout.ScopeContextPropertiesLayout, out object value)) { return value as IDictionary<string, object>; } return CaptureContextMdc(logEvent, null); } /// <summary> /// Returns the captured snapshot of <see cref="ScopeContext"/> dictionary for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <returns>Dictionary with ScopeContext properties if any, else null</returns> protected IDictionary<string, object> GetScopeContextProperties(LogEventInfo logEvent) { if (logEvent.TryGetCachedLayoutValue(_contextLayout.ScopeContextPropertiesLayout, out object value)) { return value as IDictionary<string, object>; } return CaptureScopeContextProperties(logEvent, null); } /// <summary> /// Returns the captured snapshot of <see cref="MappedDiagnosticsLogicalContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <returns>Dictionary with MDLC context if any, else null</returns> [Obsolete("Replaced by GetScopeContextProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected IDictionary<string, object> GetContextMdlc(LogEventInfo logEvent) { if (logEvent.TryGetCachedLayoutValue(_contextLayout.ScopeContextPropertiesLayout, out object value)) { return value as IDictionary<string, object>; } return CaptureContextMdlc(logEvent, null); } /// <summary> /// Returns the captured snapshot of <see cref="NestedDiagnosticsContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <returns>Collection with NDC context if any, else null</returns> [Obsolete("Replaced by GetScopeContextNested. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected IList<object> GetContextNdc(LogEventInfo logEvent) { if (logEvent.TryGetCachedLayoutValue(_contextLayout.ScopeContextNestedStatesLayout, out object value)) { return value as IList<object>; } return CaptureContextNdc(logEvent); } /// <summary> /// Returns the captured snapshot of nested states from <see cref="ScopeContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <returns>Collection of nested state objects if any, else null</returns> protected IList<object> GetScopeContextNested(LogEventInfo logEvent) { if (logEvent.TryGetCachedLayoutValue(_contextLayout.ScopeContextNestedStatesLayout, out object value)) { return value as IList<object>; } return CaptureScopeContextNested(logEvent); } /// <summary> /// Returns the captured snapshot of <see cref="NestedDiagnosticsLogicalContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <returns>Collection with NDLC context if any, else null</returns> [Obsolete("Replaced by GetScopeContextNested. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected IList<object> GetContextNdlc(LogEventInfo logEvent) { if (logEvent.TryGetCachedLayoutValue(_contextLayout.ScopeContextNestedStatesLayout, out object value)) { return value as IList<object>; } return CaptureContextNdlc(logEvent); } private IDictionary<string, object> CaptureContextProperties(LogEventInfo logEvent, IDictionary<string, object> combinedProperties) { combinedProperties = combinedProperties ?? CreateNewDictionary(ContextProperties.Count); for (int i = 0; i < ContextProperties.Count; ++i) { var contextProperty = ContextProperties[i]; if (string.IsNullOrEmpty(contextProperty?.Name) || contextProperty.Layout is null) continue; try { if (TryGetContextPropertyValue(logEvent, contextProperty, out var propertyValue)) { combinedProperties[contextProperty.Name] = propertyValue; } } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; Common.InternalLogger.Warn(ex, "{0}: Failed to add context property {1}", this, contextProperty.Name); } } return combinedProperties; } private static bool TryGetContextPropertyValue(LogEventInfo logEvent, TargetPropertyWithContext contextProperty, out object propertyValue) { propertyValue = contextProperty.RenderValue(logEvent); if (!contextProperty.IncludeEmptyValue && (propertyValue is null || string.Empty.Equals(propertyValue))) { return false; } return true; } /// <summary> /// Takes snapshot of <see cref="GlobalDiagnosticsContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <param name="contextProperties">Optional pre-allocated dictionary for the snapshot</param> /// <returns>Dictionary with GDC context if any, else null</returns> protected virtual IDictionary<string, object> CaptureContextGdc(LogEventInfo logEvent, IDictionary<string, object> contextProperties) { var globalNames = GlobalDiagnosticsContext.GetNames(); if (globalNames.Count == 0) return contextProperties; contextProperties = contextProperties ?? CreateNewDictionary(globalNames.Count); bool checkForDuplicates = contextProperties.Count > 0; bool checkExcludeProperties = ExcludeProperties.Count > 0; foreach (string propertyName in globalNames) { if (string.IsNullOrEmpty(propertyName)) continue; if (checkExcludeProperties && ExcludeProperties.Contains(propertyName)) continue; var propertyValue = GlobalDiagnosticsContext.GetObject(propertyName); if (SerializeItemValue(logEvent, propertyName, propertyValue, out propertyValue)) { AddContextProperty(logEvent, propertyName, propertyValue, checkForDuplicates, contextProperties); } } return contextProperties; } /// <summary> /// Takes snapshot of <see cref="MappedDiagnosticsContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <param name="contextProperties">Optional pre-allocated dictionary for the snapshot</param> /// <returns>Dictionary with MDC context if any, else null</returns> [Obsolete("Replaced by CaptureScopeContextProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected virtual IDictionary<string, object> CaptureContextMdc(LogEventInfo logEvent, IDictionary<string, object> contextProperties) { var names = MappedDiagnosticsContext.GetNames(); if (names.Count == 0) return contextProperties; contextProperties = contextProperties ?? CreateNewDictionary(names.Count); bool checkForDuplicates = contextProperties.Count > 0; foreach (var name in names) { object value = MappedDiagnosticsContext.GetObject(name); if (SerializeMdcItem(logEvent, name, value, out var serializedValue)) { AddContextProperty(logEvent, name, serializedValue, checkForDuplicates, contextProperties); } } return contextProperties; } /// <summary> /// Take snapshot of a single object value from <see cref="MappedDiagnosticsContext"/> /// </summary> /// <param name="logEvent">Log event</param> /// <param name="name">MDC key</param> /// <param name="value">MDC value</param> /// <param name="serializedValue">Snapshot of MDC value</param> /// <returns>Include object value in snapshot</returns> [Obsolete("Replaced by SerializeScopeContextProperty. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected virtual bool SerializeMdcItem(LogEventInfo logEvent, string name, object value, out object serializedValue) { if (string.IsNullOrEmpty(name)) { serializedValue = null; return false; } return SerializeItemValue(logEvent, name, value, out serializedValue); } /// <summary> /// Takes snapshot of <see cref="MappedDiagnosticsLogicalContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <param name="contextProperties">Optional pre-allocated dictionary for the snapshot</param> /// <returns>Dictionary with MDLC context if any, else null</returns> [Obsolete("Replaced by CaptureScopeContextProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected virtual IDictionary<string, object> CaptureContextMdlc(LogEventInfo logEvent, IDictionary<string, object> contextProperties) { return CaptureScopeContextProperties(logEvent, contextProperties); } /// <summary> /// Takes snapshot of <see cref="ScopeContext"/> dictionary for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <param name="contextProperties">Optional pre-allocated dictionary for the snapshot</param> /// <returns>Dictionary with ScopeContext properties if any, else null</returns> protected virtual IDictionary<string, object> CaptureScopeContextProperties(LogEventInfo logEvent, IDictionary<string, object> contextProperties) { using (var scopeEnumerator = ScopeContext.GetAllPropertiesEnumerator()) { bool checkForDuplicates = contextProperties?.Count > 0; bool checkExcludeProperties = ExcludeProperties.Count > 0; while (scopeEnumerator.MoveNext()) { var scopeProperty = scopeEnumerator.Current; var propertyName = scopeProperty.Key; if (string.IsNullOrEmpty(propertyName)) continue; if (checkExcludeProperties && ExcludeProperties.Contains(propertyName)) continue; contextProperties = contextProperties ?? CreateNewDictionary(0); object propertyValue = scopeProperty.Value; if (SerializeScopeContextProperty(logEvent, propertyName, propertyValue, out var serializedValue)) { AddContextProperty(logEvent, propertyName, serializedValue, checkForDuplicates, contextProperties); } } } return contextProperties; } /// <summary> /// Take snapshot of a single object value from <see cref="MappedDiagnosticsLogicalContext"/> /// </summary> /// <param name="logEvent">Log event</param> /// <param name="name">MDLC key</param> /// <param name="value">MDLC value</param> /// <param name="serializedValue">Snapshot of MDLC value</param> /// <returns>Include object value in snapshot</returns> [Obsolete("Replaced by SerializeScopeContextProperty. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected bool SerializeMdlcItem(LogEventInfo logEvent, string name, object value, out object serializedValue) { return SerializeScopeContextProperty(logEvent, name, value, out serializedValue); } /// <summary> /// Take snapshot of a single object value from <see cref="ScopeContext"/> dictionary /// </summary> /// <param name="logEvent">Log event</param> /// <param name="name">ScopeContext Dictionary key</param> /// <param name="value">ScopeContext Dictionary value</param> /// <param name="serializedValue">Snapshot of ScopeContext property-value</param> /// <returns>Include object value in snapshot</returns> protected virtual bool SerializeScopeContextProperty(LogEventInfo logEvent, string name, object value, out object serializedValue) { if (string.IsNullOrEmpty(name)) { serializedValue = null; return false; } return SerializeItemValue(logEvent, name, value, out serializedValue); } /// <summary> /// Takes snapshot of <see cref="NestedDiagnosticsContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <returns>Collection with NDC context if any, else null</returns> [Obsolete("Replaced by CaptureScopeContextNested. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected virtual IList<object> CaptureContextNdc(LogEventInfo logEvent) { var stack = NestedDiagnosticsContext.GetAllObjects(); if (stack.Length == 0) return stack; IList<object> filteredStack = null; for (int i = 0; i < stack.Length; ++i) { var ndcValue = stack[i]; if (SerializeNdcItem(logEvent, ndcValue, out var serializedValue)) { if (filteredStack != null) filteredStack.Add(serializedValue); else stack[i] = serializedValue; } else { if (filteredStack is null) { filteredStack = new List<object>(stack.Length); for (int j = 0; j < i; ++j) filteredStack.Add(stack[j]); } } } return filteredStack ?? stack; } /// <summary> /// Take snapshot of a single object value from <see cref="NestedDiagnosticsContext"/> /// </summary> /// <param name="logEvent">Log event</param> /// <param name="value">NDC value</param> /// <param name="serializedValue">Snapshot of NDC value</param> /// <returns>Include object value in snapshot</returns> [Obsolete("Replaced by SerializeScopeContextNestedState. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected virtual bool SerializeNdcItem(LogEventInfo logEvent, object value, out object serializedValue) { return SerializeItemValue(logEvent, null, value, out serializedValue); } /// <summary> /// Takes snapshot of <see cref="NestedDiagnosticsLogicalContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <returns>Collection with NDLC context if any, else null</returns> [Obsolete("Replaced by CaptureScopeContextNested. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected virtual IList<object> CaptureContextNdlc(LogEventInfo logEvent) { return CaptureScopeContextNested(logEvent); } /// <summary> /// Takes snapshot of nested states from <see cref="ScopeContext"/> for the <see cref="LogEventInfo"/> /// </summary> /// <param name="logEvent"></param> /// <returns>Collection with <see cref="ScopeContext"/> stack items if any, else null</returns> protected virtual IList<object> CaptureScopeContextNested(LogEventInfo logEvent) { var stack = ScopeContext.GetAllNestedStateList(); if (stack.Count == 0) return stack; IList<object> filteredStack = null; for (int i = 0; i < stack.Count; ++i) { var ndcValue = stack[i]; if (SerializeScopeContextNestedState(logEvent, ndcValue, out var serializedValue)) { if (filteredStack != null) filteredStack.Add(serializedValue); else stack[i] = serializedValue; } else { if (filteredStack is null) { filteredStack = new List<object>(stack.Count); for (int j = 0; j < i; ++j) filteredStack.Add(stack[j]); } } } return filteredStack ?? stack; } /// <summary> /// Take snapshot of a single object value from <see cref="NestedDiagnosticsLogicalContext"/> /// </summary> /// <param name="logEvent">Log event</param> /// <param name="value">NDLC value</param> /// <param name="serializedValue">Snapshot of NDLC value</param> /// <returns>Include object value in snapshot</returns> [Obsolete("Replaced by SerializeScopeContextNestedState. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected virtual bool SerializeNdlcItem(LogEventInfo logEvent, object value, out object serializedValue) { return SerializeScopeContextNestedState(logEvent, value, out serializedValue); } /// <summary> /// Take snapshot of a single object value from <see cref="ScopeContext"/> nested states /// </summary> /// <param name="logEvent">Log event</param> /// <param name="value"><see cref="ScopeContext"/> nested state value</param> /// <param name="serializedValue">Snapshot of <see cref="ScopeContext"/> stack item value</param> /// <returns>Include object value in snapshot</returns> protected virtual bool SerializeScopeContextNestedState(LogEventInfo logEvent, object value, out object serializedValue) { return SerializeItemValue(logEvent, null, value, out serializedValue); } /// <summary> /// Take snapshot of a single object value /// </summary> /// <param name="logEvent">Log event</param> /// <param name="name">Key Name (null when NDC / NDLC)</param> /// <param name="value">Object Value</param> /// <param name="serializedValue">Snapshot of value</param> /// <returns>Include object value in snapshot</returns> protected virtual bool SerializeItemValue(LogEventInfo logEvent, string name, object value, out object serializedValue) { if (value is null) { serializedValue = null; return true; } if (value is string || Convert.GetTypeCode(value) != TypeCode.Object || value.GetType().IsValueType()) { serializedValue = value; // Already immutable, snapshot is not needed return true; } // Make snapshot of the context value serializedValue = Convert.ToString(value, logEvent.FormatProvider ?? LoggingConfiguration?.DefaultCultureInfo); return true; } [ThreadAgnostic] internal sealed class TargetWithContextLayout : Layout, IIncludeContext, IUsesStackTrace { public Layout TargetLayout { get => _targetLayout; set => _targetLayout = ReferenceEquals(this, value) ? _targetLayout : value; } private Layout _targetLayout; /// <summary>Internal Layout that allows capture of <see cref="ScopeContext"/> properties-dictionary</summary> internal LayoutScopeContextProperties ScopeContextPropertiesLayout { get; } /// <summary>Internal Layout that allows capture of <see cref="ScopeContext"/> nested-states-stack</summary> internal LayoutScopeContextNestedStates ScopeContextNestedStatesLayout { get; } public bool IncludeEventProperties { get; set; } public bool IncludeCallSite { get; set; } public bool IncludeCallSiteStackTrace { get; set; } public bool IncludeScopeProperties { get => _includeScopeProperties ?? ScopeContextPropertiesLayout.IsActive; set => _includeScopeProperties = ScopeContextPropertiesLayout.IsActive = value; } private bool? _includeScopeProperties; public bool IncludeScopeNested { get => _includeScopeNested ?? ScopeContextNestedStatesLayout.IsActive; set => _includeScopeNested = ScopeContextNestedStatesLayout.IsActive = value; } private bool? _includeScopeNested; [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] public bool IncludeMdc { get => _includeMdc ?? false; set { _includeMdc = value; ScopeContextPropertiesLayout.IsActive = _includeScopeProperties ?? (_includeMdlc == true || value); } } private bool? _includeMdc; [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] public bool IncludeMdlc { get => _includeMdlc ?? false; set { _includeMdlc = value; ScopeContextPropertiesLayout.IsActive = _includeScopeProperties ?? (_includeMdc == true || value); } } private bool? _includeMdlc; [Obsolete("Replaced by IncludeScopeNested. Marked obsolete on NLog 5.0")] public bool IncludeNdc { get => _includeNdc ?? false; set { _includeNdc = value; ScopeContextNestedStatesLayout.IsActive = _includeScopeNested ?? (_includeNdlc == true || value); } } private bool? _includeNdc; [Obsolete("Replaced by IncludeScopeNested. Marked obsolete on NLog 5.0")] public bool IncludeNdlc { get => _includeNdlc ?? false; set { _includeNdlc = value; ScopeContextNestedStatesLayout.IsActive = _includeScopeNested ?? (_includeNdc == true || value); } } private bool? _includeNdlc; StackTraceUsage IUsesStackTrace.StackTraceUsage { get { if (IncludeCallSiteStackTrace) { return StackTraceUsage.Max; } if (IncludeCallSite) { return StackTraceUsage.WithCallSite | StackTraceUsage.WithCallSiteClassName; } return StackTraceUsage.None; } } public TargetWithContextLayout(TargetWithContext owner, Layout targetLayout) { TargetLayout = targetLayout; ScopeContextPropertiesLayout = new LayoutScopeContextProperties(owner); ScopeContextNestedStatesLayout = new LayoutScopeContextNestedStates(owner); } protected override void InitializeLayout() { base.InitializeLayout(); if (IncludeScopeProperties || IncludeScopeNested) ThreadAgnostic = false; if (IncludeEventProperties) MutableUnsafe = true; // TODO Need to convert Properties to an immutable state } public override string ToString() { return TargetLayout?.ToString() ?? base.ToString(); } public override void Precalculate(LogEventInfo logEvent) { if (!(TargetLayout?.ThreadAgnostic ?? true) || (TargetLayout?.MutableUnsafe ?? false)) { TargetLayout.Precalculate(logEvent); if (logEvent.TryGetCachedLayoutValue(TargetLayout, out var cachedLayout)) { // Also cache the result as belonging to this Layout, for fast lookup logEvent.AddCachedLayoutValue(this, cachedLayout); } } PrecalculateContext(logEvent); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { if (!(TargetLayout?.ThreadAgnostic ?? true) || (TargetLayout?.MutableUnsafe ?? false)) { TargetLayout.PrecalculateBuilder(logEvent, target); if (logEvent.TryGetCachedLayoutValue(TargetLayout, out var cachedLayout)) { // Also cache the result as belonging to this Layout, for fast lookup logEvent.AddCachedLayoutValue(this, cachedLayout); } } PrecalculateContext(logEvent); } private void PrecalculateContext(LogEventInfo logEvent) { if (IncludeScopeProperties) ScopeContextPropertiesLayout.Precalculate(logEvent); if (IncludeScopeNested) ScopeContextNestedStatesLayout.Precalculate(logEvent); } protected override string GetFormattedMessage(LogEventInfo logEvent) { return TargetLayout?.Render(logEvent) ?? string.Empty; } protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { TargetLayout?.Render(logEvent, target); } public class LayoutScopeContextProperties : Layout { private readonly TargetWithContext _owner; public bool IsActive { get; set; } public LayoutScopeContextProperties(TargetWithContext owner) { _owner = owner; } protected override string GetFormattedMessage(LogEventInfo logEvent) { CaptureContext(logEvent); return string.Empty; } public override void Precalculate(LogEventInfo logEvent) { CaptureContext(logEvent); } private void CaptureContext(LogEventInfo logEvent) { if (IsActive && !logEvent.TryGetCachedLayoutValue(this, out var _)) { var scopeContextProperties = _owner.CaptureScopeContextProperties(logEvent, null); logEvent.AddCachedLayoutValue(this, scopeContextProperties); } } } public class LayoutScopeContextNestedStates : Layout { private readonly TargetWithContext _owner; public bool IsActive { get; set; } public LayoutScopeContextNestedStates(TargetWithContext owner) { _owner = owner; } protected override string GetFormattedMessage(LogEventInfo logEvent) { CaptureContext(logEvent); return string.Empty; } public override void Precalculate(LogEventInfo logEvent) { CaptureContext(logEvent); } private void CaptureContext(LogEventInfo logEvent) { if (IsActive && !logEvent.TryGetCachedLayoutValue(this, out var _)) { var nestedContext = _owner.CaptureScopeContextNested(logEvent); logEvent.AddCachedLayoutValue(this, nestedContext); } } } } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Linq; using NLog.MessageTemplates; using Xunit; namespace NLog.UnitTests.MessageTemplates { public class MessageTemplateParametersTests { [Theory] [InlineData("", 0)] [InlineData("Hello {0}", 1)] [InlineData("I like my {car}", 1)] [InlineData("I have {0} {1} {2} parameters", 3)] [InlineData("I have {a} {1} {2} parameters", 3)] [InlineData("I have {{text}} and {{0}}", 0)] [InlineData(" {3} {4} {9} {8} {5} {6} {7}", 7)] public void ParseParameters(string input, int expected) { // Arrange var parameters = CreateParameters(expected); // Act var messageTemplateParameters = new MessageTemplateParameters(input, parameters); // Assert Assert.Equal(expected, messageTemplateParameters.Count); } [Theory] [InlineData("", true)] // no really important when empty [InlineData("{0}", true)] [InlineData("{ 0}", false)] //no trimming [InlineData("{0} {1} {2}", true)] [InlineData("{a}", false)] [InlineData("{a} {0}", false)] [InlineData("{0} {a}", false)] [InlineData("{0} {a} {1}", false)] public void IsPositionalTest(string input, bool expected) { // Arrange var parameters = CreateParameters(10); // Act var messageTemplateParameters = new MessageTemplateParameters(input, parameters); // Assert Assert.Equal(expected, messageTemplateParameters.IsPositional); } [Theory] [InlineData("{0}", 0, "0", "0", 0, CaptureType.Normal)] [InlineData("{a}", 0, "0", "a", null, CaptureType.Normal)] public void IndexerTest(string input, int index, object expectedValue, string expectedName, int? expectedPositionalIndex, CaptureType expectedCaptureType) { // Arrange var parameters = CreateParameters(1); // Act var messageTemplateParameters = new MessageTemplateParameters(input, parameters); // Assert Assert.Equal(expectedValue, messageTemplateParameters[index].Value); Assert.Equal(expectedName, messageTemplateParameters[index].Name); Assert.Equal(expectedPositionalIndex, messageTemplateParameters[index].PositionalIndex); Assert.Equal(expectedCaptureType, messageTemplateParameters[index].CaptureType); } [Theory] [InlineData("{a}", "a")] [InlineData("{a} {b}", "a;b")] [InlineData("{b} {0} {a} ", "b;0;a")] public void EnumeratorTest(string input, string namesRaw) { // Arrange var parameters = CreateParameters(1); var names = namesRaw.Split(';'); // Act var messageTemplateParameters = new MessageTemplateParameters(input, parameters); // Assert var resultNames = messageTemplateParameters.Select(t => t.Name).ToArray(); Assert.Equal(names, resultNames); } [Theory] [InlineData("", 0, true)] //empty OK [InlineData(" ", 0, true)] //empty OK [InlineData("", 1, false)] [InlineData("{0}", 1, true)] [InlineData("{A}", 1, true)] //[InlineData("{A}", 0, false)] [InlineData("{A}", 2, false)] [InlineData("{ 0}", 1, true)] //[InlineData("{0} {1}", 0, false)] [InlineData("{0} {1}", 1, false)] [InlineData("{0} {1}", 2, true)] //[InlineData("{0} {A}", 0, false)] [InlineData("{0} {A}", 1, false)] [InlineData("{0} {A}", 2, true)] //[InlineData("{A} {1}", 0, false)] [InlineData("{A} {1}", 1, false)] [InlineData("{A} {1}", 2, true)] //[InlineData("{A} {B}", 0, false)] [InlineData("{A} {B}", 1, false)] [InlineData("{A} {B}", 2, true)] //[InlineData("{0} {0}", 0, false)] [InlineData("{0} {0}", 1, true)] [InlineData("{0} {0}", 2, false)] //[InlineData("{A} {A}", 0, false)] [InlineData("{A} {A}", 1, false)] [InlineData("{A} {A}", 2, true)] //overwrite public void IsValidTemplateTest(string input, int parameterCount, bool expected) { // Arrange var parameters = CreateParameters(parameterCount); // Act var messageTemplateParameters = new MessageTemplateParameters(input, parameters); // Assert Assert.Equal(expected, messageTemplateParameters.IsValidTemplate); } private static object[] CreateParameters(int count) { var parameters = new List<object>(count); for (int i = 0; i < count; i++) { parameters.Add(i.ToString()); } return parameters.ToArray(); } } } <file_sep>using NLog; using NLog.Targets; using NLog.Targets.Wrappers; using System.Text; class Example { static void Main(string[] args) { FileTarget target = new FileTarget(); target.Layout = "${longdate} ${logger} ${message}"; target.FileName = "${basedir}/logs/logfile.txt"; target.KeepFileOpen = false; target.Encoding = Encoding.UTF8; AsyncTargetWrapper wrapper = new AsyncTargetWrapper(); wrapper.WrappedTarget = target; wrapper.QueueLimit = 5000; wrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Discard; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(wrapper, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Linq; using NLog.Internal; namespace NLog { /// <summary> /// <see cref="ScopeContext"/> stores state in the async thread execution context. All LogEvents created /// within a scope can include the scope state in the target output. The logical context scope supports /// both scope-properties and scope-nested-state-stack (Similar to log4j2 ThreadContext) /// </summary> /// <remarks> /// <see cref="MappedDiagnosticsLogicalContext"/> (MDLC), <see cref="MappedDiagnosticsContext"/> (MDC), <see cref="NestedDiagnosticsLogicalContext"/> (NDLC) /// and <see cref="NestedDiagnosticsContext"/> (NDC) have been deprecated and replaced by <see cref="ScopeContext"/>. /// /// .NetCore (and .Net46) uses AsyncLocal for handling the thread execution context. Older .NetFramework uses System.Runtime.Remoting.CallContext /// </remarks> public static class ScopeContext { internal static readonly IEqualityComparer<string> DefaultComparer = StringComparer.OrdinalIgnoreCase; #if !NET35 && !NET40 /// <summary> /// Pushes new state on the logical context scope stack together with provided properties /// </summary> /// <param name="nestedState">Value to added to the scope stack</param> /// <param name="properties">Properties being added to the scope dictionary</param> /// <returns>A disposable object that pops the nested scope state on dispose (including properties).</returns> /// <remarks>Scope dictionary keys are case-insensitive</remarks> public static IDisposable PushNestedStateProperties(object nestedState, IReadOnlyCollection<KeyValuePair<string, object>> properties) { properties = properties ?? ArrayHelper.Empty<KeyValuePair<string, object>>(); if (properties.Count > 0 || nestedState is null) { #if !NET45 var parent = GetAsyncLocalContext(); if (nestedState is null) { var allProperties = ScopeContextPropertiesCollapsed.BuildCollapsedDictionary(parent, properties.Count); if (allProperties != null) { // Collapse all 3 property-scopes into a collapsed scope, and return bookmark that can restore original parent (Avoid huge object-graphs) ScopeContextPropertyEnumerator<object>.CopyScopePropertiesToDictionary(properties, allProperties); var collapsedState = new ScopeContextPropertiesAsyncState<object>(parent.Parent.Parent, allProperties, nestedState); SetAsyncLocalContext(collapsedState); return new ScopeContextPropertiesCollapsed(parent, collapsedState); } } var current = new ScopeContextPropertiesAsyncState<object>(parent, properties, nestedState); SetAsyncLocalContext(current); return current; #else var oldMappedContext = PushPropertiesCallContext(properties); var oldNestedContext = nestedState is null ? null : PushNestedStateCallContext(nestedState); return new ScopeContextNestedStateProperties(oldNestedContext, oldMappedContext); #endif } else { return PushNestedState(nestedState); } } #endif #if !NET35 && !NET40 /// <summary> /// Updates the logical scope context with provided properties /// </summary> /// <param name="properties">Properties being added to the scope dictionary</param> /// <returns>A disposable object that removes the properties from logical context scope on dispose.</returns> /// <remarks>Scope dictionary keys are case-insensitive</remarks> public static IDisposable PushProperties(IReadOnlyCollection<KeyValuePair<string, object>> properties) { return PushProperties<object>(properties); } /// <summary> /// Updates the logical scope context with provided properties /// </summary> /// <param name="properties">Properties being added to the scope dictionary</param> /// <returns>A disposable object that removes the properties from logical context scope on dispose.</returns> /// <remarks>Scope dictionary keys are case-insensitive</remarks> public static IDisposable PushProperties<TValue>(IReadOnlyCollection<KeyValuePair<string, TValue>> properties) { #if !NET45 var parent = GetAsyncLocalContext(); var allProperties = ScopeContextPropertiesCollapsed.BuildCollapsedDictionary(parent, properties.Count); if (allProperties != null) { // Collapse all 3 property-scopes into a collapsed scope, and return bookmark that can restore original parent (Avoid huge object-graphs) ScopeContextPropertyEnumerator<TValue>.CopyScopePropertiesToDictionary(properties, allProperties); var collapsedState = new ScopeContextPropertiesAsyncState<object>(parent.Parent.Parent, allProperties); SetAsyncLocalContext(collapsedState); return new ScopeContextPropertiesCollapsed(parent, collapsedState); } var current = new ScopeContextPropertiesAsyncState<TValue>(parent, properties); SetAsyncLocalContext(current); return current; #else var oldContext = PushPropertiesCallContext(properties); return new ScopeContextProperties(oldContext); #endif } #endif /// <summary> /// Updates the logical scope context with provided property /// </summary> /// <param name="key">Name of property</param> /// <param name="value">Value of property</param> /// <returns>A disposable object that removes the properties from logical context scope on dispose.</returns> /// <remarks>Scope dictionary keys are case-insensitive</remarks> public static IDisposable PushProperty<TValue>(string key, TValue value) { #if !NET35 && !NET40 && !NET45 var parent = GetAsyncLocalContext(); var allProperties = ScopeContextPropertiesCollapsed.BuildCollapsedDictionary(parent, 1); if (allProperties != null) { // Collapse all 3 property-scopes into a collapsed scope, and return bookmark that can restore original parent (Avoid huge object-graphs) allProperties[key] = value; var collapsedState = new ScopeContextPropertiesAsyncState<object>(parent.Parent.Parent, allProperties); SetAsyncLocalContext(collapsedState); return new ScopeContextPropertiesCollapsed(parent, collapsedState); } var current = new ScopeContextPropertyAsyncState<TValue>(parent, key, value); SetAsyncLocalContext(current); return current; #else var oldContext = PushPropertyCallContext(key, value); return new ScopeContextProperties(oldContext); #endif } /// <summary> /// Updates the logical scope context with provided property /// </summary> /// <param name="key">Name of property</param> /// <param name="value">Value of property</param> /// <returns>A disposable object that removes the properties from logical context scope on dispose.</returns> /// <remarks>Scope dictionary keys are case-insensitive</remarks> public static IDisposable PushProperty(string key, object value) { return PushProperty<object>(key, value); } /// <summary> /// Pushes new state on the logical context scope stack /// </summary> /// <param name="nestedState">Value to added to the scope stack</param> /// <returns>A disposable object that pops the nested scope state on dispose.</returns> /// <remarks>Skips casting of <paramref name="nestedState"/> to check for scope-properties</remarks> public static IDisposable PushNestedState<T>(T nestedState) { #if !NET35 && !NET40 && !NET45 var parent = GetAsyncLocalContext(); var current = new ScopedContextNestedAsyncState<T>(parent, nestedState); SetAsyncLocalContext(current); return current; #else object objectValue = nestedState; var oldNestedContext = PushNestedStateCallContext(objectValue); return new ScopeContextNestedState(oldNestedContext, objectValue); #endif } /// <summary> /// Pushes new state on the logical context scope stack /// </summary> /// <param name="nestedState">Value to added to the scope stack</param> /// <returns>A disposable object that pops the nested scope state on dispose.</returns> public static IDisposable PushNestedState(object nestedState) { return PushNestedState<object>(nestedState); } /// <summary> /// Clears all the entire logical context scope, and removes any properties and nested-states /// </summary> public static void Clear() { #if !NET35 && !NET40 && !NET45 SetAsyncLocalContext(null); #else ClearMappedContextCallContext(); ClearNestedContextCallContext(); #endif } /// <summary> /// Retrieves all properties stored within the logical context scopes /// </summary> /// <returns>Collection of all properties</returns> public static IEnumerable<KeyValuePair<string, object>> GetAllProperties() { #if !NET35 && !NET40 && !NET45 var contextState = GetAsyncLocalContext(); var propertyCollector = new ScopeContextPropertyCollector(); return contextState?.CaptureContextProperties(ref propertyCollector) ?? ArrayHelper.Empty<KeyValuePair<string, object>>(); #else var mappedContext = GetMappedContextCallContext(); if (mappedContext?.Count > 0) { foreach (var item in mappedContext) { if (item.Value is ObjectHandleSerializer) { return GetAllPropertiesUnwrapped(mappedContext); } } return mappedContext; } return ArrayHelper.Empty<KeyValuePair<string, object>>(); #endif } internal static ScopeContextPropertyEnumerator<object> GetAllPropertiesEnumerator() { return new ScopeContextPropertyEnumerator<object>(GetAllProperties()); } /// <summary> /// Lookup single property stored within the logical context scopes /// </summary> /// <param name="key">Name of property</param> /// <param name="value">When this method returns, contains the value associated with the specified key</param> /// <returns>Returns true when value is found with the specified key</returns> /// <remarks>Scope dictionary keys are case-insensitive</remarks> public static bool TryGetProperty(string key, out object value) { #if !NET35 && !NET40 && !NET45 var contextState = GetAsyncLocalContext(); if (contextState != null) { var propertyCollector = new ScopeContextPropertyCollector(); var mappedContext = contextState.CaptureContextProperties(ref propertyCollector); if (mappedContext?.Count > 0) { return TryLookupProperty(mappedContext, key, out value); } } value = null; return false; #else var mappedContext = GetMappedContextCallContext(); if (mappedContext != null && mappedContext.TryGetValue(key, out value)) { if (value is ObjectHandleSerializer objectHandle) value = objectHandle.Unwrap(); return true; } value = null; return false; #endif } /// <summary> /// Retrieves all nested states inside the logical context scope stack /// </summary> /// <returns>Array of nested state objects.</returns> public static object[] GetAllNestedStates() { #if !NET35 && !NET40 && !NET45 var nestedStates = GetAllNestedStateList(); if (nestedStates?.Count > 0) { if (nestedStates is object[] nestedArray) return nestedArray; else return Enumerable.ToArray(nestedStates); } return ArrayHelper.Empty<object>(); #else var currentContext = GetNestedContextCallContext(); if (currentContext?.Count > 0) { int index = 0; object[] messages = new object[currentContext.Count]; foreach (var node in currentContext) { if (node is ObjectHandleSerializer objectHandle) messages[index++] = objectHandle.Unwrap(); else messages[index++] = node; } return messages; } return ArrayHelper.Empty<object>(); #endif } #if !NET35 && !NET40 && !NET45 internal static IList<object> GetAllNestedStateList() { var parent = GetAsyncLocalContext(); var nestedStateCollector = new ScopeContextNestedStateCollector(); return parent?.CaptureNestedContext(ref nestedStateCollector) ?? ArrayHelper.Empty<object>(); } #else internal static IList<object> GetAllNestedStateList() { return GetAllNestedStates(); } #endif /// <summary> /// Peeks the top value from the logical context scope stack /// </summary> /// <returns>Value from the top of the stack.</returns> public static object PeekNestedState() { #if !NET35 && !NET40 && !NET45 var parent = GetAsyncLocalContext(); while (parent != null) { var nestedContext = parent.NestedState; if (nestedContext != null) return nestedContext; parent = parent.Parent; } return null; #else var currentContext = GetNestedContextCallContext(); var objectValue = currentContext?.Count > 0 ? currentContext.First.Value : null; if (objectValue is ObjectHandleSerializer objectHandle) objectValue = objectHandle.Unwrap(); return objectValue; #endif } /// <summary> /// Peeks the inner state (newest) from the logical context scope stack, and returns its running duration /// </summary> /// <returns>Scope Duration Time</returns> internal static TimeSpan? PeekInnerNestedDuration() { #if !NET35 && !NET40 && !NET45 var stopwatchNow = GetNestedContextTimestampNow(); // Early timestamp to reduce chance of measuring NLog time var parent = GetAsyncLocalContext(); while (parent != null) { var scopeTimestamp = parent.NestedStateTimestamp; if (scopeTimestamp != 0) { return GetNestedStateDuration(scopeTimestamp, stopwatchNow); } parent = parent.Parent; } return null; #else return default(TimeSpan?); // Delay timing only supported when using AsyncLocal. CallContext is sensitive to custom state #endif } /// <summary> /// Peeks the outer state (oldest) from the logical context scope stack, and returns its running duration /// </summary> /// <returns>Scope Duration Time</returns> internal static TimeSpan? PeekOuterNestedDuration() { #if !NET35 && !NET40 && !NET45 var stopwatchNow = GetNestedContextTimestampNow(); // Early timestamp to reduce chance of measuring NLog time var parent = GetAsyncLocalContext(); var scopeTimestamp = 0L; while (parent != null) { if (parent.NestedStateTimestamp != 0) scopeTimestamp = parent.NestedStateTimestamp; parent = parent.Parent; } if (scopeTimestamp != 0L) { return GetNestedStateDuration(scopeTimestamp, stopwatchNow); } return null; #else return default(TimeSpan?); // Delay timing only supported when using AsyncLocal. CallContext is sensitive to custom state #endif } #if !NET35 && !NET40 && !NET45 private static bool TryLookupProperty(IReadOnlyCollection<KeyValuePair<string, object>> scopeProperties, string key, out object value) { if (scopeProperties is Dictionary<string, object> mappedDictionary && ReferenceEquals(mappedDictionary.Comparer, DefaultComparer)) { return mappedDictionary.TryGetValue(key, out value); } else { using (var scopeEnumerator = new ScopeContextPropertyEnumerator<object>(scopeProperties)) { while (scopeEnumerator.MoveNext()) { var item = scopeEnumerator.Current; if (DefaultComparer.Equals(item.Key, key)) { value = item.Value; return true; } } } value = null; return false; } } internal static long GetNestedContextTimestampNow() { if (System.Diagnostics.Stopwatch.IsHighResolution) return System.Diagnostics.Stopwatch.GetTimestamp(); else return System.Environment.TickCount; } private static TimeSpan GetNestedStateDuration(long scopeTimestamp, long currentTimestamp) { if (System.Diagnostics.Stopwatch.IsHighResolution) return TimeSpan.FromTicks((currentTimestamp - scopeTimestamp) * TimeSpan.TicksPerSecond / System.Diagnostics.Stopwatch.Frequency); else return TimeSpan.FromMilliseconds((int)currentTimestamp - (int)scopeTimestamp); } /// <summary> /// Special bookmark that can restore original parent, after scopes has been collapsed /// </summary> private sealed class ScopeContextPropertiesCollapsed : IDisposable { private readonly IScopeContextAsyncState _parent; private readonly IScopeContextPropertiesAsyncState _collapsed; private bool _disposed; public ScopeContextPropertiesCollapsed(IScopeContextAsyncState parent, IScopeContextPropertiesAsyncState collapsed) { _parent = parent; _collapsed = collapsed; } public static Dictionary<string, object> BuildCollapsedDictionary(IScopeContextAsyncState parent, int initialCapacity) { if (parent is IScopeContextPropertiesAsyncState parentProperties && parentProperties.Parent is IScopeContextPropertiesAsyncState grandParentProperties) { if (parentProperties.NestedState is null && grandParentProperties.NestedState is null) { var propertyCollectorList = new List<KeyValuePair<string, object>>(); // Marks the collector as active var propertyCollector = new ScopeContextPropertyCollector(propertyCollectorList); var propertyCollection = propertyCollector.StartCaptureProperties(parent); if (propertyCollectorList.Count > 0 && propertyCollection is Dictionary<string, object> propertyDictionary) return propertyDictionary; // New property collector was built from the list propertyDictionary = new Dictionary<string, object>(propertyCollection.Count + initialCapacity, ScopeContext.DefaultComparer); ScopeContextPropertyEnumerator<object>.CopyScopePropertiesToDictionary(propertyCollection, propertyDictionary); return propertyDictionary; } } return null; } public void Dispose() { if (_disposed) return; _disposed = true; SetAsyncLocalContext(_parent); } public override string ToString() { return _collapsed.ToString(); } } internal static void SetAsyncLocalContext(IScopeContextAsyncState newValue) { AsyncNestedDiagnosticsContext.Value = newValue; } private static IScopeContextAsyncState GetAsyncLocalContext() { return AsyncNestedDiagnosticsContext.Value; } private static readonly System.Threading.AsyncLocal<IScopeContextAsyncState> AsyncNestedDiagnosticsContext = new System.Threading.AsyncLocal<IScopeContextAsyncState>(); #endif #if NET45 private sealed class ScopeContextNestedStateProperties : IDisposable { private readonly LinkedList<object> _parentNestedContext; private readonly Dictionary<string, object> _parentMappedContext; public ScopeContextNestedStateProperties(LinkedList<object> parentNestedContext, Dictionary<string, object> parentMappedContext) { _parentNestedContext = parentNestedContext; _parentMappedContext = parentMappedContext; } public void Dispose() { if (_parentNestedContext != null) SetNestedContextCallContext(_parentNestedContext); SetMappedContextCallContext(_parentMappedContext); } } #endif [Obsolete("Replaced by ScopeContext.PushProperty. Marked obsolete on NLog 5.0")] internal static void SetMappedContextLegacy<TValue>(string key, TValue value) { #if !NET35 && !NET40 && !NET45 PushProperty(key, value); #else PushPropertyCallContext(key, value); #endif } internal static ICollection<string> GetKeysMappedContextLegacy() { #if !NET35 && !NET40 && !NET45 var contextState = GetAsyncLocalContext(); var propertyCollector = new ScopeContextPropertyCollector(); var scopeProperties = contextState?.CaptureContextProperties(ref propertyCollector); if (scopeProperties?.Count > 0) { if (scopeProperties.Count == 1) return new[] { Enumerable.First(scopeProperties).Key }; else if (scopeProperties is IDictionary<string, object> dictionary) return dictionary.Keys; else return scopeProperties.Select(prop => prop.Key).ToList(); } return ArrayHelper.Empty<string>(); #else return GetMappedContextCallContext()?.Keys ?? (ICollection<string>)ArrayHelper.Empty<string>(); #endif } [Obsolete("Replaced by disposing return value from ScopeContext.PushProperty. Marked obsolete on NLog 5.0")] internal static void RemoveMappedContextLegacy(string key) { #if !NET35 && !NET40 && !NET45 if (TryGetProperty(key, out var _)) { // Replace with new legacy-scope, the legacy-scope can be discarded when previous parent scope is restored var contextState = GetAsyncLocalContext(); ScopeContextLegacyAsyncState.CaptureLegacyContext(contextState, out var allProperties, out var scopeNestedStates, out var scopeNestedStateTimestamp); allProperties.Remove(key); var legacyScope = new ScopeContextLegacyAsyncState(allProperties, scopeNestedStates, scopeNestedStateTimestamp); SetAsyncLocalContext(legacyScope); } #else var oldContext = GetMappedContextCallContext(); if (oldContext?.ContainsKey(key) == true) { var newContext = CloneMappedContext(oldContext, 0); newContext.Remove(key); SetMappedContextCallContext(newContext); } #endif } [Obsolete("Replaced by disposing return value from ScopeContext.PushNestedState. Marked obsolete on NLog 5.0")] internal static object PopNestedContextLegacy() { #if !NET35 && !NET40 && !NET45 var contextState = GetAsyncLocalContext(); if (contextState != null) { if ((contextState.Parent is null && contextState is ScopeContextLegacyAsyncState) || contextState.NestedState is null) { var nestedStateCollector = new ScopeContextNestedStateCollector(); var nestedStates = contextState.CaptureNestedContext(ref nestedStateCollector) ?? ArrayHelper.Empty<object>(); if (nestedStates.Count == 0) return null; // Nothing to pop, just leave scope alone // Replace with new legacy-scope, the legacy-scope can be discarded when previous parent scope is restored var propertyCollector = new ScopeContextPropertyCollector(); var stackTopValue = nestedStates[0]; var allProperties = contextState.CaptureContextProperties(ref propertyCollector) ?? ArrayHelper.Empty<KeyValuePair<string, object>>(); var nestedContext = ArrayHelper.Empty<object>(); if (nestedStates.Count > 1) { nestedContext = new object[nestedStates.Count - 1]; for (int i = 0; i < nestedContext.Length; ++i) nestedContext[i] = nestedStates[i + 1]; } var legacyScope = new ScopeContextLegacyAsyncState(allProperties, nestedContext, nestedContext.Length > 0 ? GetNestedContextTimestampNow() : 0L); SetAsyncLocalContext(legacyScope); return stackTopValue; } else { SetAsyncLocalContext(contextState.Parent); return contextState.NestedState; } } return null; #else var currentContext = GetNestedContextCallContext(); if (currentContext?.Count > 0) { var objectValue = currentContext.First.Value; if (objectValue is ObjectHandleSerializer objectHandle) objectValue = objectHandle.Unwrap(); var newContext = currentContext.Count > 1 ? new LinkedList<object>(currentContext) : null; if (newContext != null) newContext.RemoveFirst(); SetNestedContextCallContext(newContext); return objectValue; } return null; #endif } [Obsolete("Replaced by ScopeContext.Clear. Marked obsolete on NLog 5.0")] internal static void ClearMappedContextLegacy() { #if !NET35 && !NET40 && !NET45 var contextState = GetAsyncLocalContext(); if (contextState != null) { ScopeContextLegacyAsyncState.CaptureLegacyContext(contextState, out var allProperties, out var nestedContext, out var nestedContextTimestamp); if (nestedContext?.Length > 0) { if (allProperties?.Count > 0) { var legacyScope = new ScopeContextLegacyAsyncState(null, nestedContext, nestedContextTimestamp); SetAsyncLocalContext(legacyScope); } } else { SetAsyncLocalContext(null); } } #else ClearMappedContextCallContext(); #endif } [Obsolete("Replaced by ScopeContext.Clear. Marked obsolete on NLog 5.0")] internal static void ClearNestedContextLegacy() { #if !NET35 && !NET40 && !NET45 var contextState = GetAsyncLocalContext(); if (contextState != null) { ScopeContextLegacyAsyncState.CaptureLegacyContext(contextState, out var allProperties, out var nestedContext, out var nestedContextTimestamp); if (allProperties?.Count > 0) { if (nestedContext?.Length > 0) { var legacyScope = new ScopeContextLegacyAsyncState(allProperties, ArrayHelper.Empty<object>(), 0L); SetAsyncLocalContext(legacyScope); } } else { SetAsyncLocalContext(null); } } #else ClearNestedContextCallContext(); #endif } #if NET35 || NET40 || NET45 #if !NET35 && !NET40 private static Dictionary<string, object> PushPropertiesCallContext<TValue>(IReadOnlyCollection<KeyValuePair<string, TValue>> properties) { var oldContext = GetMappedContextCallContext(); var newContext = CloneMappedContext(oldContext, properties.Count); using (var scopeEnumerator = new ScopeContextPropertyEnumerator<TValue>(properties)) { while (scopeEnumerator.MoveNext()) { var item = scopeEnumerator.Current; SetPropertyCallContext(item.Key, item.Value, newContext); } } SetMappedContextCallContext(newContext); return oldContext; } #endif private static Dictionary<string, object> PushPropertyCallContext<TValue>(string propertyName, TValue propertyValue) { var oldContext = GetMappedContextCallContext(); var newContext = CloneMappedContext(oldContext, 1); SetPropertyCallContext(propertyName, propertyValue, newContext); SetMappedContextCallContext(newContext); return oldContext; } private static void ClearMappedContextCallContext() { SetMappedContextCallContext(null); } private static IEnumerable<KeyValuePair<string, object>> GetAllPropertiesUnwrapped(Dictionary<string, object> properties) { foreach (var item in properties) { if (item.Value is ObjectHandleSerializer objectHandle) { yield return new KeyValuePair<string, object>(item.Key, objectHandle.Unwrap()); } else { yield return item; } } } private static Dictionary<string, object> CloneMappedContext(Dictionary<string, object> oldContext, int initialCapacity = 0) { if (oldContext?.Count > 0) { var dictionary = new Dictionary<string, object>(oldContext.Count + initialCapacity, DefaultComparer); foreach (var keyValue in oldContext) dictionary[keyValue.Key] = keyValue.Value; return dictionary; } return new Dictionary<string, object>(initialCapacity, DefaultComparer); } private static void SetPropertyCallContext<TValue>(string item, TValue value, IDictionary<string, object> mappedContext) { object objectValue = value; if (Convert.GetTypeCode(objectValue) != TypeCode.Object) mappedContext[item] = objectValue; else mappedContext[item] = new ObjectHandleSerializer(objectValue); } private sealed class ScopeContextProperties : IDisposable { private readonly Dictionary<string, object> _oldContext; private bool _diposed; public ScopeContextProperties(Dictionary<string, object> oldContext) { _oldContext = oldContext; } public void Dispose() { if (!_diposed) { SetMappedContextCallContext(_oldContext); _diposed = true; } } } private static void SetMappedContextCallContext(Dictionary<string, object> newValue) { if (newValue is null) System.Runtime.Remoting.Messaging.CallContext.FreeNamedDataSlot(MappedContextDataSlotName); else System.Runtime.Remoting.Messaging.CallContext.LogicalSetData(MappedContextDataSlotName, newValue); } internal static Dictionary<string, object> GetMappedContextCallContext() { return System.Runtime.Remoting.Messaging.CallContext.LogicalGetData(MappedContextDataSlotName) as Dictionary<string, object>; } private const string MappedContextDataSlotName = "NLog.AsyncableMappedDiagnosticsContext"; private static LinkedList<object> PushNestedStateCallContext(object objectValue) { var oldContext = GetNestedContextCallContext(); var newContext = oldContext?.Count > 0 ? new LinkedList<object>(oldContext) : new LinkedList<object>(); if (Convert.GetTypeCode(objectValue) == TypeCode.Object) objectValue = new ObjectHandleSerializer(objectValue); newContext.AddFirst(objectValue); SetNestedContextCallContext(newContext); return oldContext; } private static void ClearNestedContextCallContext() { SetNestedContextCallContext(null); } private sealed class ScopeContextNestedState : IDisposable { private readonly LinkedList<object> _oldContext; private readonly object _nestedState; private bool _diposed; public ScopeContextNestedState(LinkedList<object> oldContext, object nestedState) { _oldContext = oldContext; _nestedState = nestedState; } public void Dispose() { if (!_diposed) { SetNestedContextCallContext(_oldContext); _diposed = true; } } public override string ToString() { return _nestedState?.ToString() ?? "null"; } } [System.Security.SecuritySafeCriticalAttribute] private static void SetNestedContextCallContext(LinkedList<object> nestedContext) { if (nestedContext is null) System.Runtime.Remoting.Messaging.CallContext.FreeNamedDataSlot(NestedContextDataSlotName ); else System.Runtime.Remoting.Messaging.CallContext.LogicalSetData(NestedContextDataSlotName , nestedContext); } [System.Security.SecuritySafeCriticalAttribute] private static LinkedList<object> GetNestedContextCallContext() { return System.Runtime.Remoting.Messaging.CallContext.LogicalGetData(NestedContextDataSlotName ) as LinkedList<object>; } private const string NestedContextDataSlotName = "NLog.AsyncNestedDiagnosticsLogicalContext"; #endif } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.ComponentModel; using System.Reflection; using NLog.Config; using NLog.Internal; using NLog.Layouts; using NLog.LayoutRenderers; using NLog.Targets; using System.Diagnostics.CodeAnalysis; /// <summary> /// Extension methods to setup NLog extensions, so they are known when loading NLog LoggingConfiguration /// </summary> public static class SetupExtensionsBuilderExtensions { /// <summary> /// Enable/disables autoloading of NLog extensions by scanning and loading available assemblies /// </summary> /// <remarks> /// Disabled by default as it can give a huge performance hit during startup. Recommended to keep it disabled especially when running in the cloud. /// </remarks> [Obsolete("AutoLoadAssemblies(true) has been replaced by AutoLoadExtensions(), that matches the name of nlog-attribute in NLog.config. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public static ISetupExtensionsBuilder AutoLoadAssemblies(this ISetupExtensionsBuilder setupBuilder, bool enable) { if (enable) AutoLoadExtensions(setupBuilder); return setupBuilder; } /// <summary> /// Enable/disables autoloading of NLog extensions by scanning and loading available assemblies /// </summary> /// <remarks> /// Disabled by default as it can give a huge performance hit during startup. Recommended to keep it disabled especially when running in the cloud. /// </remarks> public static ISetupExtensionsBuilder AutoLoadExtensions(this ISetupExtensionsBuilder setupBuilder) { ConfigurationItemFactory.Default.AssemblyLoader.ScanForAutoLoadExtensions(ConfigurationItemFactory.Default); return setupBuilder; } /// <summary> /// Registers NLog extensions from the assembly. /// </summary> public static ISetupExtensionsBuilder RegisterAssembly(this ISetupExtensionsBuilder setupBuilder, Assembly assembly) { #pragma warning disable CS0618 // Type or member is obsolete ConfigurationItemFactory.Default.RegisterItemsFromAssembly(assembly); #pragma warning restore CS0618 // Type or member is obsolete return setupBuilder; } /// <summary> /// Registers NLog extensions from the assembly type name /// </summary> public static ISetupExtensionsBuilder RegisterAssembly(this ISetupExtensionsBuilder setupBuilder, string assemblyName) { ConfigurationItemFactory.Default.AssemblyLoader.LoadAssemblyFromName(ConfigurationItemFactory.Default, assemblyName, string.Empty); return setupBuilder; } /// <summary> /// Register a custom NLog Configuration Type. /// </summary> /// <typeparam name="T">Type of the NLog configuration item</typeparam> /// <param name="setupBuilder">Fluent interface parameter.</param> public static ISetupExtensionsBuilder RegisterType<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicMethods)] T>(this ISetupExtensionsBuilder setupBuilder) where T : class, new() { ConfigurationItemFactory.Default.RegisterType<T>(); return setupBuilder; } /// <summary> /// Register a custom NLog Target. /// </summary> /// <typeparam name="T">Type of the Target.</typeparam> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="name">The target type-alias for use in NLog configuration. Will extract from class-attribute when unassigned.</param> public static ISetupExtensionsBuilder RegisterTarget<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(this ISetupExtensionsBuilder setupBuilder, string name = null) where T : Target, new() { return RegisterTarget<T>(setupBuilder, () => new T(), name); } /// <summary> /// Register a custom NLog Target. /// </summary> /// <typeparam name="T">Type of the Target.</typeparam> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="factory">The factory method for creating instance of NLog Target</param> /// <param name="typeAlias">The target type-alias for use in NLog configuration. Will extract from class-attribute when unassigned.</param> public static ISetupExtensionsBuilder RegisterTarget<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(this ISetupExtensionsBuilder setupBuilder, Func<T> factory, string typeAlias = null) where T : Target { typeAlias = string.IsNullOrEmpty(typeAlias) ? typeof(T).GetFirstCustomAttribute<TargetAttribute>()?.Name : typeAlias; if (string.IsNullOrEmpty(typeAlias)) { typeAlias = ResolveTypeAlias<T>("TargetWrapper", "Target"); if (typeof(NLog.Targets.Wrappers.WrapperTargetBase).IsAssignableFrom(typeof(T)) && !typeAlias.EndsWith("Wrapper", StringComparison.OrdinalIgnoreCase)) { typeAlias += "Wrapper"; } } ConfigurationItemFactory.Default.GetTargetFactory().RegisterType<T>(typeAlias, factory); return setupBuilder; } /// <summary> /// Register a custom NLog Target. /// </summary> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="name">Type name of the Target</param> /// <param name="targetType">The target type-alias for use in NLog configuration</param> public static ISetupExtensionsBuilder RegisterTarget(this ISetupExtensionsBuilder setupBuilder, string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type targetType) { if (string.IsNullOrEmpty(name)) throw new ArgumentException("Missing NLog Target type-alias", nameof(name)); if (!typeof(Target).IsAssignableFrom(targetType)) throw new ArgumentException("Not of type NLog Target", nameof(targetType)); ConfigurationItemFactory.Default.GetTargetFactory().RegisterDefinition(name, targetType); return setupBuilder; } /// <summary> /// Register a custom NLog Layout. /// </summary> /// <typeparam name="T">Type of the layout renderer.</typeparam> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="typeAlias">The layout type-alias for use in NLog configuration. Will extract from class-attribute when unassigned.</param> public static ISetupExtensionsBuilder RegisterLayout<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(this ISetupExtensionsBuilder setupBuilder, string typeAlias = null) where T : Layout, new() { return RegisterLayout<T>(setupBuilder, () => new T(), typeAlias); } /// <summary> /// Register a custom NLog Layout. /// </summary> /// <typeparam name="T">Type of the layout renderer.</typeparam> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="factory">The factory method for creating instance of NLog Layout</param> /// <param name="typeAlias">The layout type-alias for use in NLog configuration. Will extract from class-attribute when unassigned.</param> public static ISetupExtensionsBuilder RegisterLayout<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(this ISetupExtensionsBuilder setupBuilder, Func<T> factory, string typeAlias = null) where T : Layout { typeAlias = string.IsNullOrEmpty(typeAlias) ? ResolveTypeAlias<T, LayoutAttribute>(ArrayHelper.Empty<string>()) : typeAlias; ConfigurationItemFactory.Default.GetLayoutFactory().RegisterType<T>(typeAlias, factory); return setupBuilder; } /// <summary> /// Register a custom NLog Layout. /// </summary> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="layoutType">Type of the layout.</param> /// <param name="typeAlias">The layout type-alias for use in NLog configuration</param> public static ISetupExtensionsBuilder RegisterLayout(this ISetupExtensionsBuilder setupBuilder, string typeAlias, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type layoutType) { if (string.IsNullOrEmpty(typeAlias)) throw new ArgumentException("Missing NLog Layout type-alias", nameof(typeAlias)); if (!typeof(Layout).IsAssignableFrom(layoutType)) throw new ArgumentException("Not of type NLog Layout", nameof(layoutType)); ConfigurationItemFactory.Default.GetLayoutFactory().RegisterDefinition(typeAlias, layoutType); return setupBuilder; } /// <summary> /// Register a custom NLog LayoutRenderer. /// </summary> /// <typeparam name="T">Type of the layout renderer.</typeparam> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="name">The layout-renderer type-alias for use in NLog configuration - without '${ }'. Will extract from class-attribute when unassigned.</param> public static ISetupExtensionsBuilder RegisterLayoutRenderer<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(this ISetupExtensionsBuilder setupBuilder, string name = null) where T : LayoutRenderer, new() { return RegisterLayoutRenderer<T>(setupBuilder, () => new T(), name); } /// <summary> /// Register a custom NLog LayoutRenderer. /// </summary> /// <typeparam name="T">Type of the layout renderer.</typeparam> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="factory">The factory method for creating instance of NLog LayoutRenderer</param> /// <param name="typeAlias">The layout-renderer type-alias for use in NLog configuration - without '${ }'. Will extract from class-attribute when unassigned.</param> public static ISetupExtensionsBuilder RegisterLayoutRenderer<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(this ISetupExtensionsBuilder setupBuilder, Func<T> factory, string typeAlias = null) where T : LayoutRenderer { typeAlias = string.IsNullOrEmpty(typeAlias) ? ResolveTypeAlias<T, LayoutRendererAttribute>("LayoutRendererWrapper", "LayoutRenderer") : typeAlias; ConfigurationItemFactory.Default.GetLayoutRendererFactory().RegisterType<T>(typeAlias, factory); return setupBuilder; } private static string ResolveTypeAlias<T, TNameAttribute>(params string[] trimEndings) where TNameAttribute : NameBaseAttribute { var typeAlias = typeof(T).GetFirstCustomAttribute<TNameAttribute>()?.Name; if (!string.IsNullOrEmpty(typeAlias)) return typeAlias; return ResolveTypeAlias<T>(trimEndings); } private static string ResolveTypeAlias<T>(params string[] trimEndings) { var typeAlias = typeof(T).Name; foreach (var ending in trimEndings) { int endingPosition = typeAlias.IndexOf(ending, StringComparison.OrdinalIgnoreCase); if (endingPosition > 0) { return typeAlias.Substring(endingPosition); } } return typeAlias; } /// <summary> /// Register a custom NLog LayoutRenderer. /// </summary> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="layoutRendererType">Type of the layout renderer.</param> /// <param name="name">The layout-renderer type-alias for use in NLog configuration - without '${ }'</param> public static ISetupExtensionsBuilder RegisterLayoutRenderer(this ISetupExtensionsBuilder setupBuilder, string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type layoutRendererType) { if (string.IsNullOrEmpty(name)) throw new ArgumentException("Missing NLog LayoutRenderer type-alias", nameof(name)); if (!typeof(LayoutRenderer).IsAssignableFrom(layoutRendererType)) throw new ArgumentException("Not of type NLog LayoutRenderer", nameof(layoutRendererType)); ConfigurationItemFactory.Default.GetLayoutRendererFactory().RegisterDefinition(name, layoutRendererType); return setupBuilder; } /// <summary> /// Register a custom NLog LayoutRenderer with a callback function <paramref name="layoutMethod"/>. The callback receives the logEvent. /// </summary> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="name">The layout-renderer type-alias for use in NLog configuration - without '${ }'</param> /// <param name="layoutMethod">Callback that returns the value for the layout renderer.</param> public static ISetupExtensionsBuilder RegisterLayoutRenderer(this ISetupExtensionsBuilder setupBuilder, string name, Func<LogEventInfo, object> layoutMethod) { return RegisterLayoutRenderer(setupBuilder, name, (info, configuration) => layoutMethod(info)); } /// <summary> /// Register a custom NLog LayoutRenderer with a callback function <paramref name="layoutMethod"/>. The callback receives the logEvent and the current configuration. /// </summary> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="name">The layout-renderer type-alias for use in NLog configuration - without '${ }'</param> /// <param name="layoutMethod">Callback that returns the value for the layout renderer.</param> public static ISetupExtensionsBuilder RegisterLayoutRenderer(this ISetupExtensionsBuilder setupBuilder, string name, Func<LogEventInfo, LoggingConfiguration, object> layoutMethod) { return RegisterLayoutRenderer(setupBuilder, name, layoutMethod, LayoutRenderOptions.None); } /// <summary> /// Register a custom NLog LayoutRenderer with a callback function <paramref name="layoutMethod"/>. The callback receives the logEvent. /// </summary> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="name">The layout-renderer type-alias for use in NLog configuration - without '${ }'</param> /// <param name="layoutMethod">Callback that returns the value for the layout renderer.</param> /// <param name="options">Options of the layout renderer.</param> public static ISetupExtensionsBuilder RegisterLayoutRenderer(this ISetupExtensionsBuilder setupBuilder, string name, Func<LogEventInfo, object> layoutMethod, LayoutRenderOptions options) { return RegisterLayoutRenderer(setupBuilder, name, (info, configuration) => layoutMethod(info), options); } /// <summary> /// Register a custom NLog LayoutRenderer with a callback function <paramref name="layoutMethod"/>. The callback receives the logEvent and the current configuration. /// </summary> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="name">The layout-renderer type-alias for use in NLog configuration - without '${ }'</param> /// <param name="layoutMethod">Callback that returns the value for the layout renderer.</param> /// <param name="options">Options of the layout renderer.</param> public static ISetupExtensionsBuilder RegisterLayoutRenderer(this ISetupExtensionsBuilder setupBuilder, string name, Func<LogEventInfo, LoggingConfiguration, object> layoutMethod, LayoutRenderOptions options) { FuncLayoutRenderer layoutRenderer = Layout.CreateFuncLayoutRenderer(layoutMethod, options, name); return setupBuilder.RegisterLayoutRenderer(layoutRenderer); } /// <summary> /// Register a custom NLog LayoutRenderer with a callback function /// </summary> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="layoutRenderer">LayoutRenderer instance with type-alias and callback-method.</param> public static ISetupExtensionsBuilder RegisterLayoutRenderer(this ISetupExtensionsBuilder setupBuilder, FuncLayoutRenderer layoutRenderer) { ConfigurationItemFactory.Default.GetLayoutRendererFactory().RegisterFuncLayout(layoutRenderer.LayoutRendererName, layoutRenderer); return setupBuilder; } /// <summary> /// Register a custom condition method, that can use in condition filters /// </summary> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="name">Name of the condition filter method</param> /// <param name="conditionMethod">MethodInfo extracted by reflection - typeof(MyClass).GetMethod("MyFunc", BindingFlags.Static).</param> [Obsolete("Instead use RegisterConditionMethod with delegate, as type reflection will be moved out. Marked obsolete with NLog v5.2")] public static ISetupExtensionsBuilder RegisterConditionMethod(this ISetupExtensionsBuilder setupBuilder, string name, MethodInfo conditionMethod) { Guard.ThrowIfNull(conditionMethod); if (!conditionMethod.IsStatic) throw new ArgumentException($"{conditionMethod.Name} must be static", nameof(conditionMethod)); ConfigurationItemFactory.Default.ConditionMethodFactory.RegisterDefinition(name, conditionMethod); return setupBuilder; } /// <summary> /// Register a custom condition method, that can use in condition filters /// </summary> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="name">Name of the condition filter method</param> /// <param name="conditionMethod">Lambda method.</param> public static ISetupExtensionsBuilder RegisterConditionMethod(this ISetupExtensionsBuilder setupBuilder, string name, Func<LogEventInfo, object> conditionMethod) { Guard.ThrowIfNull(conditionMethod); ConfigurationItemFactory.Default.ConditionMethodFactory.RegisterNoParameters(name, (logEvent) => conditionMethod(logEvent)); return setupBuilder; } /// <summary> /// Register a custom condition method, that can use in condition filters /// </summary> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="name">Name of the condition filter method</param> /// <param name="conditionMethod">Lambda method.</param> public static ISetupExtensionsBuilder RegisterConditionMethod(this ISetupExtensionsBuilder setupBuilder, string name, Func<object> conditionMethod) { Guard.ThrowIfNull(conditionMethod); ConfigurationItemFactory.Default.ConditionMethodFactory.RegisterNoParameters(name, (logEvent) => conditionMethod()); return setupBuilder; } /// <summary> /// Register (or replaces) singleton-object for the specified service-type /// </summary> /// <typeparam name="T">Service interface type</typeparam> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="singletonService">Implementation of interface.</param> public static ISetupExtensionsBuilder RegisterSingletonService<T>(this ISetupExtensionsBuilder setupBuilder, T singletonService) where T : class { Guard.ThrowIfNull(singletonService); setupBuilder.LogFactory.ServiceRepository.RegisterSingleton<T>(singletonService); return setupBuilder; } /// <summary> /// Register (or replaces) singleton-object for the specified service-type /// </summary> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="interfaceType">Service interface type.</param> /// <param name="singletonService">Implementation of interface.</param> public static ISetupExtensionsBuilder RegisterSingletonService(this ISetupExtensionsBuilder setupBuilder, Type interfaceType, object singletonService) { Guard.ThrowIfNull(interfaceType); Guard.ThrowIfNull(singletonService); if (!interfaceType.IsAssignableFrom(singletonService.GetType())) throw new ArgumentException("Service instance not matching type", nameof(singletonService)); setupBuilder.LogFactory.ServiceRepository.RegisterService(interfaceType, singletonService); return setupBuilder; } /// <summary> /// Register (or replaces) external service-repository for resolving dependency injection /// </summary> /// <param name="setupBuilder">Fluent interface parameter.</param> /// <param name="serviceProvider">External dependency injection repository</param> public static ISetupExtensionsBuilder RegisterServiceProvider(this ISetupExtensionsBuilder setupBuilder, IServiceProvider serviceProvider) { Guard.ThrowIfNull(serviceProvider); setupBuilder.LogFactory.ServiceRepository.RegisterSingleton(serviceProvider); return setupBuilder; } } } <file_sep>// // Copyright (c) 2004-2021 <NAME> <<EMAIL>>, <NAME>, <NAME> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of <NAME> nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Threading; using NLog.Common; /// <summary> /// Helper class for dealing with exceptions. /// </summary> internal static class ExceptionHelper { private const string LoggedKey = "NLog.ExceptionLoggedToInternalLogger"; /// <summary> /// Mark this exception as logged to the <see cref="InternalLogger"/>. /// </summary> /// <param name="exception"></param> /// <returns></returns> public static void MarkAsLoggedToInternalLogger(this Exception exception) { if (exception != null) { exception.Data[LoggedKey] = true; } } /// <summary> /// Is this exception logged to the <see cref="InternalLogger"/>? /// </summary> /// <param name="exception"></param> /// <returns><c>true</c>if the <paramref name="exception"/> has been logged to the <see cref="InternalLogger"/>.</returns> public static bool IsLoggedToInternalLogger(this Exception exception) { if (exception?.Data?.Count > 0) { return exception.Data[LoggedKey] as bool? ?? false; } return false; } /// <summary> /// Determines whether the exception must be rethrown and logs the error to the <see cref="InternalLogger"/> if <see cref="IsLoggedToInternalLogger"/> is <c>false</c>. /// /// Advised to log first the error to the <see cref="InternalLogger"/> before calling this method. /// </summary> /// <param name="exception">The exception to check.</param> /// <param name="loggerContext">Target Object context of the exception.</param> /// <param name="callerMemberName">Target Method context of the exception.</param> /// <returns><c>true</c>if the <paramref name="exception"/> must be rethrown, <c>false</c> otherwise.</returns> public static bool MustBeRethrown(this Exception exception, IInternalLoggerContext loggerContext = null, string callerMemberName = null) { if (exception.MustBeRethrownImmediately()) { //no further logging, because it can make severe exceptions only worse. return true; } var isConfigError = exception is NLogConfigurationException; var logFactory = loggerContext?.LogFactory; var throwExceptionsAll = logFactory?.ThrowExceptions == true || LogManager.ThrowExceptions; var shallRethrow = isConfigError ? (logFactory?.ThrowConfigExceptions ?? LogManager.ThrowConfigExceptions ?? throwExceptionsAll) : throwExceptionsAll; //we throw always configuration exceptions (historical) if (!exception.IsLoggedToInternalLogger()) { var level = shallRethrow ? LogLevel.Error : LogLevel.Warn; if (loggerContext != null) { if (string.IsNullOrEmpty(callerMemberName)) InternalLogger.Log(exception, level, "{0}: Error has been raised.", loggerContext); else InternalLogger.Log(exception, level, "{0}: Exception in {1}", loggerContext, callerMemberName); } else { InternalLogger.Log(exception, level, "Error has been raised."); } } return shallRethrow; } /// <summary> /// Determines whether the exception must be rethrown immediately, without logging the error to the <see cref="InternalLogger"/>. /// /// Only used this method in special cases. /// </summary> /// <param name="exception">The exception to check.</param> /// <returns><c>true</c>if the <paramref name="exception"/> must be rethrown, <c>false</c> otherwise.</returns> public static bool MustBeRethrownImmediately(this Exception exception) { #if !NETSTANDARD1_3 && !NETSTANDARD1_5 if (exception is StackOverflowException) { return true; // StackOverflowException cannot be caught since .NetFramework 2.0 } if (exception is ThreadAbortException) { return true; // ThreadAbortException will automatically be rethrown at end of catch-block } #endif if (exception is OutOfMemoryException) { return true; } #if DEBUG if (exception is InvalidCastException) { return true; } if (exception is NullReferenceException) { return true; } if (exception is ArgumentNullException) { return true; } if (exception is ArgumentOutOfRangeException) { return true; } if (exception is DivideByZeroException) { return true; } if (exception is OverflowException) { return true; } if (exception is System.Net.WebException) { return false; // Not a real InvalidOperationException } if (exception is InvalidOperationException) { return true; // Ex. Collection was modified } if (exception is IndexOutOfRangeException) { return true; } if (exception is System.Reflection.TargetInvocationException) { return true; // Compiler/reflection exception } #endif return false; } } }
d10ec4bc838bc65870f1907ff1b8aefe627dc3f7
[ "Markdown", "C#", "Text", "HTML" ]
373
C#
NLog/NLog
eb775a34b5999f53ef2159d7e826c75b03cda6f3
444c6e3270178ac314bf1b8d3188a99bd9178670
refs/heads/master
<repo_name>adammlr/blankletters<file_sep>/src/words.js export const things = [ "Active Volcanoes", "Beach Chair With Side Table", "Biceps & Triceps", "Big Blue Eyes", "Bits And Pieces", "Bold Measures", "Bonuses & Incentives", "Buzzwords", "Canvas Sneakers", "Car Cupholders", "Cars Trucks And Vans", "Castle Moat & Drawbridge", "Casual T-Shirts & Pants", "Champagne Bubbles", "Chubby Cheeks", "Clocks & Watches", "Coloring Book & Crayons", "Comic Books", "Complex Carbs", "Congested Freeways", "Daily & Weekly Calendar", "Day & Evening Classes", "Electric Cars", "Employee Benefits", "Fiction & Nonfiction", "Fingers And Toes", "Foot-Massaging Sandals", "Fuel Additives", "Funny Quotations", "Fur-Lined Winter Boots", "Giant Sand Dunes", "Golf Shoes", "Granite & Marble Floors", "Hamburger Wrappers", "Hammer And Nails", "Handbags & Shoes", "Hidden Talents", "High Hopes", "Homemade Gifts", "Honest Answers", "House Rules", "Job Postings", "Limericks", "Lipstick & Eye Shadow", "Lush Tropical Greenery", "Minor Adjustments", "Mixed Emotions", "Moisturizing Towelettes", "Morning Stretches", "Motorcycle Boots", "Motorcycles", "News Weather & Sports", "Outdoor Activities", "Parking Restrictions", "Party Favors", "Personal Movie Collection", "Plush Stuffed Animals", "Preemptive Measures", "Prom Dress & Tuxedo", "Public Sector", "Punctuation Marks", "Relaxing Spa Services", "Rose Petals", "Rustling Autumn Leaves", "Sample Questions", "Science And Technology", "Shearling-Lined Boots", "Shocks & Struts", "Spanish-Language Subtitles", "Stylish Sunglasses", "Subliminal Messages", "Tacks & Pushpins", "Tired And Aching Feet", "Traditional Christmas Gifts", "Unlimited Privileges", "Warm Caribbean Breezes", "Warmth & Compassion", "Waves Rolling Onto The Shore", "Wool Gloves" ]; <file_sep>/src/components/PickedLetterDisplay.jsx import React from "react"; import styled from "styled-components"; const PickedLetter = styled.div` display: inline-block; border: solid 1px #ddd; background-color: white; font-size: 18px; width: 18px; text-align: center; margin: 2px; font-family: "Source Code Pro"; `; const Container = styled.div` display: inline-block; `; export default function PickedLetterDisplay({ pickedLetters }) { return ( <Container> {pickedLetters.map(letter => { return <PickedLetter key={letter}>{letter}</PickedLetter>; })} </Container> ); } <file_sep>/src/constants.js export const initalLetters = ["R", "S", "T", "L", "N", "E"]; export const defaultLetters = [" ", "-", "&"]; export const maxPuzzlePoints = 1000; <file_sep>/src/components/Word.jsx import React from "react"; import styled from "styled-components"; import Letter from "./Letter"; import { defaultLetters } from "../constants"; const WordWrapper = styled.div` display: inline-block; padding-right: 20px; `; export default function Word({ word, pickedLetters }) { return ( <WordWrapper> {[...word].map((letter, index) => { return ( <Letter key={index} letter={getLetterToDisplay(letter, [ ...pickedLetters, ...defaultLetters ])} /> ); })} </WordWrapper> ); } function getLetterToDisplay(letter, pickedLetters) { if (pickedLetters.includes(letter)) { return letter; } return "_"; } <file_sep>/src/components/Letter.jsx import styled from "styled-components"; import React from "react"; const LetterContainer = styled.div` display: inline-block; border: solid 1px black; background-color: white; font-size: 24px; width: 20px; height: 30px; text-align: center; margin: 2px; vertical-align: middle; font-family: "Source Code Pro"; `; export default function Letter({ letter }) { return <LetterContainer>{letter === "_" ? null : letter}</LetterContainer>; } <file_sep>/src/components/Puzzle.jsx import React, { useState, useEffect } from "react"; import PickedLetterDisplay from "./PickedLetterDisplay"; import SelectLetter from "./SelectLetter"; import Word from "./Word"; import { initalLetters, defaultLetters, maxPuzzlePoints } from "../constants"; import ScoreBar from "./ScoreBar"; export default function Puzzle({ word, nextWord }) { const upperWord = word.toUpperCase(); const [pickedLetters, setPickedLetters] = useState(initalLetters); const [solved, setSolved] = useState(false); const [points, setPoints] = useState(maxPuzzlePoints); useEffect(checkSolved, [pickedLetters]); useEffect(newWord, [word]); useEffect(solve, [points]); useEffect(() => { let timer; if (solved) { window.clearInterval(timer); } else { timer = window.setInterval(() => { if (points >= 50) { setPoints(points => points - 50); } }, 1000); } return () => { window.clearInterval(timer); }; }, [solved, points]); function newWord() { setSolved(false); setPickedLetters(initalLetters); setPoints(maxPuzzlePoints); } function solve() { if (points === 0) { const newLetters = []; [...upperWord].forEach(letter => { if (![...pickedLetters, ...defaultLetters].includes(letter)) { if (!newLetters.includes(letter)) { newLetters.push(letter); } } }); setPickedLetters([...pickedLetters, ...newLetters]); } } function handleNewLetter(newLetter) { if (!pickedLetters.includes(newLetter)) { setPickedLetters([...pickedLetters, newLetter]); if (!upperWord.includes(newLetter) && points >= 50) { setPoints(points => points - 50); } } } function checkSolved() { const isSolved = [...upperWord].every(letter => { return [...pickedLetters, ...defaultLetters].includes(letter); }); if (isSolved) { setSolved(true); } } return ( <div> <ScoreBar currentPoints={points} /> <div> {upperWord.split(" ").map((eachWord, index) => { return ( <Word key={index} pickedLetters={pickedLetters} word={eachWord} /> ); })} </div> <PickedLetterDisplay pickedLetters={pickedLetters} /> {!solved && <SelectLetter submitLetter={handleNewLetter} />} { <div> <button onClick={nextWord}>New Word!</button> </div> } </div> ); }
2f7b4e666814aaa2b6cad0c6649361daa4518700
[ "JavaScript" ]
6
JavaScript
adammlr/blankletters
ccdc091972919f686f7170fcdd732ad44bc461b5
99079c3586671c62ab960a5df6f964ba16074ceb
refs/heads/master
<repo_name>littlelightwang/weather_swift<file_sep>/weather_swift/ViewController.swift // // ViewController.swift // weather_swift // // Created by wangxiaoliang on 15-1-26. // Copyright (c) 2015年 wangxiaoliang. All rights reserved. // import UIKit import Alamofire import CoreLocation import SwiftyJSON class ViewController: UIViewController,CLLocationManagerDelegate { let locationManager:CLLocationManager = CLLocationManager() @IBOutlet weak var loadingIndicator: UIActivityIndicatorView! @IBOutlet weak var icon: UIImageView! @IBOutlet weak var temperature: UILabel! @IBOutlet weak var loading: UILabel! @IBOutlet weak var location: UILabel! @IBOutlet weak var time1: UILabel! @IBOutlet weak var time2: UILabel! @IBOutlet weak var time3: UILabel! @IBOutlet weak var time4: UILabel! @IBOutlet weak var image1: UIImageView! @IBOutlet weak var image2: UIImageView! @IBOutlet weak var image3: UIImageView! @IBOutlet weak var image4: UIImageView! @IBOutlet weak var temp1: UILabel! @IBOutlet weak var temp2: UILabel! @IBOutlet weak var temp3: UILabel! @IBOutlet weak var temp4: UILabel! override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self //精度 locationManager.desiredAccuracy = kCLLocationAccuracyBest self.loadingIndicator.startAnimating() let background = UIImage(named: "background.png") self.view.backgroundColor = UIColor(patternImage: background!) let singleFingerTap = UITapGestureRecognizer(target: self, action: "handleSingleTap:") //添加手势 self.view.addGestureRecognizer(singleFingerTap) locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } func handleSingleTap(recognizer:UITapGestureRecognizer){ locationManager.startUpdatingLocation() self.loadingIndicator.startAnimating() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //请求 func updateWeatherInfo(latitude:CLLocationDegrees,longitude:CLLocationDegrees){ let url = "http://api.openweathermap.org/data/2.5/forecast" let params = ["lat":latitude,"lon":longitude] println(params) Alamofire.request(.GET, url, parameters: params).responseJSON { (request, response, json, error) in if error != nil{ println("Error:\(error)") println(request) println(response) self.loading.text = "Internet appears down!" } else{ println("Success:\(url)") println(request) var json = JSON(json!) self.updateUISuccess(json) } } } func updateUISuccess(json:JSON){ self.loading.text = nil self.loadingIndicator.hidden = true self.loadingIndicator.stopAnimating() //let if let tempResult = json["list"][0]["main"]["temp"].double{ //Get country let country = json["city"]["country"].stringValue //Get and convert temperature var temperature = self.convertTemperature(country, temperature: tempResult) self.temperature.text = "\(temperature)°" //Get city name self.location.text = json["city"]["name"].stringValue //Get and set icon let weather = json["list"][0]["weather"][0] let condition = weather["id"].intValue var icon = weather["icon"].stringValue var nightTime = self.isNightTime(icon) self.updateWeatherIcon(condition, nightTime: nightTime, index: 0, callback: self.updatePictures) //Get forecast for index in 1...4{ println(json["list"][index]) if let newtempResult = json["list"][index]["main"]["temp"].double{ //Get and convert temperature var newtemperature = self.convertTemperature(country, temperature: newtempResult) if index == 1{ self.temp1.text = "\(newtemperature)°" } else if index == 2{ self.temp2.text = "\(newtemperature)°" } else if index == 3{ self.temp3.text = "\(newtemperature)°" } else if index == 4{ self.temp4.text = "\(newtemperature)°" } //Get forecast time var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" let rawDate = json["list"][index]["dt"].doubleValue let date = NSDate(timeIntervalSince1970: rawDate) let forecastTime = dateFormatter.stringFromDate(date) if index == 1{ self.time1.text = forecastTime } else if index == 2{ self.time2.text = forecastTime } else if index == 3{ self.time3.text = forecastTime } else if index == 4{ self.time4.text = forecastTime } //Get and set icon let newWeather = json["list"][index]["weather"][0] let newCondition = newWeather["id"].intValue let newIcon = newWeather["icon"].stringValue var newNightTime = self.isNightTime(newIcon) self.updateWeatherIcon(newCondition, nightTime: newNightTime, index: index, callback: self.updatePictures) } else{ continue } } }else { self.loading.text = "Weather info is not available!" } } func isNightTime(icon: String)->Bool { return icon.rangeOfString("n") != nil } func convertTemperature(country: String, temperature: Double)->Double{ if (country == "US") { // Convert temperature to Fahrenheit if user is within the US return round(((temperature - 273.15) * 1.8) + 32) } else { // Otherwise, convert temperature to Celsius return round(temperature - 273.15) } } func updateWeatherIcon(condition: Int, nightTime: Bool, index: Int, callback:(index: Int, name: String)->()) { // Thunderstorm if (condition < 300) { if nightTime { callback(index: index, name: "tstorm1_night") } else { callback(index: index, name: "tstorm1") } } // Drizzle else if (condition < 500) { callback(index: index, name: "light_rain") } // Rain / Freezing rain / Shower rain else if (condition < 600) { callback(index: index, name: "shower3") } // Snow else if (condition < 700) { callback(index: index, name: "snow4") } // Fog / Mist / Haze / etc. else if (condition < 771) { if nightTime { callback(index: index, name: "fog_night") } else { callback(index: index, name: "fog") } } // Tornado / Squalls else if (condition < 800) { callback(index: index, name: "tstorm3") } // Sky is clear else if (condition == 800) { if (nightTime){ callback(index: index, name: "sunny_night") } else { callback(index: index, name: "sunny") } } // few / scattered / broken clouds else if (condition < 804) { if (nightTime){ callback(index: index, name: "cloudy2_night") } else{ callback(index: index, name: "cloudy2") } } // overcast clouds else if (condition == 804) { callback(index: index, name: "overcast") } // Extreme else if ((condition >= 900 && condition < 903) || (condition > 904 && condition < 1000)) { callback(index: index, name: "tstorm3") } // Cold else if (condition == 903) { callback(index: index, name: "snow5") } // Hot else if (condition == 904) { callback(index: index, name: "sunny") } // Weather condition is not available else { callback(index: index, name: "dunno") } } func updatePictures(index: Int, name: String) { if (index==0) { self.icon.image = UIImage(named: name) } if (index==1) { self.image1.image = UIImage(named: name) } if (index==2) { self.image2.image = UIImage(named: name) } if (index==3) { self.image3.image = UIImage(named: name) } if (index==4) { self.image4.image = UIImage(named: name) } } //MARK: - CLLocationManagerDelegate func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { var location:CLLocation = locations[locations.count-1] as CLLocation if location.horizontalAccuracy > 0{ self.locationManager.stopUpdatingLocation() println("lat = \(location.coordinate.latitude),lon = \(location.coordinate.longitude)") updateWeatherInfo(location.coordinate.latitude, longitude: location.coordinate.longitude) } } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { println(error) self.loading.text = "Can't get your location!" } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } }
378e6327a6a7e3c0ba44b92ee3b0c807e85504f4
[ "Swift" ]
1
Swift
littlelightwang/weather_swift
ed7a78f34588b777238c86b8c2f63b15eb34f652
5189758a16853f776df7127963f36c5c398c44c0
refs/heads/master
<repo_name>lennartsc/MSc-Statistics-and-Machine-Learning<file_sep>/Advanced R Programming/lab05/lab05_result/tests/testthat.R library(testthat) library(rLab5) test_check("rLab5") <file_sep>/Bioinformatics/README.md # Lab files: Bioinformatics :point_left: [Back to overview](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning#overview).<file_sep>/Bayesian Learning/README.md # Lab files: Bayesian Learning |Lab|Content| |:---:|:---:| |Lab 1| Exploring posterior distributions in one-parameter models by simulation and direct numerical evaluation| |Lab 2| Polynomial regression and classification with logistic regression| |Lab 3| MCMC using Gibbs sampling and Metropolis-Hastings| |Lab 4| Hamiltonian Monte Carlo with Stan| :point_left: [Back to overview](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning#overview).<file_sep>/Big Data Analytics/lab03/lab03_code.py from __future__ import division from math import radians, cos, sin, asin, sqrt, exp from datetime import datetime, timedelta from pyspark import SparkContext from collections import OrderedDict # Defining haversine-function to calculate great circle distance between two points on earth. def haversine(lon1, lat1, lon2, lat2): # Converting decimal degrees to radians. lon1, lati1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # Calculating distance in km using haversine formula. dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) km = 6367 * c # Returning distance in km. return km # Setting up Spark's execution environment. sc = SparkContext(appName="BDA3") # Setting up input parameters. h_distance = 100 h_date = 3 h_time = 2 lat_given = 58.4274 lon_given = 14.826 given_date = "2015-07-04" start = datetime.strptime("04:00:00","%H:%M:%S") given_time = [start + timedelta(hours=2*x) for x in range(0, 11)] # Reading stations data and broadcasting it. ## Reading data. stations = sc.textFile("/user/x_lensc/data/stations.csv") stations = stations.map(lambda line: line.split(";")) ## Extracting station number (key) and longitude, latitude (value). stations = stations.map(lambda x: (x[0], (x[3], x[4]))) ## Broadcasting stations data to each node (accessable over attribute 'value'). stations = stations.collectAsMap() stations = sc.broadcast(stations) # Reading temperature data. ## Reading data. temps = sc.textFile("/user/x_lensc/data/temperature-readings.csv") temps = temps.map(lambda line: line.split(";")) ## Extracting station number (key) and date, time, temperature (value). temps = temps.map(lambda x: (x[0], (x[1], x[2], float(x[3])))) # Filtering temperature data related to given date # (keep onlydata prior to date. Posterior data should not be considererd for the prediction.) ## Filtering data with date <= given date. temps = temps.filter(lambda x: x[1][0] <= given_date) # Adding longitute, latitude of stations to temperature data. temps = temps.map(lambda x: (x[0], (stations.value.get(x[0], "-"), x[1]))) temps = temps.map(lambda x: (x[0], (x[1][0][0], x[1][0][1], x[1][1][0], x[1][1][1], x[1][1][2]))) # Caching data. temps = temps.cache() # Implementing kernel function. def gaussian_kernel(diff, h): return exp(-(diff / h) ** 2) # Creating an emtpy dictionary # Creating empty dictionaries to store predictions. # Results for addition and multiplication of kernels will be stored. predAddition = OrderedDict() predMultiplication = OrderedDict() for i in range(len(given_time)): # Remapping temperature data including distances for location, day and hour to # given location, given date and to each given time. # New format: station_nr, distance in km, distance in days, distance in hours, temperature. temp = temps.map(lambda x: (x[0], (haversine(lon_given, lat_given,float(x[1][1]), float(x[1][0])), (datetime.strptime(x[1][2], '%Y-%m-%d') - datetime.strptime(given_date,'%Y-%m-%d')).days, (datetime.strptime(x[1][3], '%H:%M:%S') - given_time[i]).seconds / 3600, x[1][4]))) # Remapping using kernel function. # Key will be set to 0 for later aggregation. # New format: 0, kernel value for distance in km, kernel value for distance in days, # kernel value for distance in hours, temperature. # Storing new value in temp instead of temps because we need to use temps again. temp = temp.map(lambda x: (0, (gaussian_kernel(x[1][0], h_distance), gaussian_kernel(x[1][1], h_date), gaussian_kernel(x[1][2], h_time), x[1][3]))) # Addition of kernels. ## Remapping. ## New format: ## (0, (distance kernel * temp + day kernel * temp + hour kernel * temp, sum of kernels)) tempAdd = temp.map(lambda x: (x[0], (x[1][0] * x[1][3] + x[1][1] * x[1][3] + x[1][2] * x[1][3], x[1][0] + x[1][1] + x[1][2]))) ## Aggregating by key (we implemented same key for every observation, ## so aggreagating over all observations. ## New format: (0, (sum of kernel values * temps, sum of kernel values)) tempAdd = tempAdd.reduceByKey(lambda x, y: (x[0] + y[0], x[1] + y[1])) ## Remapping to extract result: ## Prediction = (sum of kernel values * temps) / sum of kernel values tempAdd = tempAdd.map(lambda x: x[1][0] / x[1][1]) ## Storing predicted values. predAddition[given_time[i].strftime("%H:%M:%S")] = tempAdd.take(1) # Multiplication of kernels. ## Remapping. ## New format: ## (0, (distance kernel * day kernel * hour kernel * temp, product of kernels)) tempMult = temp.map(lambda x: (x[0], (x[1][0] * x[1][1] * x[1][2] * x[1][3], x[1][0] * x[1][1] * x[1][2]))) ## Aggregating by key (we implemented same key for every observation, ## so aggreagating over all observations. ## New format: (0, (sum of kernel values * temps, sum of kernel values)) tempMult = tempMult.reduceByKey(lambda x, y: (x[0] + y[0], x[1] + y[1])) ## Remapping to extract result: ## Prediction = (sum of kernel values * temps) / sum of kernel values tempMult = tempMult.map(lambda x: x[1][0] / x[1][1]) ## Storing predicted values. predMultiplication[given_time[i].strftime("%H:%M:%S")] = tempMult.take(1) # Printing results. print("Results for addition of kernels:\n") print("Time | Predicted Temperature") print("----------------------------------") for key,value in predAddition.items() : print(key,' | ',round(value[0],2)) print("Results for multiplication of kernels:\n") print("Time | Predicted Temperature") print("----------------------------------") for key,value in predMultiplication.items() : print(key,' | ',round(value[0],2)) # Closing spark enviorenment. sc.stop() <file_sep>/Advanced R Programming/lab01/lab01_result.R name = "<NAME>" liuid = "lensc874" # ******************************************************************************************** # 1.1 Vectors #### ## 1.1.1 my_num_vector() my_num_vector = function() { return(c(log(11, base = 10), cos(pi/5), exp(pi/3), (1173 %% 7) / 19 ) ) } ## 1.1.2 filter_my_vector(x, leq) filter_my_vector= function(x, leq) { x[x >= leq] = NA return(x) } ## 1.1.3 dot_prod(a, b) dot_prod = function(a, b) { return(sum(a*b)) } ## 1.1.4 approx_e(N) approx_e = function(N) { e = 0 for (i in 0:N) { e = e + 1/factorial(i) } return(e) } testNeededSizeOfN = function() { e = round(exp(1),5) N = 0 approx_e = approx_e(N) while(approx_e != e) { N = N+1 approx_e = approx_e(N) } return(N) } testNeededSizeOfN() # N needs to be 8 to approximate e to the fifth decimal place. # ******************************************************************************************** # 1.2 Matrices #### ## 1.2.1 my_magic_matrix() my_magic_matrix = function() { return(matrix(c(4,3,8,9,5,1,2,7,6),3,3)) } ## 1.2.2 calculate_elements(A) calculate_elements = function(A) { nElements = 0 for(i in A) { nElements = nElements + 1 } return(nElements) } ## 1.2.3 row_to_zero(A, i) row_to_zero = function(A, i) { A[i,] = 0 return(A) } ## 1.2.4 add_elements_to_matrix(A, x, i, j) add_elements_to_matrix = function(A, x, i, j) { A[i,j] = A[i,j] + x return(A) } # answer: functionality of the function is clear. Examples helped a lot and should be kept. # ******************************************************************************************** # 1.3 Lists #### ## 1.3.1 my_magic_list() my_magic_list = function() { return( list( info = "my own list", my_num_vector(), my_magic_matrix() ) ) } ## 1.3.2 change_info(x, text) change_info = function(x, text) { x[["info"]] = text return(x) } ## 1.3.3 add_note(x, note) add_note = function(x, note) { x[["note"]] = note return(x) } ## 1.3.4 sum_numeric_parts(x) sum_numeric_parts = function(x) { sumNumericParts = 0 for (elem in x) { if(!is.character(elem)) { sumNumericParts = sumNumericParts + sum(elem) } } return(sumNumericParts) } # ******************************************************************************************** # 1.4 data.frames #### ## 1.4.1 my.data.frame() my_data.frame = function() { df = data.frame(id = c(1,2,3), name = c("John","Lisa","Azra"), income = c(7.3, 0, 15.21), rich = c(FALSE,FALSE,TRUE) ) return(df) } ## 1.4.2 sort_head(df, var.name, n) sort_head = function(df, var.name, n) { df = df[order(-df[var.name]),][1:n,] return(df) } ## 1.4.3 add_median_variable(df, j) add_median_variable = function(df, j) { median = median(df[,j]) df[df[,j]-median == 0,"compared_to_median"] = "Median" df[df[,j]-median > 0,"compared_to_median"] = "Greater" df[df[,j]-median < 0,"compared_to_median"] = "Smaller" return(df) } ## 1.4.4 analyze_columns(df, j) analyze_columns = function(df, j) { list = list() for(i in 1:2) { list[[colnames(df)[j[i]]]] = c(mean = mean(df[,j[i]]), median = median(df[,j[i]]), sd = sd(df[,j[i]])) } list[["correlation_matrix"]] = cor(df[,j]) return(list) } <file_sep>/Advanced R Programming/lab06/lab06_result/tests/testthat/test-rlab6_test.R context("test-rlab6_test.R") set.seed(42) n <- 2000 knapsack_objects <- data.frame( w=sample(1:4000, size = n, replace = TRUE), v=runif(n = n, 0, 10000) ) test_that("brute_force_knapsack works", { expect_silent(bfk <- brute_force_knapsack(x = knapsack_objects[1:8,], W = 3500)) expect_named(bfk, c("value", "elements")) }) test_that("functions rejects errounous input.", { expect_error(brute_force_knapsack("hej", 3500)) expect_error(brute_force_knapsack(x = knapsack_objects[1:8,], W = -3500)) }) test_that("Function return correct results.", { bfk <- brute_force_knapsack(x = knapsack_objects[1:8,], W = 3500) expect_equal(round(bfk$value), 16770) expect_true(all((bfk$elements) %in% c(5, 8))) bfk <- brute_force_knapsack(x = knapsack_objects[1:12,], W = 3500) expect_equal(round(bfk$value), 16770) expect_true(all((bfk$elements) %in% c(5, 8))) bfk <- brute_force_knapsack(x = knapsack_objects[1:8,], W = 2000) expect_equal(round(bfk$value), 15428) expect_true(all((bfk$elements) %in% c(3, 8))) bfk <- brute_force_knapsack(x = knapsack_objects[1:12,], W = 2000) expect_equal(round(bfk$value), 15428) expect_true(all((bfk$elements) %in% c(3, 8))) start.time <- Sys.time() brute_force_knapsack(x = knapsack_objects[1:16,], W = 2000) end.time <- Sys.time() time.taken <- end.time - start.time expect_true(as.numeric(time.taken) >= 0.00) }) test_that("knapsack_dynamic works", { expect_silent(bfk <- knapsack_dynamic(x = knapsack_objects[1:8,], W = 3500)) expect_named(bfk, c("value", "elements")) }) test_that("functions rejects errounous input.", { expect_error(knapsack_dynamic("hej", 3500)) expect_error(knapsack_dynamic(x = knapsack_objects[1:8,], W = -3500)) }) test_that("Function return correct results.", { bfk <- knapsack_dynamic(x = knapsack_objects[1:8,], W = 3500) expect_equal(round(bfk$value), 16770) expect_true(all((bfk$elements) %in% c(5, 8))) bfk <- knapsack_dynamic(x = knapsack_objects[1:12,], W = 3500) expect_equal(round(bfk$value), 16770) expect_true(all((bfk$elements) %in% c(5, 8))) bfk <- knapsack_dynamic(x = knapsack_objects[1:8,], W = 2000) expect_equal(round(bfk$value), 15428) expect_true(all((bfk$elements) %in% c(3, 8))) bfk <- knapsack_dynamic(x = knapsack_objects[1:12,], W = 2000) expect_equal(round(bfk$value), 15428) expect_true(all((bfk$elements) %in% c(3, 8))) start.time <- Sys.time() knapsack_dynamic(x = knapsack_objects[1:16,], W = 2000) end.time <- Sys.time() time.taken <- end.time - start.time expect_true(as.numeric(time.taken) >= 0.00) }) test_that("Correct object is returned", { expect_silent(gk <- greedy_knapsack(x = knapsack_objects[1:8,], W = 3500)) expect_named(gk, c("value", "elements")) }) test_that("functions rejects errounous input.", { expect_error(greedy_knapsack("hej", 3500)) expect_error(greedy_knapsack(x = knapsack_objects[1:8,], W = -3500)) }) test_that("Function return correct results.", { gk <- greedy_knapsack(x = knapsack_objects[1:8,], W = 3500) expect_equal(round(gk$value), 15428) expect_true(all((gk$elements) %in% c(3, 8))) gk <- greedy_knapsack(x = knapsack_objects[1:12,], W = 3500) expect_equal(round(gk$value), 15428) expect_true(all((gk$elements) %in% c(3, 8))) gk <- greedy_knapsack(x = knapsack_objects[1:8,], W = 2000) expect_equal(round(gk$value), 15428) expect_true(all((gk$elements) %in% c(3, 8))) gk <- greedy_knapsack(x = knapsack_objects[1:12,], W = 2000) expect_equal(round(gk$value), 15428) expect_true(all((gk$elements) %in% c(3, 8))) st <- system.time(gk <- greedy_knapsack(x = knapsack_objects[1:16,], W = 2000)) expect_true(as.numeric(st)[2] <= 0.01) gk <- greedy_knapsack(x = knapsack_objects[1:800,], W = 3500) expect_equal((gk$value), 192647) gk <- greedy_knapsack(x = knapsack_objects[1:1200,], W = 3500) expect_equal((gk$value), 270290) }) <file_sep>/Computational Statistics/README.md # Lab files: Computational Statistics |Lab|Content| |:---:|:---:| |Lab 1| Computer arithmetics| |Lab 2| Optimization| |Lab 3| Random number generation| |Lab 4| Monte Carlo Methods| |Lab 5| Model Selection and Hypothesis Testing| |Lab 6| Genetic algorithm, EM algorithm| :point_left: [Back to overview](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning#overview).<file_sep>/Text Mining/project/myfunctions.py # ------------------- Importing modules. ------------------- # # Own functions. import myfunctions # General. import pandas as pd import numpy as np import time import pickle # Pipelining. from sklearn.pipeline import make_pipeline from sklearn.pipeline import Pipeline # Vectorizing and preprocessing. import spacy from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer # Grid Search. from sklearn.model_selection import GridSearchCV # Plotting. import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib import rc # Classifying. from sklearn.naive_bayes import MultinomialNB from sklearn.tree import DecisionTreeClassifier from xgboost import XGBClassifier # Evaluating. from sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score from sklearn.metrics import confusion_matrix # ------------------- Defining functions. ------------------- # def read_split_data(path, tuning_set = False, print_n = True): ''' Read data, modify label, shuffle data and split it into training, test and optionally "tuning" sets while keeping all datasets equally balanced. Optionally print information about the different sets. ''' # Reading data for training classifier. origin_df = pd.read_csv(path) # Modifying sentiment values for positive sentiments from 4 to 1. origin_df.loc[origin_df.sentiment == 4, "sentiment"] = 1 # Shuffling data. origin_df = origin_df.sample(frac = 1) if print_n: # Getting overview about balance regarding the target variable (sentiment). print("Number of tweets in origin data in total: " + str(len(origin_df))) print("Number of tweets in origin data with sentiment == 1 (positive): " + str(len(origin_df[origin_df.sentiment == 1]))) print("Number of tweets in origin data with sentiment == 0 (negative): " + str(len(origin_df[origin_df.sentiment == 0]))) # Splitting original data into train (70%) and val data (30%) while keeping data balanced (50:50) relating the sentiments. # Both will be finally used to train and val the best identified model with its optimal parameters.. origin_pos_df = origin_df[origin_df.sentiment == 1] origin_neg_df = origin_df[origin_df.sentiment == 0] n_train_pos_neg = int(len(origin_pos_df) * 0.7) train_df = origin_pos_df.head(n = n_train_pos_neg) train_df = train_df.append(origin_neg_df.head(n = n_train_pos_neg)) if print_n: print("\nNumber of tweets in training data in total: " + str(len(train_df))) print("Number of tweets in training data with sentiment == 1 (positive): " + str(len(train_df[train_df.sentiment == 1]))) print("Number of tweets in training data with sentiment == 0 (negative): " + str(len(train_df[train_df.sentiment == 0]))) test_df = origin_pos_df.tail(len(origin_pos_df) - n_train_pos_neg) test_df = test_df.append(origin_neg_df.tail(len(origin_pos_df) - n_train_pos_neg)) if print_n: print("\nNumber of tweets in test data in total: " + str(len(test_df))) print("Number of tweets in test data with sentiment == 1 (positive): " + str(len(test_df[test_df.sentiment == 1]))) print("Number of tweets in test data with sentiment == 0 (negative): " + str(len(test_df[test_df.sentiment == 0]))) if tuning_set: # Subsetting train set while keeping data balanced (50:50) relating the sentiments. # Resulting "tuning set" will be used for hyperparameter tuning (time reasons). n_tuning_pos_neg = int(len(train_df[train_df.sentiment == 1]) * tuning_set) tuning_df = train_df[train_df.sentiment == 1].head(n = n_tuning_pos_neg) tuning_df = tuning_df.append(train_df[train_df.sentiment == 0].head(n = n_tuning_pos_neg)) if print_n: print("\nNumber of tweets in tuning data in total: " + str(len(tuning_df))) print("Number of tweets in tuning data with sentiment == 1 (positive): " + str(len(tuning_df[tuning_df.sentiment == 1]))) print("Number of tweets in tuning data with sentiment == 0 (negative): " + str(len(tuning_df[tuning_df.sentiment == 0]))) # Returning extracted sets. if tuning_set: return [train_df, test_df, tuning_df] else: return [train_df, test_df] def vect_model_tuning(train_set, model, vectorizers, preprocessors, params_dict, file_name, njobs = 1): ''' Perform GridSearch with CV (folds = 3) for given training data, classifier, list of vectorizers, list of preprocessors and parameter-dictionary. Returning evaluation metrics (accuracy, precision, recall, f1-score) for all models in a dataframe. ''' # Initializing dataframe to store information in. results = pd.DataFrame(columns=["params", "mean_val_accuracy", "mean_train_accuracy", "mean_val_precision", "mean_train_precision", "mean_val_recall", "mean_train_recall", "mean_val_f1", "mean_train_f1", "model", "vectorizer", "preprocess"]) model_name = model.__name__ for vectorizer in vectorizers: vect_name = vectorizer.__name__ for f_preprocessor in preprocessors: if f_preprocessor == None: preprocess_name = "None" else: preprocess_name = f_preprocessor.__name__ print("\nModel: " + model_name) print("Vectorizer: " + vect_name) print("Preprocessor: " + preprocess_name) # Defining pipeline. pipeline = Pipeline([('vect', vectorizer(tokenizer = f_preprocessor)), ('clf', model())]) # Defining GridSearch procedure. gs_procedure = GridSearchCV( pipeline, params_dict, cv = 3, iid = False, n_jobs = njobs, refit = False, return_train_score = True, scoring = ["accuracy", "precision", "recall", "f1"]) # Training and validating classifier for each parameter setting. gs_fits = gs_procedure.fit(train_set["text"], train_set["sentiment"]) # Transforming GridSearch results to dataframe. gs_res = pd.DataFrame.from_dict(gs_fits.cv_results_, orient='columns', dtype=None, columns=None) # Modifying dataframe. ## Specifying columns to keep. gs_res = gs_res[["params", "mean_test_accuracy", "mean_train_accuracy", "mean_test_precision", "mean_train_precision", "mean_test_recall", "mean_train_recall", "mean_test_f1", "mean_train_f1"]] ## Renaming "test"-columns to "val"-columns (since it is actually the validation error, not test error). gs_res = gs_res.rename(columns={"mean_test_accuracy": "mean_val_accuracy", "mean_test_precision": "mean_val_precision", "mean_test_recall": "mean_val_recall", "mean_test_f1": "mean_val_f1"}) ## Adding model name, vectorizer name and preprocess name. gs_res["model"] = model_name gs_res["vectorizer"] = vect_name gs_res["preprocess"] = preprocess_name # Appending dataframe to initialized dataframe. results = results.append(gs_res) print(results) # Saving appended dataframe as csv. results.to_csv("vect_model_tuning/" + file_name + ".csv", index = False) ## Adding model index and ranks to final dataframe (from 1:n_models). Saving as csv. n_models = len(results) results["model_idx"] = list(range(1, n_models+1)) results["rank_val_accuracy"] = results["mean_val_accuracy"].rank(ascending = False) results["rank_val_accuracy"] = results["rank_val_accuracy"].astype(int) results["rank_val_precision"] = results["mean_val_precision"].rank(ascending = False) results["rank_val_precision"] = results["rank_val_precision"].astype(int) results["rank_val_recall"] = results["mean_val_recall"].rank(ascending = False) results["rank_val_recall"] = results["rank_val_recall"].astype(int) results["rank_val_f1"] = results["mean_val_f1"].rank(ascending = False) results["rank_val_f1"] = results["rank_val_f1"].astype(int) results.to_csv("vect_model_tuning/" + file_name + ".csv", index = False) def define_metric_settings(metric_name, x_range): '''Extract information for given metrics. Used within function "visual_model_comparison()".''' if metric_name == "accuracy": metric_range = [x - 0.075 for x in x_range] val_name = "mean_val_accuracy" train_name = "mean_train_accuracy" color = "blue" elif metric_name == "precision": metric_range = [x - 0.025 for x in x_range] val_name = "mean_val_precision" train_name = "mean_train_precision" color = "green" elif metric_name == "recall": metric_range = [x + 0.025 for x in x_range] val_name = "mean_val_recall" train_name = "mean_train_recall" color = "red" elif metric_name == "f1": metric_range = [x + 0.075 for x in x_range] val_name = "mean_val_f1" train_name = "mean_train_f1" color = "black" return {"metric_range": metric_range, "val_name": val_name, "train_name": train_name, "color": color} def visual_model_comparison(metric_list, gs_res, directory, plot_name, x_label = "Model index", top_n = "all"): ''' Compare models regarding specified metrics (acccuracy, precision, recall or/and f1) visually. If "top_n" is specified as integer, only top-n-models (according to their mean metrics rank) will be investigated. ''' # Defining font. rc('font', **{'family': 'serif', 'serif': ['Computer Modern']}) rc('text', usetex=True) ## Specifying models to keep for further investigation. Top-n-models will be considered for further investigation. if isinstance(top_n, int): # Defining rank criteria which are used to calculate mean rank. rank_criteria = [] for metric in metric_list: rank_criteria.append("rank_val_" + metric) ### Calculating mean rank for each model. Sorting models according their mean rank ascendingly. model_mean_ranks = gs_res[rank_criteria].mean(axis=1) model_mean_ranks = pd.DataFrame({'model_idx':gs_res["model_idx"], 'mean_rank':model_mean_ranks}).sort_values(by = ["mean_rank"]) ### Extracting model indices of top-n-models. top_n_indices = list(model_mean_ranks["model_idx"])[0:top_n] ### Subsetting data frame to only keep top-n-models. gs_res = gs_res.loc[gs_res["model_idx"].isin(top_n_indices)] ### Adjusting row indices. gs_res = gs_res.set_index([pd.Index(range(0, top_n))]) # Initializing legend elements. legend_elements = [] # Extracting number of models to visually analyze. n_models = len(gs_res) model_range = list(range(1, n_models+1)) # Adding metric values as points. for metric in metric_list: ## Appending legend element. legend_elements.append(Line2D([0], [0], marker = 'o', color = "w", markerfacecolor = define_metric_settings(metric, model_range)["color"], label = metric.capitalize())) ## Defining x-values for plot. metric_range = define_metric_settings(metric, model_range)["metric_range"] ## Defining column names for metric. colname_val = define_metric_settings(metric, model_range)["val_name"] colname_train = define_metric_settings(metric, model_range)["train_name"] ## Defining color for metric. col = define_metric_settings(metric, model_range)["color"] ## Initializing model to choose from. i = 0 ## Looping over each x-value. for x_metric in metric_range: ## Extracting and plotting val_metric and train_metric for current model. val_metric = gs_res[colname_val][i] train_metric = gs_res[colname_train][i] plt.plot(x_metric, val_metric, marker = "o", color = col) plt.plot(x_metric, train_metric, marker = "o", color = "grey", alpha = 0.5) ## Jumping to next model. i = i + 1 # Plotting line between train and validation metric values to highlight differences. ## Transforming metrics to be able to use plt.axvline. ### plt.axvline uses values ymin and ymax for 0 is bottom of the plot, 1 the top of the plot. ### Since plot ylim differs (not from 0 to 1), metric values have to be adjusted for usage of plt.axvline. ## Extracting ymin, ymax. axes = plt.gca() ylim = axes.get_ylim() ## Calculating range of ylim. ylim_range = ylim[1] - ylim[0] for metric in metric_list: ## Defining x-values for plot. metric_range = define_metric_settings(metric, model_range)["metric_range"] ## Defining column names for metric. colname_val = define_metric_settings(metric, model_range)["val_name"] colname_train = define_metric_settings(metric, model_range)["train_name"] ## Initializing model to choose from. i = 0 ## Looping over each x-value. for x_metric in metric_range: ## Extracting val_metric and train_metric for current model. val_metric = gs_res[colname_val][i] train_metric = gs_res[colname_train][i] ## Plotting lines between val_metric and train_metric for current model. if val_metric <= train_metric: vline_min = 1 - (ylim[1] - val_metric) / ylim_range vline_max = 1 - (ylim[1] - train_metric) / ylim_range else: vline_min = 1 - (ylim[1] - train_metric) / ylim_range vline_max = 1 - (ylim[1] - val_metric) / ylim_range plt.axvline(x_metric, ymin = vline_min, ymax = vline_max, color = "grey", alpha = 0.5) ## Jumping to next model. i = i + 1 # Finishing legend. legend_elements.append(Line2D([0], [0], marker = 'o', color = "w", alpha = 0.5, markerfacecolor = "grey", label = "Training score")) legend_elements.append(Line2D([0], [0], color = "grey", alpha = 0.5, lw = 2, label = "Difference")) # Plotting. if len(legend_elements) > 4: ncol_legend = 3 bbox = (0.5, 1.18) elif len(legend_elements) <= 4: ncol_legend = 4 bbox = (0.5, 1.12) plt.legend(handles = legend_elements, loc = "upper center", ncol = ncol_legend, bbox_to_anchor=bbox, fancybox = True, shadow = False) plt.xticks(model_range, (gs_res["model_idx"])) plt.xlabel(x_label) plt.ylabel("Score") plt.savefig(directory + "/" + plot_name + ".png", dpi = 500) plt.show() def fit_best_classifiers(model_dict, train_df, test_df): ''' Given a dictionary with all model pipelines to fit, the classifiers will be fit on the whole training set and evaluated on both training and test data. The '75%-approach' is also applied and evaluated. The resulting metrics are returned as data frames. ''' # Inizializing dataframe to store results in. results_classes = pd.DataFrame(columns=["model_idx", "mean_val_accuracy", "mean_train_accuracy", "mean_val_precision", "mean_train_precision", "mean_val_recall", "mean_train_recall", "mean_val_f1", "mean_train_f1"]) # Inizializing dataframe to store results in. results_probs = pd.DataFrame(columns=["model_idx", "mean_val_accuracy", "mean_train_accuracy", "mean_val_precision", "mean_train_precision", "mean_val_recall", "mean_train_recall", "mean_val_f1", "mean_train_f1"]) for key in model_dict: # Printing progress. print(key) # Extracting model name and model pipeline. model_name = model_dict[key][0] model_pipeline = model_dict[key][1] # Fitting classifier on whole training set. classifier = model_pipeline.fit(train_df["text"], train_df["sentiment"]) # Saving classifier. pickle.dump(classifier, open("best_classifiers/best_" + model_name + "_classifier" + ".sav", 'wb')) # Evaluating model using predicted classes. train_c_predictions = classifier.predict(train_df["text"]) test_c_predictions = classifier.predict(test_df["text"]) train_c_accuracy = accuracy_score(train_df["sentiment"], train_c_predictions) train_c_precision = precision_score(train_df["sentiment"], train_c_predictions) train_c_recall = recall_score(train_df["sentiment"], train_c_predictions) train_c_f1_score = f1_score(train_df["sentiment"], train_c_predictions) test_c_accuracy = accuracy_score(test_df["sentiment"], test_c_predictions) test_c_precision = precision_score(test_df["sentiment"], test_c_predictions) test_c_recall = recall_score(test_df["sentiment"], test_c_predictions) test_c_f1_score = f1_score(test_df["sentiment"], test_c_predictions) # Storing and saving results using predicted classes. results_classes = results_classes.append(pd.DataFrame({ "model_idx": [model_name], "mean_val_accuracy": [test_c_accuracy], "mean_train_accuracy": [train_c_accuracy], "mean_val_precision": [test_c_precision], "mean_train_precision": [train_c_precision], "mean_val_recall": [test_c_recall], "mean_train_recall": [train_c_recall], "mean_val_f1": [test_c_f1_score], "mean_train_f1": [train_c_f1_score]}), ignore_index = True) results_classes.to_csv("best_classifiers/results_classes.csv", index = False) # Evaluating model using predicted class probabilities. train_p_predictions = classifier.predict_proba(train_df["text"])[:,1] train_df_temp = train_df train_df_temp.loc[:, 'prob_pos'] = train_p_predictions train_df_temp = train_df_temp.loc[(train_df_temp["prob_pos"] >= 0.75) | (train_df_temp["prob_pos"] <= 0.25)] train_p_predictions = train_df_temp.loc[:, "prob_pos"] train_p_predictions = train_p_predictions.mask(train_p_predictions >= 0.75, 1) train_p_predictions = train_p_predictions.mask(train_p_predictions <= 0.25, 0) test_p_predictions = classifier.predict_proba(test_df["text"])[:,1] test_df_temp = test_df test_df_temp.loc[:, 'prob_pos'] = test_p_predictions test_df_temp = test_df_temp.loc[(test_df_temp["prob_pos"] >= 0.75) | (test_df_temp["prob_pos"] <= 0.25)] test_p_predictions = test_df_temp.loc[:, "prob_pos"] test_p_predictions = test_p_predictions.mask(test_p_predictions >= 0.75, 1) test_p_predictions = test_p_predictions.mask(test_p_predictions <= 0.25, 0) train_p_accuracy = accuracy_score(train_df_temp["sentiment"], train_p_predictions) train_p_precision = precision_score(train_df_temp["sentiment"], train_p_predictions) train_p_recall = recall_score(train_df_temp["sentiment"], train_p_predictions) train_p_f1_score = f1_score(train_df_temp["sentiment"], train_p_predictions) test_p_accuracy = accuracy_score(test_df_temp["sentiment"], test_p_predictions) test_p_precision = precision_score(test_df_temp["sentiment"], test_p_predictions) test_p_recall = recall_score(test_df_temp["sentiment"], test_p_predictions) test_p_f1_score = f1_score(test_df_temp["sentiment"], test_p_predictions) # Storing evaluation results in initialized dataframe. results_probs = results_probs.append(pd.DataFrame({ "model_idx": [model_name], "mean_val_accuracy": [test_p_accuracy], "mean_train_accuracy": [train_p_accuracy], "mean_val_precision": [test_p_precision], "mean_train_precision": [train_p_precision], "mean_val_recall": [test_p_recall], "mean_train_recall": [train_p_recall], "mean_val_f1": [test_p_f1_score], "mean_train_f1": [train_p_f1_score]}), ignore_index = True) results_probs.to_csv("best_classifiers/results_probs.csv", index = False) # Returning filled dataframes as dictionary. return {"results_classes": results_classes, "results_probs": results_probs} def classify_new_tweets(new_tweets_df, classifier): ''' Given a data frame including tweets and a classifier, the sentiment will be predicted. Only tweets with a predicted probability of at least 75% will be kept. The classification result will be added to the data frame which will be returned. ''' probs_pos = classifier.predict_proba(new_tweets_df["tweet"])[:,1] new_tweets_df.loc[:, 'prob_pos'] = probs_pos pos = new_tweets_df.loc[new_tweets_df["prob_pos"] >= 0.75] neg = new_tweets_df.loc[new_tweets_df["prob_pos"] <= 0.25] total = pos.append(neg) total.loc[total["prob_pos"] >= 0.75, "classification"] = "pos" total.loc[total["prob_pos"] <= 0.25, "classification"] = "neg" return total def plot_tweets_by_year(by_year_df, plot_name): ''' A plot to compare the regions (UK, Africa South) over time is created and saved. ''' ## Defining font. rc('font', **{'family': 'serif', 'serif': ['Computer Modern']}) rc('text', usetex=True) africa_df = by_year_df.loc[by_year_df["country"] == "Africa_South"] uk_df = by_year_df.loc[by_year_df["country"] == "UK"] plt.plot(africa_df["year"], africa_df["percentage"], marker = "o", color = "blue", alpha = 0.5) plt.plot(uk_df["year"], uk_df["percentage"], marker = "o", color = "black", alpha = 0.5) legend_elements = [Line2D([0], [0], marker = "o" , color = "black", alpha = 0.5, lw = 2, label = "UK"), Line2D([0], [0], marker = "o" , color = "blue", alpha = 0.5, lw = 2, label = "Africa")] plt.legend(handles = legend_elements, loc = "upper center", ncol = 2, bbox_to_anchor=(0.5, 1.12), fancybox = True, shadow = False) plt.xlabel("Year") plt.ylabel("Percentage of positive tweets") plt.xticks([2015, 2016, 2017, 2018, 2019]) plt.savefig("by_year/" + plot_name + ".png", dpi = 500) <file_sep>/Time Series Analysis/README.md # Lab files: Time Series Analysis |Lab|Content| |:---:|:---:| |Lab 1,2| Different assignments related to the ARIMA modeling cycle| |Lab 3|Implementation of Kalman Filter| :point_left: [Back to overview](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning#overview).<file_sep>/Text Mining/labs/README.md # Lab files: Text Mining |Lab|Content| |:---:|:---:| |Lab 1|Information Retrieval| |Lab 2|Text classification| |Lab 3|Text clustering and topic modelling| |Lab 4|Word embeddings| |Lab 5|Information extraction| :point_left: [Back to overview](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning#overview).<file_sep>/Advanced R Programming/lab03/lab03_result/README.Rmd --- output: github_document --- [![Travis build status](https://travis-ci.com/anubhav-dikshit/rLab3.svg?branch=master)](https://travis-ci.com/anubhav-dikshit/rLab3) [![Coverage status](https://codecov.io/gh/anubhav-dikshit/rLab3/branch/master/graph/badge.svg)](https://codecov.io/github/anubhav-dikshit/rLab3?branch=master) <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "man/figures/README-", out.width = "100%" ) ``` # rLab3 The goal of rLab3 is to Returns the GCD of two numbers and provides the shortest distance from a node in network to all other nodes ## Installation You can install the released version of rLab3 from [CRAN](https://CRAN.R-project.org) with: ``` r install.packages("rLab3") ``` ## Example This is a basic example which shows you how to solve a common problem: ```{r example} ## basic example code library(rLab3) euclidean(100,1000) wiki_graph <- data.frame(v1=c(1,1,1,2,2,2,3,3,3,3,4,4,4,5,5,6,6,6), v2=c(2,3,6,1,3,4,1,2,4,6,2,3,5,4,6,1,3,5), w=c(7,9,14,7,10,15,9,10,11,2,15,11,6,6,9,14,2,9)) dijkstra_adv(wiki_graph, 1) ``` <file_sep>/Machine Learning/README.md # Lab files: Machine Learning |Lab|Content| |:---:|:---:| |Lab 1| Spam classification with nearest neighbors, Inference about lifetime of machines, Feature selection by cross-validation in a linear model, Linear regression and regularization| |Lab 2| LDA and logistic regression, Analysis of credit scoring, Uncertainty estimation, Principal components| |Lab 3| Kernel methods, Support vector machines, Neural networks| |Lab 4| Ensemble methods, EM algorithm| |Lab 5| Using GAM and GLM to examine mortality rates, High-dimensional methods| :point_left: [Back to overview](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning#overview).<file_sep>/Advanced R Programming/lab02/lab02_result.R name = "<NAME>" liuid = "lensc874" # ******************************************************************************************** # 1.1 Conditional statements #### ## 1.1.1 sheldon_game(player1, player2) sheldon_game = function(player1, player2) { if(!player1 %in% c("rock","paper","scissors","lizard","spock") | !player2 %in% c("rock","paper","scissors","lizard","spock")) { stop("at least one of the players did not make an available choice.") } if(player1 == player2) { matchResult = "Draw!" } else if(player1 == "rock" & player2 %in% c("scissors","lizard") | player1 == "paper" & player2 %in% c("spock","rock") | player1 == "scissors" & player2 %in% c("lizard","paper") | player1 == "lizard" & player2 %in% c("spock","paper") | player1 == "spock" & player2 %in% c("scissors","rock")) { matchResult = "Player 1 wins!" } else { matchResult = "Player 2 wins!" } return(matchResult) } # ******************************************************************************************** # 1.2 for loops #### ## 1.2.1 my_moving_median() my_moving_median = function(x, n, ...) { if(!is.numeric(x)) { stop("x is not a numeric vector.") } if(!is.numeric(n)) { stop("n is not a numeric scalar.") } movingMedian = c() for(t in 1:(length(x)-n)) { movingMedian = c(movingMedian,median(x[t:(t+n)], ... )) } return(movingMedian) } ## 1.2.2 for_mult_table for_mult_table = function(from, to) { if(!is.numeric(from)) { stop("argument 'from' is not a numeric scalar.") } if(!is.numeric(to)) { stop("argument 'to' is not a numeric scalar.") } inputSequence = seq(from = from, to = to, by = 1) forMultTable = matrix(data = NA, nrow = length(inputSequence), ncol = length(inputSequence), dimnames = list(inputSequence, inputSequence)) for(rowname in rownames(forMultTable)) { for(colname in colnames(forMultTable)) { forMultTable[rowname,colname] = as.numeric(rowname)*as.numeric(colname) } } return(forMultTable) } # ******************************************************************************************** # 1.3 while loops #### ## 1.3.1 find_cumsum() find_cumsum = function(x, find_sum) { if(!is.numeric(x)) { stop("argument 'x' has to be a numeric vector.") } if(!is.numeric(find_sum)) { stop("argument 'find_sum' has to be a numeric scalar.") } cumSum = 0 i = 1 while(cumSum <= find_sum & i <= length(x)) { cumSum = cumSum + x[i] i = i+1 } return(cumSum) } ## 1.3.2 while_mult_table while_mult_table = function(from, to) { if(!is.numeric(from)) { stop("argument 'from' is not a numeric scalar.") } if(!is.numeric(to)) { stop("argument 'to' is not a numeric scalar.") } inputSequence = seq(from = from, to = to, by = 1) output = matrix(data = NA, nrow = length(inputSequence), ncol = length(inputSequence), dimnames = list(inputSequence, inputSequence)) while(sum(is.na(output)) > 0) { output[which(is.na(output))[1]] = as.numeric(rownames(output)[row(output)[which(is.na(output))[1]]]) * as.numeric(colnames(output)[col(output)[which(is.na(output))[1]]]) } return(output) } # ******************************************************************************************** # 1.4 repeat and loop controls #### ## 1.4.1 repeat_find_cumsum() repeat_find_cumsum = function(x, find_sum) { if(!is.numeric(x)) { stop("argument 'x' has to be a numeric vector.") } if(!is.numeric(find_sum)) { stop("argument 'find_sum' has to be a numeric scalar.") } cumSum = 0 i = 1 repeat { cumSum = cumSum + x[i] i = i+1 if(i>length(x) | cumSum > find_sum) { break } } return(cumSum) } ## 1.4.2 repeat_my_moving_median() repeat_my_moving_median = function(x, n, ...) { if(!is.numeric(x)) { stop("x is not a numeric vector.") } if(!is.numeric(n)) { stop("n is not a numeric scalar.") } movingMedian = c() t = 1 repeat { movingMedian = c(movingMedian,median(x[t:(t+n)], ...)) t = t+1 if(t > (length(x)-n)) { break } } return(movingMedian) } # ******************************************************************************************** # 1.5 Environment #### ## 1.5.1 in_environment() in_environment = function(env) { return(ls(env)) } # ******************************************************************************************** # 1.6 Functionals #### ## 1.6.1 cov() cov = function(X) { if(!is.data.frame(X)){ stop("X is not of class 'data.frame'") } return( unlist(lapply(X, function(X) sd(X)/mean(X))) ) } # ******************************************************************************************** # 1.7 Closures #### ## 1.7.1 moment() moment = function(i) { if(!is.numeric(i)){ stop("i has to be numeric.") } return( function(x) { sum = c() mean = mean(x) for(elem in x) { sum = c(sum, (elem-mean)^i) } return(mean(sum)) } ) } <file_sep>/Advanced R Programming/lab05/lab05_result/inst/server.R #' Server function that returns the weather information #' #' @param input for the server #' @param output for server #' @importFrom shiny renderText renderPrint #' @importFrom rLab5 get_data #' #' server <- function(input, output) { output$country = shiny::renderText(rLab5::get_data(input$city)$metaData$country) output$latitude = shiny::renderText(rLab5::get_data(input$city)$metaData$latitude) output$longitude = shiny::renderText(rLab5::get_data(input$city)$metaData$longitude) output$current = shiny::renderPrint({ output = c() for(chosenParam in input$param) { output = cbind(output, rLab5::get_data(input$city)$current[[chosenParam]]) } output = as.data.frame(output) colnames(output) = input$param print(output) }) output$forecast = shiny::renderPrint({ output = c() output = cbind(output, date = as.character( rLab5::get_data(input$city, input$forecast_horizon)$forecast$date)) if ("currentTempC" %in% input$param) { output = cbind(output, maxTempC = as.character( rLab5::get_data(input$city, input$forecast_horizon)$forecast$maxTempC)) } if ("currentWindKph" %in% input$param) { output = cbind(output, maxWindKph = as.character( rLab5::get_data(input$city, input$forecast_horizon)$forecast$maxWindKph)) } if ("currentHumidity" %in% input$param) { output = cbind(output, avgHumidity = as.character( rLab5::get_data(input$city, input$forecast_horizon)$forecast$avgHumidity)) } if ("currentCondition" %in% input$param) { output = cbind(output, dayCondition = as.character( rLab5::get_data(input$city, input$forecast_horizon)$forecast$dayCondition)) } output = as.data.frame(output) print(output) }) } <file_sep>/Text Mining/project/README.md # Project files: Text Mining Title: Sentiment analysis of Twitter data to analyse people's happiness - A comparison between a highly and less developed region :point_left: [Back to overview](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning#overview).<file_sep>/Advanced R Programming/lab05/lab05_result/vignettes/vignette.Rmd --- title: "Our Weather Forecast" author: "<NAME>, <NAME>, <NAME>" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Vignette Title} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ## API This package extracts data from the API of https://www.apixu.com. When using this package one can either create an account and request a personal key, or use the default key provided. With a shiny application the extracted data is then presented to the user in an interactive way, in which the user can specify the city of interest and number of days to be forecasted. ## The package This R package consits of three R scripts: (1) get_data.R, which extracts the data from the apixu and stores it as a data.frame, (2) ui.R, which specifies the user interface of the shiny app, (3) server.R, which computes output values and connects to the server. ## Use When typing in a cityname, do not use characters on letters. E.g., when trying to extract weather data for Linköping, type "Linkoping". ## Data The package includes one function called get_data(city, days) which returns a list with information about the specified location, current weather and the number of days to be forecasted as specified in the function. An example of the output of this function is shown below for the city Bangalore in India. ```{r echo = -1} library(rLab5) get_data("Bangalore", 1) ``` ```{r shiny example, eval=FALSE} ## shiny app library(rLab5) shiny::runGitHub(repo = "lennartsc/rLab5", subdir = "inst") ``` ## Default By default the shiny app shows an example for the city of Bangalore. One can easily change the city and forecast days by typing in a different city name and checking the forecast button, subsequently, one should specify the number of days to be forecasted. ## Enjoy the weather!! <file_sep>/Advanced R Programming/lab06/lab06_result/tests/testthat.R library(testthat) library(rLab6) test_check("rLab6") <file_sep>/Advanced R Programming/lab03/lab03_result/tests/testthat/test-my-test.R context("test-my-test.R") context("test-my-test.R") test_that("package works", { expect_equal(euclidean(100, 1000), 100) expect_equal(euclidean(123612, 13892347912), 4) expect_equal(euclidean(-100, 1000), 100) expect_equal(dijkstra_man(wiki_graph, 1), c(0,7,9,20,20,11)) expect_equal(dijkstra_man(wiki_graph,3), c(9,10,0,11,11,2)) expect_equal(dijkstra_adv(wiki_graph,1), c(0,7,9,20,20,11)) expect_equal(dijkstra_adv(wiki_graph,3), c(9,10,0,11,11,2)) }) test_that("Error messages are returned for erronous input in the Dijkstra algorithm.", { wiki_wrong_graph <- wiki_graph names(wiki_wrong_graph) <- c("v1, v3, w") expect_error(dijkstra_man(wiki_wrong_graph, 3)) expect_error(dijkstra_adv(wiki_wrong_graph, 3)) wiki_wrong_graph <- wiki_graph[1:2] expect_error(dijkstra_man(wiki_wrong_graph, 3)) expect_error(dijkstra_man(wiki_graph, 7)) expect_error(dijkstra_man(as.matrix(wiki_graph), 3)) expect_error(dijkstra_adv(wiki_wrong_graph, 3)) expect_error(dijkstra_adv(wiki_graph, 7)) expect_error(dijkstra_adv(as.matrix(wiki_graph), 3)) }) test_that("Wrong input throws an error.", { expect_error(euclidean("100", 1000)) expect_error(euclidean(0, 1000)) expect_error(euclidean(0, NA)) expect_error(euclidean(100, "1000")) expect_error(euclidean(TRUE, "1000")) }) <file_sep>/Advanced R Programming/lab05/lab05_result/tests/testthat/test-testing_package.R context("test-testing_package.R") test_that("get_data works", { expect_error(get_data(1,1)) expect_error(get_data(1,X)) }) <file_sep>/Advanced R Programming/lab06/lab06_result/data-raw/data_creation.R set.seed(42) n <- 2000 knapsack_objects <- data.frame( w=sample(1:4000, size = n, replace = TRUE), v=runif(n = n, 0, 10000) ) <file_sep>/Advanced R Programming/lab05/lab05_result/R/get_data.R #' Get current and forecasted weather data for a specified city #' #' This function requires a character of a city and optionally a forecast horizon to return a list with #' geographical information about the city, data about the current weather and if specified also detailed #' information for the forecasted time periode. #' #' @param city a character of the city for that weather needs to be fetched #' @param forecast_horizon An integer between 0 and 7 to specify the maximum forecast horizon in days. #' @param api_key a character of a valid 'Apixu' API key. If FALSE, the function uses the included standard API key. #' #' @return a list containing three main parts: 1) metaData: geographical information of the city, #' 2) current: current weather information, 3) forecast: forecast weather information #' #' @export #' @importFrom jsonlite fromJSON #' @importFrom RCurl url.exists #' #' @examples get_data("Bangalore", 1) #' get_data <- function(city, forecast_horizon = 0, api_key = FALSE){ # checking input # input_ciy if (!is.character(city)) stop("'city' should be a character.") # forecast_horizon if (!is.numeric(forecast_horizon) | !forecast_horizon %in% seq(0,7)) { stop("'forecast_horizon' should be of class numeric with a value within the range 0 to 7.") } # api_key if (isFALSE(api_key)) { api_key = "defd42234deb45f194a112828182609" } else { api_key = as.character(api_key) while (isFALSE(RCurl::url.exists(paste("http://api.apixu.com/v1/forecast.json?key=", api_key, "&q=Bremen", sep = "")))) { api_key = readline("The API key you specified is not valid. Insert a valid API key WITHOUT quotes. : ") } } # executing api request - returning json_data url = paste("http://api.apixu.com/v1/forecast.json?key=", api_key, "&q=", city, "&days=", forecast_horizon, sep = "") data_json = jsonlite::fromJSON(url) # transforming json_data to returnObject weatherObject = list( # metaData including information about the location metaData = list(name = data_json$location$name, country = data_json$location$country, latitude = data_json$location$lat, longitude = data_json$location$lon), # current including current weather information current = list(currentTempC = data_json$current$temp_c, currentWindKph = data_json$current$wind_kph, currentHumidity = data_json$current$humidity, currentCondition = data_json$current$condition$text), # forecast including forecast weather information forecast = setNames( as.data.frame( cbind( data_json$forecast$forecastday$date, data_json$forecast$forecastday$day$maxtemp_c, data_json$forecast$forecastday$day$mintemp_c, data_json$forecast$forecastday$day$avgtemp_c, data_json$forecast$forecastday$day$maxwind_kph, data_json$forecast$forecastday$day$avghumidity, data_json$forecast$forecastday$day$condition$text ) ), c("date", "maxTempC", "minTempC", "avgTempC", "maxWindKph", "avgHumidity", "dayCondition") ) ) # returning returnObject return(weatherObject) } <file_sep>/Advanced R Programming/lab03/lab03_result/R/wiki_graph.R #' A graph dataset is present here #' #' A dataset containing the source, destination and weight of each node #' #' @format A data frame with 18 rows and 3 variables: #' \describe{ #' \item{v1}{source node} #' \item{v2}{destination node} #' \item{w}{weight or distance} #' ... #' } "wiki_graph"<file_sep>/Introduction to Python/lab05/text_stats.py #!/usr/bin/env python3 ## Importing modules. import sys import os import string import operator import re import collections # Testing terminal arguments and opening files. def open_files(command_args): # Printing error message if no file is provided. if len(command_args) - 1 == 0: raise ValueError(".txt-file from home directory has to be provided.") # Opening provided files. if command_args[0] == "text_stats.py": if len(command_args) - 1 == 1: data = open(command_args[1], encoding = "utf8") # If file not found, error will be returned. return data if len(command_args) - 1 == 2: data = open(command_args[1], encoding = "utf8") # If file not found, error will be returned. new_file = open(command_args[2], 'w') return data, new_file ## If used as import in "generate_text.py", always open sys.argv[0]. elif command_args[0] == "generate_text.py": data = open(command_args[1], encoding = "utf8") # If file not found, error will be returned. return data if __name__ == '__main__': # If-condition prevents running this code if file will be imported. opened_files = open_files(sys.argv) # Setting print location for print-function. ## If second argument provided by user, printout should be saved in provided file. ## Otherwise, results are just printed in terminal itself. def get_print_location(opened_files): if not isinstance(opened_files, tuple): # If only one file has been opened: return sys.stdout # Printout at terminal itself. else: # If two files have been opened: return opened_files[1] # Printout at second provided file. if __name__ == '__main__': # If-condition prevents running this code if file will be imported. print_location = get_print_location(opened_files) # Performing process of collecting information about characters and words. def create_collection(opened_files, valid_chars_regex): # Setting up process of collecting information about characters and words. ## Extracting data from opened_files. if not isinstance(opened_files, tuple): data = opened_files else: data = opened_files[0] ## Creating empty dictionary for collection of characters. char_dict = {} ## Creating empty dictionary for collection of words. word_dict = {} ## Creating empty string to track previous word. previous_word = "" ## Specifying allowed characters. regex = re.compile(valid_chars_regex) # Looping over each line of data and storing collected word/char information. for line in data: words = line.split() for word in words: # Filtering out non-alphabetical elements. Emtpy strings will not be considered as a word. word = regex.sub("", word) if word == "": continue # Lowering all characters within the word. word = word.lower() # Filling word dictionary. # Increasing number of word occurence at first position of dictionary word entry. if not word in word_dict: word_dict[word] = [1] else: word_dict[word][0] += 1 # Appending word to dictionary entry of previous occured word. if previous_word != "": word_dict[previous_word].append(word) # Saving word as last word. previous_word = word # Filling character dictionary. chars = list(word) for char in chars: if not char in char_dict: char_dict[char] = 1 else: char_dict[char] += 1 # Returning collections. return word_dict, char_dict if __name__ == '__main__': # If-condition prevents running this code if file will be imported. dics = create_collection(opened_files, "[^a-zA-Z]") # Aggregating collected information. def print_results(dics, print_location): # Extracting word and chat dictionaries from dics. word_dict = dics[0] char_dict = dics[1] # Printing ordered frequency table for alphabetic letters. print("Frequences of alphabetic letters, ordered from the most common to the least:", file = print_location) for char in sorted(char_dict, key = char_dict.get, reverse = True): print(char, char_dict[char], file = print_location) # Printing number of words. print("", file = print_location) print("Number of words in total:", file = print_location) n_words = 0 for word in word_dict.items(): n_words += word[1][0] print(n_words, file = print_location) # Printing number of unique words. print("", file = print_location) print("Number of unique words in total:", file = print_location) print(len(word_dict), file = print_location) # Printing five most frequent words and their frequencies. print("", file = print_location) print("Five most frequent words with frequency and words that most commonly follow them:", file = print_location) most_frequent_names = [] for key, items in word_dict.items(): if len(most_frequent_names) < 5: most_frequent_names.append(key) elif word_dict[key][0] > word_dict[most_frequent_names[0]][0]: most_frequent_names[4] = most_frequent_names[3] most_frequent_names[3] = most_frequent_names[2] most_frequent_names[2] = most_frequent_names[1] most_frequent_names[1] = most_frequent_names[0] most_frequent_names[0] = key elif word_dict[key][0] > word_dict[most_frequent_names[1]][0]: most_frequent_names[4] = most_frequent_names[3] most_frequent_names[3] = most_frequent_names[2] most_frequent_names[2] = most_frequent_names[1] most_frequent_names[1] = key elif word_dict[key][0] > word_dict[most_frequent_names[2]][0]: most_frequent_names[4] = most_frequent_names[3] most_frequent_names[3] = most_frequent_names[2] most_frequent_names[2] = key elif word_dict[key][0] > word_dict[most_frequent_names[3]][0]: most_frequent_names[4] = most_frequent_names[3] most_frequent_names[3] = key elif word_dict[key][0] > word_dict[most_frequent_names[4]][0]: most_frequent_names[4] = key for word in most_frequent_names: words_followed = collections.Counter(word_dict[word]).most_common(3) print(word + " (" + str(word_dict[word][0]) + " occurences)", file = print_location) print("-- " + str(words_followed[0][0]) + ", " + str(words_followed[0][1]), file = print_location) print("-- " + str(words_followed[1][0]) + ", " + str(words_followed[1][1]), file = print_location) print("-- " + str(words_followed[2][0]) + ", " + str(words_followed[2][1]), file = print_location) if __name__ == '__main__': # If-condition prevents running this code if file will be imported. print_results(dics, print_location) <file_sep>/Advanced Machine Learning/README.md # Lab files: Advanced Machine Learning |Lab|Content| |:---:|:---:| |Lab 1| Graphical Models| |Lab 2| Hidden Markov Models| |Lab 3| State Space Models| |Lab 4| Gaussian Processes| :point_left: [Back to overview](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning#overview).<file_sep>/Big Data Analytics/lab02/5.py from pyspark import SparkContext from pyspark.sql import SQLContext, Row from pyspark.sql import functions as F # Setting up Spark's execution environment. sc = SparkContext(appName = "BDA2_assignment5") sqlContext= SQLContext(sc) # Extracting Ostergotland stations. ## Creating RDD. stations_rdd = sc.textFile("/user/x_lensc/data/stations-Ostergotland.csv") ## Splitting lines. stations_rdd = stations_rdd.map(lambda line: line.split(";")) ## Creating DataFrame with column station_nr. stations_rdd = stations_rdd.map(lambda x: Row(ostergotland_station_nr = x[0])) stations_df = sqlContext.createDataFrame(stations_rdd) # Filtering precipitation data only for Ostergotland stations. ## Creating RDD. precip_rdd = sc.textFile("/user/x_lensc/data/precipitation-readings.csv") ## Splitting lines. precip_rdd = precip_rdd.map(lambda line: line.split(";")) ## Creating DataFrame with column station_nr. precip_rdd = precip_rdd.map(lambda x: Row(station_nr = x[0], year = int(x[1][0:4]), month = x[1][5:7], precip = float(x[3]))) precip_df = sqlContext.createDataFrame(precip_rdd) ## Filtering for period 1993-2016. precip_df = precip_df.filter(precip_df["year"] >= 1993) precip_df = precip_df.filter(precip_df["year"] <= 2016) ## Joining precipitation data with stations_df to keep only data for Ostergotland stations. precip_df = precip_df.join(stations_df, precip_df["station_nr"] == stations_df["ostergotland_station_nr"]).select( "station_nr", "year", "month", "precip") # Extracting average monthly precipitation over all stations. ## Extracting total monthly precipitation for each station. precip_df = precip_df.groupBy( "year", "month", "station_nr").agg(F.sum('precip').alias("precipitation_sum")) # Extracting average monthly precipitation over all stations. precip_df = precip_df.groupBy( "year", "month").agg(F.avg('precipitation_sum').alias("precipitation_avg")) # Ordering df BY year DESC, month DESC. precip_df = precip_df.orderBy(['year', 'month'], ascending=[0,0]) # Printing result. print("Extract of result shown as follows: year-month, average precipitation\n") print(precip_df.show(10)) # Closing Spark's execution environment. sc.stop() <file_sep>/Advanced R Programming/lab03/lab03_result/R/euclidean.R # 1.1.1 euclidean() #' Title euclidean() returns the gcd #' #' @param a first parameter #' @param b second parameter #' #' @return the gcd #' @export #' @source \href{https://en.wikipedia.org/wiki/Euclidean_algorithm}{Wikipedia} #' @examples euclidean(100,1000) euclidean <- function(a,b){ a <- abs(a) b <- abs(b) if(a == 0 | b == 0 | is.na(a) | is.na(b) | !is.numeric(a) | !is.numeric(b)){stop("incorrect inputs")} if(a > b){ temp <- b b <- a a <- temp } r <- b%%a return(ifelse(r, euclidean(a, r), a)) } <file_sep>/Advanced R Programming/lab06/lab06_result/R/knapsack_dynamic.R #' Title Dynamic Program Knapsack #' #' @param x The input to function containing the number of items #' @param W The weights of the items #' #' @return NULL #' @export #' @source http://www.es.ele.tue.nl/education/5MC10/Solutions/knapsack.pdf #' #' @examples set.seed(42) #' n <- 2000 #' knapsack_objects <- data.frame(w=sample(1:4000, size = n, replace = TRUE), v=runif(n = n, 0, 10000)) #'knapsack_dynamic(x = knapsack_objects[1:8,], W = 3500) #' knapsack_dynamic <- function(x, W){ stopifnot(is.data.frame(x),is.numeric(W)) stopifnot(W > 0) # reorder the items according to their weight to get near the maximum as soon as possible x <- x[rev(order(x[,1])),] # remove combinations that are invalid from the start # only consider items with a weight that is less than the capacity x <- x[x[,'w']<=W,] elements <- rownames(x) w <-(x[,1]) p <-(x[,2]) n <- nrow(x) # initiate arrays x <- logical(n) F <- matrix(0, nrow = W + 1, ncol = n) G <- matrix(0, nrow = W + 1, ncol = 1) # forwarding part for (k in 1:n) { F[, k] <- G H <- c(numeric(w[k]), G[1:(W + 1 - w[k]), 1] + p[k]) G <- pmax(G, H) } fmax <- G[W + 1, 1] # backtracking part f <- fmax j <- W + 1 for (k in n:1) { if (F[j, k] < f) { x[k] <- TRUE j <- j - w[k] f <- F[j, k] } } inds <- which(x) elem <- elements[x] prof <- round(sum(p[inds])) elem <- noquote(elem) return(list(value = prof, elements = elem)) } <file_sep>/Advanced R Programming/README.md # Lab files: Advanced R Programming |Lab|Content| |:---:|:---:| |Lab 1| Data structures| |Lab 2| Loops, functions, general syntax| |Lab 3,4,5,6| Create R packages including different functions, unit tests, vignettes, connection to a web API, Shiny application and different programming strategies| :point_left: [Back to overview](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning#overview).<file_sep>/Big Data Analytics/lab01/5.py from pyspark import SparkContext # Setting up Spark's execution environment. sc = SparkContext(appName = "bda1_assignment5") # Extracting Ostergotland stations and broadcasting RDD to all nodes. ## Creating RDD. stations_file = sc.textFile("/user/x_lensc/data/stations-Ostergotland.csv") ## Splitting lines. stations_file = stations_file.map(lambda line: line.split(";")) ## Extracting station number (key) and temperature (value). stations = stations_file.map(lambda x: (x[0])) ## Broadcasting stations data to each node (accessable over attribute 'value'). stations = stations.collect() stations = sc.broadcast(stations) # Filtering precipitation data only for Ostergotland stations. ## Creating RDD. precip_file = sc.textFile("/user/x_lensc/data/precipitation-readings.csv") ## Splitting lines. precip_file = precip_file.map(lambda line: line.split(";")) ## Filering data for Ostergotland stations. stations_precip = precip_file.filter(lambda x: x[0] in stations.value) # Calculating average monthly precipitation over all stations. ## Extracting total monthly precipitation for each station. stations_monthly_precip = stations_precip.map(lambda x: ((x[0], x[1][0:7]), float(x[3]))) stations_monthly_precip = stations_monthly_precip.reduceByKey(lambda a,b: a+b) # Extracting average monthly precipitation over all stations. avg_monthly_precip = stations_monthly_precip.map(lambda x: (x[0][1], (x[1], 1))) avg_monthly_precip = avg_monthly_precip.reduceByKey(lambda a,b: a+b) avg_monthly_precip = avg_monthly_precip.map(lambda x: (x[0], (x[1][0])/x[1][1])) # Printing result. print("Extract of result shown as follows: year-month, average precipitation\n") print(stations_monthly_precip.take(10)) # Closing Spark's execution environment. sc.stop() <file_sep>/Advanced R Programming/lab03/lab03_result/tests/testthat.R library(testthat) library(rLab3) test_check("rLab3") <file_sep>/Big Data Analytics/lab02/3.py from pyspark import SparkContext from pyspark.sql import SQLContext, Row from pyspark.sql import functions as F # Setting up Spark's execution environment. sc = SparkContext(appName = "BDA2_assignment3") sqlContext= SQLContext(sc) # Creating RDD. temperature_file = sc.textFile("/user/x_lensc/data/temperature-readings.csv") # Splitting lines. lines = temperature_file.map(lambda line: line.split(";")) # Creating DataFrame with columns date, station number and temperature. station_daily_all_rdd = lines.map(lambda x: Row(year = x[1][0:4], month = x[1][5:7], day = x[1][8:10], station_nr = x[0], temperature = float(x[3]))) station_daily_all_df = sqlContext.createDataFrame(station_daily_all_rdd) station_daily_all_df.registerTempTable("station_daily_all_rdd") # Filtering for period 1960-2014. station_daily_all_df = station_daily_all_df.filter(station_daily_all_df["year"] >= 1960) station_daily_all_df = station_daily_all_df.filter(station_daily_all_df["year"] <= 2014) # Aggregating maximum temperature per day and station. station_daily_max_df = station_daily_all_df.groupBy("station_nr", "year", "month", "day").agg( F.max("temperature").alias("temperature")) # Aggregating minimum temperature per day and station. station_daily_min_df = station_daily_all_df.groupBy("station_nr", "year", "month", "day").agg( F.min("temperature").alias("temperature")) # Unioning maximum and minimum daily temperatures per station. station_daily_minmax_df = station_daily_max_df.unionAll(station_daily_min_df) # Aggregating average monthly temperature per station. station_monthly_avg_df = station_daily_minmax_df.groupBy("station_nr", "year", "month").agg( F.avg("temperature").alias("temperature_avg")) # Ordering dataFrame by avgMonthlyTemperature DESC station_monthly_avg_df = station_monthly_avg_df.orderBy(["temperature_avg"], ascending=[0]) # Printing extract of results. print(station_monthly_avg_df.show(10)) # Closing Spark's execution environment. sc.stop() <file_sep>/Big Data Analytics/lab02/2.py from pyspark import SparkContext from pyspark.sql import SQLContext, Row from pyspark.sql import functions as F # Setting up Spark's execution environment. sc = SparkContext(appName = "BDA2_assignment2") sqlContext= SQLContext(sc) # Creating RDD. temperature_file = sc.textFile("/user/x_lensc/data/temperature-readings.csv") # Splitting lines. lines = temperature_file.map(lambda line: line.split(";")) # Creating DataFrame with columns year-month-day, station number and temperature. station_daily_all_rdd = lines.map(lambda x: Row(year = x[1][0:4], month = x[1][5:7], station_nr = x[0], temperature = float(x[3]))) station_daily_all_df = sqlContext.createDataFrame(station_daily_all_rdd) station_daily_all_df.registerTempTable("station_daily_all_rdd") # Filtering for period 1950-2014 and temperatures larger 10 degrees using SQL-like queries. station_daily_all_df = sqlContext.sql("SELECT * FROM station_daily_all_rdd WHERE year >= 1950 AND year <= 2014 AND temperature >= 10") # Using all readings. ## Counting. year_month_counts_all = station_daily_all_df.groupBy( "year", "month").agg(F.count("temperature").alias("count")) ## Ordering by value DESC. year_month_counts_all = year_month_counts_all.orderBy(["count"], ascending = [0]) ## Printing result. print("\nExtract of results using all readings:\n") print(year_month_counts_all.show(10)) # Using only distinct readings. ## Keeping one entry per station and month. station_monthly_distinct_df = station_daily_all_df.select("station_nr", "year", "month").distinct() ## Counting. station_monthly_distinct_df = station_monthly_distinct_df.groupBy( "year", "month").agg(F.count("station_nr").alias("count")) ## Ordering by value DESC. station_monthly_distinct_df = station_monthly_distinct_df.orderBy(["count"], ascending = [0]) ## Printing result. print("\nExtract of results using distinct readings:\n") print(station_monthly_distinct_df.show(10)) # Closing Spark's execution environment. sc.stop() <file_sep>/Big Data Analytics/lab02/6.py from pyspark import SparkContext from pyspark.sql import SQLContext, Row from pyspark.sql import functions as F # Setting up Spark's execution environment. sc = SparkContext(appName = "BDA2_assignment6") sqlContext= SQLContext(sc) # Creating RDD. temperature_file = sc.textFile("/user/x_lensc/data/temperature-readings.csv") # Splitting lines. lines = temperature_file.map(lambda line: line.split(";")) # Creating DataFrame with columns year-month-day, station number and temperature. station_daily_all_rdd = lines.map(lambda x: Row(year_month_day = x[1], station_nr = x[0], temperature = float(x[3]))) station_daily_all_df = sqlContext.createDataFrame(station_daily_all_rdd) station_daily_all_df.registerTempTable("station_daily_all_rdd") # Calculating monthly average temperature per station 1950-2014. ## Filtering for period 1950-2014. station_daily_all_df = station_daily_all_df.filter(station_daily_all_df["year_month_day"][0:4] >= 1950) station_daily_all_df = station_daily_all_df.filter(station_daily_all_df["year_month_day"][0:4] <= 2014) ## Aggregating maximum and minimum temperature per day and station. station_daily_max_df = station_daily_all_df.groupBy( "year_month_day", "station_nr").agg(F.max('temperature').alias("temperature")) station_daily_min_df = station_daily_all_df.groupBy( "year_month_day", "station_nr").agg(F.min('temperature').alias("temperature")) ## Unioning DataFrames. station_daily_min_max_df = station_daily_max_df.unionAll(station_daily_min_df) ## Aggregating average monthly temperature per station. station_monthly_avg_df = station_daily_min_max_df.groupBy( station_daily_min_max_df["year_month_day"][0:7].alias("year_month"), "station_nr").agg(F.avg("temperature").alias("temperature_avg")) # Calculating average temperature over all stations for a specific year and month 1950-2014 monthly_avg_df = station_monthly_avg_df.groupBy("year_month").agg(F.avg("temperature_avg").alias("temperature_avg")) # Calculating long-term monthly averages in the period of 1950-1980. ## Filtering for period 1950-1980. monthly_avg_longterm_df = monthly_avg_df.filter(monthly_avg_df["year_month"][0:4] >= 1950) monthly_avg_longterm_df = monthly_avg_df.filter(monthly_avg_df["year_month"][0:4] <= 1980) ## Calculating monthly averages. monthly_avg_longterm_df = monthly_avg_longterm_df.groupBy( monthly_avg_longterm_df["year_month"][6:7].alias("month")).agg(F.avg("temperature_avg").alias("temperature_avg_longterm")) # Adjusting monthly_avg_df by adding long-term averages. monthly_avg_df = monthly_avg_df.join(monthly_avg_longterm_df, monthly_avg_df["year_month"][6:7] == monthly_avg_longterm_df["month"]) # Calculating difference and selecting columns year, month, difference. monthly_avg_df = monthly_avg_df.select(monthly_avg_df["year_month"][0:4].alias("year"), monthly_avg_df["year_month"][6:7].alias("month"), (monthly_avg_df["temperature_avg"] - monthly_avg_df["temperature_avg_longterm"]).alias("difference")) # Ordering dataFrame by year DESC, month DESC. monthly_avg_df = monthly_avg_df.orderBy(['year', 'month'], ascending=[0,0]) # Printing extract of results. print(monthly_avg_df.show(10)) # Storing results. monthly_avg_df.rdd.repartition(1).saveAsTextFile("bda2_result_assignment6") # Closing Spark's execution environment. sc.stop() <file_sep>/Advanced R Programming/lab03/lab03_result/README.md [![Travis build status](https://travis-ci.com/anubhav-dikshit/rLab3.svg?branch=master)](https://travis-ci.com/anubhav-dikshit/rLab3) [![Coverage status](https://codecov.io/gh/anubhav-dikshit/rLab3/branch/master/graph/badge.svg)](https://codecov.io/github/anubhav-dikshit/rLab3?branch=master) <!-- README.md is generated from README.Rmd. Please edit that file --> rLab3 ===== The goal of rLab3 is to Returns the GCD of two numbers and provides the shortest distance from a node in network to all other nodes Installation ------------ You can install the released version of rLab3 from [CRAN](https://CRAN.R-project.org) with: ``` r install.packages("rLab3") ``` Example ------- This is a basic example which shows you how to solve a common problem: ``` r ## basic example code library(rLab3) euclidean(100,1000) #> [1] 100 wiki_graph <- data.frame(v1=c(1,1,1,2,2,2,3,3,3,3,4,4,4,5,5,6,6,6), v2=c(2,3,6,1,3,4,1,2,4,6,2,3,5,4,6,1,3,5), w=c(7,9,14,7,10,15,9,10,11,2,15,11,6,6,9,14,2,9)) dijkstra_adv(wiki_graph, 1) #> [1] 0 7 9 20 20 11 ``` <file_sep>/Big Data Analytics/lab01/2.py from pyspark import SparkContext # Setting up Spark's execution environment. sc = SparkContext(appName = "assignment2") # Creating RDD. temperature_file = sc.textFile("/user/x_lensc/data/temperature-readings.csv") # Splitting lines. lines = temperature_file.map(lambda line: line.split(";")) # Using all readings. ## Extracting year-month(key) and temperature(value). year_month_temperature = lines.map(lambda x: (x[1][0:7], float(x[3]))) ## Filtering for period 1950-2014 and temperatures larger 10 degrees. year_month_temperature = year_month_temperature.filter(lambda x: int(x[0][0:4]) in range(1950, 2015) and x[1] > 10) ## Mapping count of 1 to each filtered reading. year_month_counts = year_month_temperature.map(lambda x: (x[0], 1)) ## Adding up counts for each key(year-month) year_month_counts = year_month_counts.reduceByKey(lambda x,y: x+y) ## Printing result. print("\nExtract of results using all readings:\n") print(year_month_counts.take(10)) # Using only distinct readings. ## Extracting year-month(key) and temperature, station number (value). year_month_temperature = lines.map(lambda x: (x[1][0:7], (float(x[3]), x[0]))) ## Filtering for period 1950-2014 and temperatures larger 10 degrees. year_month_temperature = year_month_temperature.filter(lambda x: int(x[0][0:4]) in range(1950, 2015) and x[1][0] > 10) ## Mapping count of 1 to each filtered reading and keeping distinct pairs. year_month_counts = year_month_temperature.map(lambda x: (x[0], (x[1][1], 1))).distinct() ## Extracting year-month(key) and count(value). year_month_counts = year_month_counts.map(lambda x: (x[0], x[1][1])) ## Adding up counts for each key(year-month) year_month_counts = year_month_counts.reduceByKey(lambda x,y: x+y) ## Printing result. print("\nExtract of results using distinct readings:\n") print(year_month_counts.take(10)) # Closing Spark's execution environment. sc.stop() <file_sep>/Introduction to Python/README.md # Lab files: Introduction to Python |Lab|Content| |:---:|:---:| |Lab 1|Python Basics| |Lab 2|Functions and procedural abstraction| |Lab 3|Functional programming and declarative patterns| |Lab 4|Introductory Object-oriented Programming in Python| |Lab 5|Developing a script to extract and generate text| :point_left: [Back to overview](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning#overview).<file_sep>/Big Data Analytics/lab02/1a_temperature-readings.py from pyspark import SparkContext from pyspark.sql import SQLContext, Row from pyspark.sql import functions as F # Setting up Spark's execution environment. sc = SparkContext(appName = "BDA2_assignment1a_temperature-readings") sqlContext= SQLContext(sc) # Creating RDD. temperature_file = sc.textFile("/user/x_lensc/data/temperature-readings.csv") # Splitting lines. lines = temperature_file.map(lambda line: line.split(";")) # Creating DataFrame with columns year, station number and temperature. station_daily_all_rdd = lines.map(lambda x: Row(year = x[1][0:4], station_nr = x[0], temperature = float(x[3]))) station_daily_all_df = sqlContext.createDataFrame(station_daily_all_rdd) station_daily_all_df.registerTempTable("station_daily_all_rdd") # Filtering for period 1950-2014. station_daily_all_df = station_daily_all_df.filter(station_daily_all_df["year"] >= 1950) station_daily_all_df = station_daily_all_df.filter(station_daily_all_df["year"] <= 2014) # Identifying minimum temperature per year in descending order with respect to maximum temperature. station_daily_min_df = station_daily_all_df.groupBy("year").agg(F.min(station_daily_all_df["temperature"]).alias("temperature")) ## Adding station_nr to station_daily_min_df. station_daily_min_df = station_daily_min_df.join(station_daily_all_df, ["year", "temperature"]) ## Ordering dataFrame by minValue DESC. station_daily_min_df = station_daily_min_df.orderBy(["temperature"], ascending=[0]) # Identifying maximum temperature per year in descending order with respect to maximum temperature. station_daily_max_df = station_daily_all_df.groupBy("year").agg(F.max(station_daily_all_df["temperature"]).alias("temperature")) ## Adding station_nr to station_daily_min_df. station_daily_max_df = station_daily_max_df.join(station_daily_all_df, ["year", "temperature"]) ## Ordering dataFrame by minValue DESC. station_daily_max_df = station_daily_max_df.orderBy(["temperature"], ascending=[0]) # Printing results. print("Extrat of results for data:" + "temperature-readings.csv:") print("\nMaximum temperature per year:\n") print(station_daily_max_df.show(10)) print("\Minimum temperature per year:\n") print(station_daily_min_df.show(10)) sc.stop() <file_sep>/Introduction to Python/lab05/generate_text.py import text_stats import random import sys # Testing terminal arguments and opening files. if len(sys.argv) - 1 != 3: raise ValueError("Three arguments (file_name, starting_word, n_words) have to be provided.") opened_files = open(sys.argv[1], encoding = "utf8") # If file not found, error will be returned. # Setting print location for print-function. print_location = text_stats.get_print_location(opened_files) # Performing process of collecting information about characters and words. dics = text_stats.create_collection(opened_files, "[^a-zA-Z]") word_dict = dics[0] # Initializing starting_word, number of words and text. current_word = sys.argv[2] n_words = sys.argv[3] text = current_word # Creating message. '''word_dict stores for every key (therefore for every word) the number of appearences in the first position and all followed words appended in the other positions (in all other positions except the first position). Consequently, if the word 'am' follows the word 'I' 20 times within the text, then the string 'am' is appended 20 times to the dictionary-entry for key 'I'. Ignoring the first position of the values of every key, the next word will be chosen with its probability by just randomly choosing one of the appended words. If for example there are in total 100 words appended to the dictionary-entry of the key 'I', then, just randomly choosing one of the values(appended words), the word 'am' will be chosen with a probability of 20%.''' ## Iterating "number of words - times". for i in range(int(n_words)-1): # If no successors of current_word: printing message. if len(word_dict[current_word]) == 1: print("") print("Result of Text generator: ") print(text) break # Generating random number which will be the index of dictionary-entry for current_word. # Random number will be >= 1 (Because first element of dictionary-entry is not a word but number of appearences.). # Random number will be < length(dictionary-entry). random_number = (random.randint(1, len(word_dict[current_word])-1)) # The value belonging to the identied index will be chosen as next current_word. current_word = word_dict[current_word][random_number] # Current_word will be added to message. text = text + " " + current_word # Printing generated text. print("") print("Result of text generator for " + sys.argv[1] + " (" + n_words + " words): ") print(text) <file_sep>/Advanced R Programming/lab06/lab06_result/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> [![Travis build status](https://travis-ci.com/anubhav-dikshit/rLab6.svg?branch=master)](https://travis-ci.com/anubhav-dikshit/rLab6) [![Coverage status](https://codecov.io/gh/anubhav-dikshit/rLab6/branch/master/graph/badge.svg)](https://codecov.io/github/anubhav-dikshit/rLab6?branch=master) This packages is a fast knapsack solver. For a detailed background of the knapsack problem see [here](https://en.wikipedia.org/wiki/Knapsack problem). Within this vignette, the example data.frame `knapsack_objects` is used to show how to work with the package. It is a manually created data.frame with 2000 rows: ```{r, echo=FALSE, eval = TRUE} set.seed(42) n = 1000000 knapsack_objects <- data.frame( w=sample(1:4000, size = n, replace = TRUE), v=runif(n = n, 0, 10000) ) ``` ```{r, echo=TRUE, eval = TRUE} head(knapsack_objects) ``` ## Usage of the package The package includes in total three functions which all return the result for a specified knapsack problem. - `brute_force_knapsack(x, W)` - `knapsack_dynamic(x, W)` - `greedy_knapsack(x, W)` For each function, inputs `x` and `W` have to be specified. `x` has to be a data.frame with two columns called `v` (for value) and `w` (for weight). `W` is the specified maximum weight of the knapsack. All algorithms try to find - in a different way - the optimal filling of the knapsack to put in the maximum value considering the specified maximum weight `W`. ### `brute_force_knapsack(x, W)` ```{r, echo=FALSE, eval = TRUE} library(utils) brute_force_knapsack <- function(x, W){ original_value = x stopifnot(is.data.frame(x),is.numeric(W)) stopifnot(W > 0) # reorder the items according to their weight to get near the maximum as soon as possible x <- x[rev(order(x[,1])),] # remove combinations that are invalid from the start # only consider items with a weight that is less than the capacity x <- x[x[,'w']<=W,] elements <- rownames(x) i=2 optimum_value = 0 selected_items = c() weights<-c() values<-c() while(i<=nrow(x)) { w<-as.data.frame(combn(x[,1], i)) v<-as.data.frame(combn(x[,2], i)) sumw<-colSums(w) # most time consuming using profvis sumv<-colSums(v) # most time consuming using profvis weights<-which(sumw<=W) if(length(weights) != 0){ values<-sumv[weights] optimum_value<-max(values) temp<-which((values)==optimum_value) maxValWghtIdx<-weights[temp] maxValWght<-w[, maxValWghtIdx] j<-1 while (j<=i){ selected_items[j]<-which(x[,1]==maxValWght[j]) j=j+1 } } i=i+1 } elem <- subset(original_value, w %in% maxValWght) elem <- noquote(rownames(elem)) return(list(value=round(optimum_value), elements=elem)) } ``` ```{r, echo=TRUE, eval = TRUE} brute_force_knapsack(x = knapsack_objects[1:8,], W = 3500) ``` ### `knapsack_dynamic(x, W)` ```{r, echo=FALSE, eval = TRUE} knapsack_dynamic <- function(x, W){ stopifnot(is.data.frame(x),is.numeric(W)) stopifnot(W > 0) # reorder the items according to their weight to get near the maximum as soon as possible x <- x[rev(order(x[,1])),] # remove combinations that are invalid from the start # only consider items with a weight that is less than the capacity x <- x[x[,'w']<=W,] elements <- rownames(x) w <-(x[,1]) p <-(x[,2]) n <- nrow(x) # initiate arrays x <- logical(n) F <- matrix(0, nrow = W + 1, ncol = n) G <- matrix(0, nrow = W + 1, ncol = 1) # forwarding part for (k in 1:n) { F[, k] <- G H <- c(numeric(w[k]), G[1:(W + 1 - w[k]), 1] + p[k]) G <- pmax(G, H) } fmax <- G[W + 1, 1] # backtracking part f <- fmax j <- W + 1 for (k in n:1) { if (F[j, k] < f) { x[k] <- TRUE j <- j - w[k] f <- F[j, k] } } inds <- which(x) elem <- elements[x] prof <- round(sum(p[inds])) elem <- noquote(elem) return(list(value = prof, elements = elem)) } ``` ```{r, echo=TRUE, eval = TRUE} knapsack_dynamic(x = knapsack_objects[1:8,], W = 3500) ``` ### `greedy_knapsack(x, W)` ```{r, echo=FALSE, eval = TRUE} library(Rcpp) greedy_knapsack <- function(x, W, fast= NULL){ stopifnot(is.data.frame(x),is.numeric(W)) stopifnot(W > 0) x$v_by_w <- x$v/x$w # reorder the items according to their max profit per weight x <- x[rev(order(x[,3])),] x$max_weight <- W # remove combinations that are invalid from the start # only consider items with a weight that is less than the capacity x <- x[x[,'w']<=W,] elements <- rownames(x) x$running_weight <- cumsum(x$w) x$retain_in_bag <- ifelse(x$running_weight <= x$max_weight, "Retain", "Drop") x <- x[x$retain_in_bag == "Retain",] elem <- noquote(rownames(x)) if(!is.null(fast)){ prof <- round(vectorSum(x$v)) }else{prof <- round(sum(x$v))} elem <- noquote(elem) return(list(value = prof, elements = elem)) } ``` ```{r, echo=TRUE, eval = TRUE} greedy_knapsack(x = knapsack_objects[1:8,], W = 3500) ``` ## Speed of algorithms The speed of the algorithms is tested. By doing so, the questions in the lab6 are answered. ### `brute_force_knapsack(x, W)` Question: How much time does it takes to run the algorithm for n = 16 objects? ```{r, echo=TRUE, eval = TRUE} start_time <- Sys.time() brute_force_knapsack(x = knapsack_objects[1:16,], W = 3500) end_time <- Sys.time() end_time - start_time ``` ### `knapsack_dynamic(x, W)` Question: How much time does it takes to run the algorithm for n = 500 objects? ```{r, echo=TRUE, eval = TRUE} start_time <- Sys.time() knapsack_dynamic(x = knapsack_objects[1:500,], W = 3500) end_time <- Sys.time() end_time - start_time ``` ### `greedy_knapsack(x, W)` Question: How much time does it takes to run the algorithm for n = 1000000 objects? ```{r, echo=TRUE, eval = TRUE} start_time <- Sys.time() greedy_knapsack(x = knapsack_objects[1:1000000,], W = 3500) end_time <- Sys.time() end_time - start_time ``` <file_sep>/Advanced R Programming/lab06/lab06_result/R/brute_force_knapsack.R #' Title The Brute Force Knapsnack Solver #' #' @param x The input to function containing the number of items #' @param W The weights of the items #' #' #' @return NULL #' @export #' @importFrom utils combn #' @examples set.seed(42) #' n <- 2000 #' knapsack_objects <- data.frame(w=sample(1:4000, size = n, replace = TRUE), v=runif(n = n, 0, 10000)) #'brute_force_knapsack(x = knapsack_objects[1:8,], W = 3500) #' brute_force_knapsack <- function(x, W){ original_value = x stopifnot(is.data.frame(x),is.numeric(W)) stopifnot(W > 0) # reorder the items according to their weight to get near the maximum as soon as possible x <- x[rev(order(x[,1])),] # remove combinations that are invalid from the start # only consider items with a weight that is less than the capacity x <- x[x[,'w']<=W,] elements <- rownames(x) i=2 optimum_value = 0 selected_items = c() weights<-c() values<-c() while(i<=nrow(x)) { w<-as.data.frame(combn(x[,1], i)) v<-as.data.frame(combn(x[,2], i)) sumw<-colSums(w) # most time consuming using profvis sumv<-colSums(v) # most time consuming using profvis weights<-which(sumw<=W) if(length(weights) != 0){ values<-sumv[weights] optimum_value<-max(values) temp<-which((values)==optimum_value) maxValWghtIdx<-weights[temp] maxValWght<-w[, maxValWghtIdx] j<-1 while (j<=i){ selected_items[j]<-which(x[,1]==maxValWght[j]) j=j+1 } } i=i+1 } elem <- subset(original_value, w %in% maxValWght) elem <- noquote(rownames(elem)) return(list(value=round(optimum_value), elements=elem)) } <file_sep>/Advanced R Programming/lab06/lab06_result/src/vectorSum.cpp #include <Rcpp.h> using namespace Rcpp; #include <algorithm> // [[Rcpp::export]] double vectorSum(NumericVector x) { return std::accumulate(x.begin(), x.end(), 0.0); } <file_sep>/Big Data Analytics/lab01/1b.py import time import operator import sys # Storing starting time. start = time.time() # Initializing empty dictionaries. res_max = {} res_min = {} # Extracting file path from user-specified input. if sys.argv[1] == "temperature-readings.csv": file_path = "../../hadoop_examples/shared_data/temperature-readings.csv" elif sys.argv[1] == "temperatures-big.csv": file_path = "../../hadoop_examples/shared_data/temperatures-big.csv" else: print("SPECIFIED FILE DOES NOT EXIST.") # Filling dictionaries. with open(file_path) as file: for line in file: # Splitting line. line_splitted = line.split(";") # Skipping line if year not in desired period. if not float(line_splitted[1][0:4]) in range(1950, 2015): continue # Updating res_max. ## Initializing value (temperature, station_nr) for year if year entry does not exist yet. if not line_splitted[1][0:4] in res_max: res_max[line_splitted[1][0:4]] = [float(line_splitted[3]), line_splitted[0]] ## Updating value (temperature, station_nr) for year if year entry already exists. elif float(line_splitted[3]) > res_max[line_splitted[1][0:4]][0]: res_max[line_splitted[1][0:4]][0] = float(line_splitted[3]) # Updating res_min. ## Initializing value (temperature, station_nr) for year if year entry does not exist yet. if not line_splitted[1][0:4] in res_min: res_min[line_splitted[1][0:4]] = [float(line_splitted[3]), line_splitted[0]] ## Updating value (temperature, station_nr) for year if year entry already exists. elif float(line_splitted[3]) < res_min[line_splitted[1][0:4]][0]: res_min[line_splitted[1][0:4]][0] = float(line_splitted[3]) # Sorting results. ## Sorting res_max. res_max = sorted(res_max.items(), key = operator.itemgetter(1)) res_max.reverse() ## Sorting res_min. res_min = sorted(res_min.items(), key = operator.itemgetter(1)) res_min.reverse() # Printing results. print("Extract of results for data:" + sys.argv[1]) ## Printing res_max. print("\nMaximum temperature per year (including station number) in descending order with respect to maximum temperature:\n") print(res_max[0:11]) ## Printing res_min. print("\nMinimum temperature per year (including station number) in descending order with respect to maximum temperature:\n") print(res_min[0:11]) # Calculating running time.. end = time.time() print("Running time: " + str(end - start)) <file_sep>/Big Data Analytics/lab01/3.py from pyspark import SparkContext # Setting up Spark's execution environment. sc = SparkContext(appName = "assignment3") # Creating RDD. temperature_file = sc.textFile("/user/x_lensc/data/temperature-readings.csv") # Splitting lines. lines = temperature_file.map(lambda line: line.split(";")) # Extracting year-month-day, station number (key) and temperature (value). station_daily_all = lines.map(lambda x: ((x[1], x[0]), float(x[3]))) # Filtering for period 1960-2014. station_daily_all = station_daily_all.filter(lambda x: int(x[0][0][0:4]) in range(1960, 2015)) # Aggregating maximum temperature per day and station. station_daily_max = station_daily_all.reduceByKey(lambda a,b: a if a > b else b) # Aggregating minimum temperature per day and station. station_daily_min = station_daily_all.reduceByKey(lambda a,b: a if a < b else b) # Unioning maximum and minimum daily temperatures per station. station_daily_minmax = station_daily_max.union(station_daily_min) # Extracting year-month, station number (key) and daily min and max temperatures (value). station_monthly_minmax = station_daily_minmax.map(lambda x: ((x[0][0][0:7], x[0][1]), x[1])) # Aggregating average monthly temperature per station. station_monthly_avg = station_monthly_minmax.reduceByKey(lambda a,b: (a+b)/2) # Printing results. print("Extract of results:\n") print(station_monthly_avg.take(25)) # Closing Spark's execution environment. sc.stop() <file_sep>/Big Data Analytics/lab01/1a_temperature-readings.py from pyspark import SparkContext import time # Storing starting time. start = time.time() # Setting up Spark's execution environment. sc = SparkContext(appName = "assignment1_temperature-readings") # Creating RDD. temperature_file = sc.textFile("/user/x_lensc/data/temperature-readings.csv") # Performing RDD transformations. ## Splitting lines. lines = temperature_file.map(lambda line: line.split(";")) ## Extracting year(key) and temperature, station_nr (value). year_temperature = lines.map(lambda x: (x[1][0:4], (float(x[3]), x[0]))) ## Filtering for period 1950-2014. year_temperature = year_temperature.filter(lambda x: int(x[0]) in range(1950, 2015)) # Performing RDD actions. ## Identifying maximum temperature per year in descending order with respect to maximum temperature. ### Aggregating maximum temperature per year. max_temperatures = year_temperature.reduceByKey(lambda a,b: a if a[0] >= b[0] else b) ### Sorting key-value-pairs by decreasing values. max_temperatures_sorted = max_temperatures.sortBy(keyfunc = lambda elem: elem[1][0], ascending = False) ### Printing ordered maximum temperatures per year. print("Extrat of results for data:" + "temperature-readings.csv:") print("\nMaximum temperature per year (year, (temperature, station nr)) in descending order with respect to maximum temperature:\n") print(max_temperatures_sorted.take(10)) ## Identifying maximum temperature per year in descending order with respect to maximum temperature. ### Aggregating maximum temperature per year. min_temperatures = year_temperature.reduceByKey(lambda a,b: a if a[0] <= b[0] else b) ### Sorting key-value-pairs by decreasing values. min_temperatures = min_temperatures.sortBy(keyfunc = lambda elem: elem[1][0], ascending = False) ### Printing ordered maximum temperatures per year. print("\nMinimum temperature per year (year, (temperature, station nr)) in descending order with respect to maximum temperature:\n") print(min_temperatures.take(10)) # Closing Spark's execution environment. sc.stop() # Calculating running time.. end = time.time() print("\nRunning time: " + str(end - start)) <file_sep>/Big Data Analytics/README.md # Lab files: Big Data Analytics |Lab|Content| |:---:|:---:| |Lab 1| Spark| |Lab 2| Spark SQL| |Lab 3| Machine Learning with Spark| :point_left: [Back to overview](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning#overview).<file_sep>/README.md # MSc Statistics & Machine Learning <img src="./LiU_logo.png"> This repository serves to give an overview of my gained knowledge within the Master's program "Statistics & Machine Learning" at Linköping University. The curriculum joins courses in statistics, computer science and mathematics into a programme in the interface between statistics and computer science. For further information about the programme, click [here](https://liu.se/en/education/program/f7msl). ## Overview The courses taken are listed. Clicking on a linked course will take you to the detailed section of the course. **First semester** * [Advanced Academic Studies](#advanced-academic-studies-3-ects) (3 ECTS) * [Advanced R Programming](#advanced-r-programming-6-ects) (6 ECTS) * [Bioinformatics](#bioinformatics-6-ects) (6 ECTS) * [Machine Learning](#machine-learning-9-ects) (9 ECTS) * [Statistical Methods](#statistical-methods-6-ects) (6 ECTS) **Second semester** * [Advanced Data Mining](#advanced-data-mining-6-ects) (6 ECTS) * [Bayesian Learning](#bayesian-learning-6-ects) (6 ECTS) * [Big Data Analytics](#big-data-analytics-6-ects) (6 ECTS) * [Computational Statistics](#computational-statistics-6-ects) (6 ECTS) * [Introduction to Python](#introduction-to-python-3-ects) (3 ECTS) * [Philosophy of Science](#philosophy-of-science-3-ects) (3 ECTS) **Third semester** * [Advanced Machine Learning](#advanced-machine-learning-6-ects) (6 ECTS) * [Time Series Analysis](#time-series-analysis-6-ects) (6 ECTS) * [Decision Theory](#decision-theory-6-ects) (6 ECTS) * [Database Technology](#database-technology-6-ects) (6 ECTS) * [Text Mining](#text-mining-6-ects) (6 ECTS) **Fourth semester** * Master's Thesis (30 ECTS) An [individual repository](https://github.com/lennartsc/GANs-Keras) is created for the Master's thesis. ## Courses in detail For every course, a general description about its contents is given. In many courses we have worked - in groups as well as individually - on so-called labs in which the theoretically presented contents from the lectures were directly applied in practice. In this case, the labs are also described in detail in this section. You also have the possibility to access the corresponding files. ### Advanced Academic Studies (3 ECTS) **Course description** The main aims of the course are to give an information about the program structure and opportunities, to discuss practical questions related to the studies at the program, to learn scientific writing and referencing, ethical rules, how to avoid plagiarism, and how to use library facilities. **Labs** No labs. Content was taught exclusively theoretically in the form of lectures and written assignments. :point_up: [Back to overview](#overview). ### Advanced Data Mining (6 ECTS) **Course description** Principles and tools for dividing objects into groups and discovering relationships hidden in large data sets. Partitional methods and hierarchical clustering. Cluster evaluation. Association analysis using item sets and association rules. Evaluation of association patterns. **Labs** No labs. Content was taught exclusively theoretically in the form of lectures and written assignments. :point_up: [Back to overview](#overview). ### Advanced Machine Learning (6 ECTS) **Course description** Bayesian networks and hidden Markov models. State Space models and random fields. Gaussian processes. Kalman filtering. Particle methods. **Labs** |Lab|Content| |:---:|:---:| |Lab 1| Graphical Models| |Lab 2| Hidden Markov Models| |Lab 3| State Space Models| |Lab 4| Gaussian Processes| :floppy_disk: [Access lab files](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning/tree/master/Advanced%20Machine%20Learning). :point_up: [Back to overview](#overview). ### Advanced R Programming (6 ECTS) **Course description** R Environment. General programming techniques. Language concepts of R: variables, vectors, matrices, data frames. Language tools: operators, loops, conditions, functions. Importing data from text and spreadsheet files. Using external R packages. Graphics. Object-oriented programming. Performance enhancement and parallel programming. Literate programming. Developing R packages. **Labs** |Lab|Content| |:---:|:---:| |Lab 1| Data structures| |Lab 2| Loops, functions, general syntax| |Lab 3,4,5,6| Create R packages including different functions, unit tests, vignettes, connection to a web API, Shiny application and different programming strategies| :floppy_disk: [Access lab files](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning/tree/master/Advanced%20R%20Programming). :point_up: [Back to overview](#overview). ### Bayesian Learning (6 ECTS) **Course description** Bayes' theorem to combine data information with other prior information. Bayesian analysis of conjugate models. Markov Chain Monte Carlo methods for Bayesian computations. Bayesian model comparison. **Labs** |Lab|Content| |:---:|:---:| |Lab 1| Exploring posterior distributions in one-parameter models by simulation and direct numerical evaluation| |Lab 2| Polynomial regression and classification with logistic regression| |Lab 3| MCMC using Gibbs sampling and Metropolis-Hastings| |Lab 4| Hamiltonian Monte Carlo with Stan| :floppy_disk: [Access lab files](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning/tree/master/Bayesian%20Learning). :point_up: [Back to overview](#overview). ### Big Data Analytics (6 ECTS) **Course description** File systems and databases for Big Data. Querying for Big Data. Resource management in a cluster environment. Parallelizing computations for Big Data. Machine Learning for Big Data. **Labs** |Lab|Content| |:---:|:---:| |Lab 1| Spark| |Lab 2| Spark SQL| |Lab 3| Machine Learning with Spark| :floppy_disk: [Access lab files](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning/tree/master/Big%20Data%20Analytics). :point_up: [Back to overview](#overview). ### Bioinformatics (6 ECTS) **Course description** Basics of molecular biology and genetics. Hidden Markov models, genetic sequence analysis. Sequence similarity, sequence alignment. Phylogeny reconstruction. Quantitative trait modelling. Microarray analysis. Network biology. **Labs** :floppy_disk: [Access lab files](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning/tree/master/Bioinformatics). :point_up: [Back to overview](#overview). ### Computational Statistics (6 ECTS) **Course description** Computer arithmetic. Random number generation and simulation techniques. Markov Chain Monte Carlo methods. Numerical linear algebra. Optimization methods in statistics. **Labs** |Lab|Content| |:---:|:---:| |Lab 1| Computer arithmetics| |Lab 2| Optimization| |Lab 3| Random number generation| |Lab 4| Monte Carlo Methods| |Lab 5| Model Selection and Hypothesis Testing| |Lab 6| Genetic algorithm, EM algorithm| :floppy_disk: [Access lab files](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning/tree/master/Computational%20Statistics). :point_up: [Back to overview](#overview). ### Database Technology (6 ECTS) **Course description** General database management systems (DBMS). Methods for data modelling and database design. ER-diagrams, relational databases and data structures for databases. Architectures and query languages for the relational model. Relational algebra and query optimization. :point_up: [Back to overview](#overview). ### Decision Theory (6 ECTS) **Course description** Probabilistic reasoning and likelihood theory. Bayesian hypothesis testing. Decision theoretic elements. Utility and loss functions. Graphical modeling as a tool for decision making. Sequential analysis. **Labs** No labs. Content has been taught exclusively theoretically in the form of lectures and written assignments. :point_up: [Back to overview](#overview). ### Introduction to Python (3 ECTS) **Course description** Python environment. Data structures: numbers, strings, lists, tuples, dictionaries. Basic language elements: loops, conditions, functions. Modules. Input and Output. Debugging. Machine learning and data mining in Python. **Labs** |Lab|Content| |:---:|:---:| |Lab 1|Python Basics| |Lab 2|Functions and procedural abstraction| |Lab 3|Functional programming and declarative patterns| |Lab 4|Introductory Object-oriented Programming in Python| |Lab 5|Developing a script to extract and generate text| :floppy_disk: [Access lab files](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning/tree/master/Introduction%20to%20Python). :point_up: [Back to overview](#overview). ### Machine Learning (9 ECTS) **Course description** Basic concepts in machine learning and data mining. Bayesian and frequentist modelling, model selection. Linear regression and regularization. Linear discriminant analysis and logistic regression. Bagging and boosting. Splines, generalized additive models, trees, and random forests. Kernel smoothers and support vector machines. Gaussian process. **Labs** |Lab|Content| |:---:|:---:| |Lab 1|Spam classification with nearest neighbors, Inference about lifetime of machines, Feature selection by cross-validation in a linear model, Linear regression and regularization| |Lab 2|LDA and logistic regression, Analysis of credit scoring, Uncertainty estimation, Principal components| |Lab 3|Kernel methods, Support vector machines, Neural networks| |Lab 4|Ensemble methods, EM algorithm| |Lab 5|Using GAM and GLM to examine mortality rates, High-dimensional methods| :floppy_disk: [Access lab files](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning/tree/master/Machine%20Learning). :point_up: [Back to overview](#overview). ### Philosophy of Science (3 ECTS) **Course description** Philosophy of science is an attempt to give an account of what science is, and what it is that distinguishes science from other activities. This can be done in several different ways, for instance by studying the history of science, that is, studying how people in different periods have viewed scientific activities. It could also be studied in a more sociological manner, examining how science is organized today. The focus of this course is more normative, however: the main issue is to examine how science should be conducted, what it is that distinguishes good science from bad science, or science from pseudo-science. Focusing on the normative aspects of science will involve studying what a scientific theory is, how a scientific theory is related to observation, and what a scientific theory will tell us about the world. **Labs** No labs. Content was taught exclusively theoretically in the form of lectures and written assignments. :point_up: [Back to overview](#overview). ### Statistical Methods (6 ECTS) **Course description** Concept of probability. Random variable, common statistical distributions and their properties. Point and interval estimation. Hypothesis testing. Simple and multiple linear regression. Resampling. Elements of Bayesian theory. **Labs** No labs. Content was taught exclusively theoretically in the form of lectures and written assignments. :point_up: [Back to overview](#overview). ### Text Mining (6 ECTS) **Course description** Retrieval of textual data from different sources. Text processing by means of computational linguistics. Statistical models for text classification and prediction. **Labs** |Lab|Content| |:---:|:---:| |Lab 1|Information Retrieval| |Lab 2|Text classification| |Lab 3|Text clustering and topic modelling| |Lab 4|Word embeddings| |Lab 5|Information extraction| :floppy_disk: [Access lab files](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning/tree/master/Text%20Mining/labs). **Project** Title: Sentiment analysis of Twitter data to analyse people's happiness - A comparison between a highly and less developed region :floppy_disk: [Access project files](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning/tree/master/Text%20Mining/project). :point_up: [Back to overview](#overview). ### Time Series Analysis (6 ECTS) **Course description** Introduction to Probability and Time Series Analysis. Exploratory Analysis and Time Series Regression. ARIMA Models. State Space Models. Deep Learning Methods: RNN. **Labs** |Lab|Content| |:---:|:---:| |Lab 1,2| Different assignments related to the ARIMA modeling cycle| |Lab 3|Implementation of Kalman Filter| :floppy_disk: [Access lab files](https://github.com/lennartsc/MSc-Statistics-and-Machine-Learning/tree/master/Time%20Series%20Analysis). :point_up: [Back to overview](#overview).<file_sep>/Advanced R Programming/lab03/lab03_result/R/dijkstra_man.R #' Title #' #' @param graph the input dataframe which represents a network #' @param init_node the node for which the distance to other nodes must be calculated #' #' @return returns a vector with distances to other nodes #' @export #' @source \href{https://en.wikipedia.org/wiki/Dijkstra\%27s_algorithm}{Wikipedia} #' #' @examples wiki_graph <- #' data.frame(v1=c(1,1,1,2,2,2,3,3,3,3,4,4,4,5,5,6,6,6), #' v2=c(2,3,6,1,3,4,1,2,4,6,2,3,5,4,6,1,3,5), #' w=c(7,9,14,7,10,15,9,10,11,2,15,11,6,6,9,14,2,9)) #' dijkstra_man(wiki_graph, 1) dijkstra_man = function(graph, init_node) { # checking input if(NCOL(graph) != 3){stop("Incorrect dataframe size")} if(any(colnames(graph) != c("v1", "v2", "w"))){stop("Incorrect dataframe names")} if(init_node >= length(unique(graph[,1]))){stop("Incorrect node selected")} if(!is.data.frame(graph) | !is.numeric(init_node)) { stop("input is not correct.") } # initialization of vectors 'nodesToVisit' and 'distances' nodesToVisit = c() distances = c() for (node in unique(graph$v1)) { # every distinct node in the graph will be added to the vector 'notesToVisit' nodesToVisit = c(nodesToVisit, node) # at the beginning, distance to the init_node will be set to zero and to all other notes to infinite if(node != init_node) { distances[as.character(node)] = Inf } else { distances[as.character(node)] = 0 } } # distance adjustment while(length(nodesToVisit) >= 1) { # in a loop, always the node of 'nodesToVisit' will the minimal distance to the init_node will be chosen currentNode = as.numeric(names(distances)[distances == min(distances[names(distances) %in% nodesToVisit])])[1] # for every neigbor of the currentNode, the distance to the init_note will be checked. If the distance is smaller than the currently saved distance, it will be edited. for (neighbor in graph[graph$v1 == currentNode,]$v2) { if(unname(distances[names(distances) == currentNode]) + graph[graph$v1 == currentNode & graph$v2 == neighbor,]$w < (unname(distances[names(distances) == neighbor]))) { distances[names(distances) == neighbor] = distances[names(distances) == currentNode] + graph[graph$v1 == currentNode & graph$v2 == neighbor,]$w } } # every node will be just visited once nodesToVisit = nodesToVisit[-which(nodesToVisit == currentNode)] } return(unname(distances)) } <file_sep>/Advanced R Programming/lab05/lab05_result/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> [![Travis build status](https://travis-ci.com/lennartsc/rLab5.svg?branch=master)](https://travis-ci.com/lennartsc/rLab5) [![Coverage status](https://codecov.io/gh/lennartsc/rLab5/branch/master/graph/badge.svg)](https://codecov.io/github/lennartsc/rLab5?branch=master) rLab5 ===== The goal of rLab5 is to create a R package to read from an API, in our case from APIXU.com which provides weather API. Installation ------------ You can install the released version of rLab5 from [CRAN](https://CRAN.R-project.org) with: ``` r install.packages("rLab5") ``` And the development version from [GitHub](https://github.com/) with: ``` r # install.packages("devtools") devtools::install_github("lennartsc/rLab5") ``` Example ------- This is a basic example which shows you how to solve a common problem: ``` r ## basic example code library(rLab5) get_data("Bangalore", 1) ``` <file_sep>/Advanced R Programming/lab06/lab06_result/R/knapsack_objects.R #' A dataset containing the knapsnack data is present here #' #' A dataset containing the weight and value of each item #' #' @format A data frame with 2000 rows and 2 columns. #' \describe{ #' \item{w}{weight of the item} #' \item{v}{value of the item} #' ... #' } "knapsack_objects"<file_sep>/Advanced R Programming/lab03/lab03_result/R/dijkstra_adv.R #' Title dijkstra_adv is the dataframe method for dijkstra #' #' @param df is the input dataframe #' @param node is the node for which the distances are computed #' #' @return returns a vector with distance to all other nodes #' @export #' @importFrom dplyr left_join bind_rows #' @importFrom data.table shift #' #' @source \href{https://en.wikipedia.org/wiki/Dijkstra\%27s_algorithm}{Wikipedia} #' #' @examples wiki_graph <- data.frame(v1=c(1,1,1,2,2,2,3,3,3,3,4,4,4,5,5,6,6,6), #' v2=c(2,3,6,1,3,4,1,2,4,6,2,3,5,4,6,1,3,5), #' w=c(7,9,14,7,10,15,9,10,11,2,15,11,6,6,9,14,2,9)) #' dijkstra_adv(wiki_graph, 1) dijkstra_adv <- function(df, node) { if(NCOL(df) != 3){stop("Incorrect dataframe size")} if(any(colnames(df) != c("v1", "v2", "w"))){stop("Incorrect dataframe names")} if(node >= length(unique(df[,1]))){stop("Incorrect node selected")} if(is.data.frame(df) & is.numeric(node)){ n <- length(unique(df[,1])) colnames(df) <- c("S", "D", "W") result <- df for(i in 1:n-1){ df2 <- dplyr::left_join(x = result, y = df, by = c("D" = "S")) df2$W <- df2$W.x + df2$W.y df2 <- df2[,c("S", "D.y", "W")] colnames(df2)[colnames(df2)=="D.y"] <- "D" result <- dplyr::bind_rows(df2, df) result$W <- ifelse(result$S == result$D, 0, result$W) # fixing the self reference distance as zero result <- result[!duplicated(result),] rm(df2) } # sorting result <- result[with(result, order(S, D, W)), ] result$concat <- paste(result$S, result$D, sep = "") result$lag_concat <- data.table::shift(result$concat, n=1L, fill=0, type=c("lag"), give.names=FALSE) result$change_flag <- ifelse(result$concat == result$lag_concat, 0, 1) result <- result[result$change_flag == 1,] result <- result[, c("S", "D", "W")] temp_wide <- reshape2::dcast(result, S ~ D, value.var = "W", fill = 0) rownames(temp_wide) <- NULL return(as.vector(temp_wide[,node+1])) } else{stop("Input must be a dataframe")}} <file_sep>/Big Data Analytics/lab01/4.py from pyspark import SparkContext # Setting up Spark's execution environment. sc = SparkContext(appName = "assignment4") # Identifying maximum temperature per station. ## Creating RDD. temperature_file = sc.textFile("/user/x_lensc/data/temperature-readings.csv") ## Splitting lines. lines = temperature_file.map(lambda line: line.split(";")) ## Extracting station number (key) and temperature (value). station_temp_all = lines.map(lambda x: (x[0], float(x[3]))) ## Aggregating maximum temperature per station. station_temp_max = station_temp_all.reduceByKey(lambda a,b: a if a > b else b) # Identifying maximum daily precipitation per station. ## Creating RDD. precipitation_file = sc.textFile("/user/x_lensc/data/precipitation-readings.csv") ## Splitting lines. lines = precipitation_file.map(lambda line: line.split(";")) ## Extracting station number (key) and precipitation (value). station_precip_all = lines.map(lambda x: (x[0], float(x[3]))) ## Aggregating maximum daily precipitation per station. station_precip_max = station_precip_all.reduceByKey(lambda a,b: a if a > b else b) # Joining maximum temperature and maximum daily precipitation per station. station_temp_precip_max = station_temp_max.join(station_precip_max) # Filtering stations related to maximum temperature and maximum precipitation. station_temp_precip_max = station_temp_precip_max.filter(lambda x: x[1][0] >= 25 and x[1][0] <= 30) station_temp_precip_max = station_temp_precip_max.filter(lambda x: x[1][1] >= 100 and x[1][1] <= 200) # Printing result. print("Result shown as follows: station number, (maximum temperature, maximum daily precipitation)\n") print(station_temp_precip_max.collect()) # Closing Spark's execution environment. sc.stop() <file_sep>/Advanced R Programming/lab05/lab05_result/inst/ui.R #' Ui function that sets the ui #' #' @importFrom shiny fluidPage sidebarLayout sidebarPanel textInput selectInput mainPanel sliderInput checkboxGroupInput textOutput verbatimTextOutput conditionalPanel #' #' ui = shiny::fluidPage( shiny::sidebarLayout( # Inputs shiny::sidebarPanel( shiny::p(shiny::strong(shiny::textInput(inputId = "city", label = "City? (Letters should be without characters)", value = "Bangalore"))), shiny::checkboxGroupInput(inputId = "param", label = "Weather parameters?", choices = c("Temperature in °C" = "currentTempC", "Wind speed in km/h" = "currentWindKph", "Humidity in %" = "currentHumidity", "Condition" = "currentCondition"), selected = c("currentTempC","currentWindKph","currentHumidity","currentCondition") ), shiny::checkboxInput(inputId = "forecast_flag", label = "Forecast?" ), shiny::conditionalPanel( condition = "input.forecast_flag", shiny::sliderInput(inputId = "forecast_horizon", label = "Number of forecasted days?", min = 0, max = 7, value = 0 ) ) ), # Outputs shiny::mainPanel( shiny::p(shiny::strong("Country:")), shiny::textOutput(outputId = "country"), shiny::p(shiny::strong("Latitude:")), shiny::textOutput(outputId = "latitude"), shiny::p(shiny::strong("Longitude:")), shiny::textOutput(outputId = "longitude"), shiny::p(shiny::strong("Current weather data:")), shiny::verbatimTextOutput(outputId = "current"), shiny::conditionalPanel( condition = "input.forecast_flag", shiny::p(shiny::strong("Forecasted weather data:")), shiny::verbatimTextOutput(outputId = "forecast") ) ) ) ) <file_sep>/Advanced R Programming/lab06/lab06_result/R/greedy_knapsack.R #' Title Greedy Algorithm Knapsack #' #' @param x The input to function containing the number of items #' @param W The weights of the items #' @param fast Whether to speed up using Rccp #' #' @return NULL #' @export #' #' @examples set.seed(42) #' n <- 2000 #' knapsack_objects <- data.frame(w=sample(1:4000, size = n, replace = TRUE), v=runif(n = n, 0, 10000)) #'greedy_knapsack(x = knapsack_objects[1:8,], W = 3500) #' #' @useDynLib rLab6, .registration = TRUE #' @importFrom Rcpp sourceCpp greedy_knapsack <- function(x, W, fast= NULL){ stopifnot(is.data.frame(x),is.numeric(W)) stopifnot(W > 0) x$v_by_w <- x$v/x$w # reorder the items according to their max profit per weight x <- x[rev(order(x$v_by_w)),] x$max_weight <- W # only consider items with a weight that is less than the capacity x <- x[x[,'w']<=W,] elements <- rownames(x) x$running_weight_v_w <- cumsum(x$w) x$retain_in_bag_v_w <- ifelse(x$running_weight_v_w <= x$max_weight, "Retain", "Drop") x <- x[x$retain_in_bag_v_w == "Retain",] elem <- noquote(rownames(x)) if(!is.null(fast)){ prof <- round(vectorSum(x$v)) }else{prof <- round(sum(x$v))} elem <- noquote(elem) return(list(value = prof, elements = elem)) } <file_sep>/Big Data Analytics/lab02/4.py from pyspark import SparkContext from pyspark.sql import SQLContext, Row from pyspark.sql import functions as F # Setting up Spark's execution environment. sc = SparkContext(appName = "BDA2_assignment4") sqlContext= SQLContext(sc) # Identifying maximum temperature per station. ## Creating RDD. temperature_file = sc.textFile("/user/x_lensc/data/temperature-readings.csv") ## Splitting lines. lines = temperature_file.map(lambda line: line.split(";")) ## Creating DataFrame with columns station_nr and temperature. temp_station_all_rdd = lines.map(lambda x: Row(station_nr = x[0], temperature = float(x[3]))) temp_station_all_df = sqlContext.createDataFrame(temp_station_all_rdd) temp_station_all_df.registerTempTable("temp_station_all_rdd") ## Aggregating maximum temperature per station. temp_station_max_df = temp_station_all_df.groupBy("station_nr").agg( F.max("temperature").alias("temperature_max")) # Identifying maximum daily precipitation per station. ## Creating RDD. precipitation_file = sc.textFile("/user/x_lensc/data/precipitation-readings.csv") ## Splitting lines. lines = precipitation_file.map(lambda line: line.split(";")) ## Creating DataFrame with columns station_nr and precipitation. precip_station_all_rdd = lines.map(lambda x: Row(precip_station_nr = x[0], precipitation = float(x[3]))) precip_station_all_df = sqlContext.createDataFrame(precip_station_all_rdd) precip_station_all_df.registerTempTable("precip_station_all_rdd") ## Aggregating maximum daily precipitation per station. precip_station_max_df = precip_station_all_df.groupBy("precip_station_nr").agg( F.max("precipitation").alias("precipitation_max")) # Joining maximum temperature and maximum daily precipitation per station. temp_precip_station_max_df = temp_station_max_df.join(precip_station_max_df, temp_station_max_df["station_nr"] == precip_station_max_df["precip_station_nr"]).select( "station_nr", "temperature_max","precipitation_max") # Filtering stations related to maximum temperature and maximum precipitation. temp_precip_station_max_df = temp_precip_station_max_df.filter(temp_precip_station_max_df["temperature_max"] >= 25) temp_precip_station_max_df = temp_precip_station_max_df.filter(temp_precip_station_max_df["temperature_max"] <= 25) temp_precip_station_max_df = temp_precip_station_max_df.filter(temp_precip_station_max_df["precipitation_max"] >= 100) temp_precip_station_max_df = temp_precip_station_max_df.filter(temp_precip_station_max_df["precipitation_max"] <= 200) # Printing result. print("Extract of the result:\n") print(temp_precip_station_max_df.show(10)) # Closing Spark's execution environment. sc.stop() <file_sep>/Advanced R Programming/lab05/lab05_result/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> [![Travis build status](https://travis-ci.com/lennartsc/rLab5.svg?branch=master)](https://travis-ci.com/lennartsc/rLab5) [![Coverage status](https://codecov.io/gh/lennartsc/rLab5/branch/master/graph/badge.svg)](https://codecov.io/github/lennartsc/rLab5?branch=master) ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "man/figures/README-", out.width = "100%" ) ``` # rLab5 The goal of rLab5 is to create a R package to read from an API, in our case from APIXU.com which provides weather API. ## Installation You can install the released version of rLab5 from [CRAN](https://CRAN.R-project.org) with: ``` r install.packages("rLab5") ``` And the development version from [GitHub](https://github.com/) with: ``` r # install.packages("devtools") devtools::install_github("lennartsc/rLab5") ``` ## Example This is a basic example which shows you how to solve a common problem: ```{r example} ## basic example code library(rLab5) get_data("Bangalore", 1) ``` ```{r shiny example, eval=FALSE} ## shiny app library(rLab5) shiny::runGitHub(repo = "lennartsc/rLab5", subdir = "inst") ``` <file_sep>/Big Data Analytics/lab01/6.py from pyspark import SparkContext # Setting up Spark's execution environment. sc = SparkContext(appName = "assignment6") # Creating RDD. temperature_file = sc.textFile("/user/x_lensc/data/temperature-readings.csv") # Splitting lines. lines = temperature_file.map(lambda line: line.split(";")) # Calculating monthly average temperature per station 1950-2014. ## Extracting year-month-day, station number (key) and temperature (value). station_daily_all = lines.map(lambda x: ((x[1], x[0]), float(x[3]))) ## Filtering for period 1950-2014. station_daily_all = station_daily_all.filter(lambda x: int(x[0][0][0:4]) in range(1950, 2015)) ## Aggregating maximum temperature per day and station. station_daily_max = station_daily_all.reduceByKey(lambda a,b: a if a > b else b) ## Aggregating minimum temperature per day and station. station_daily_min = station_daily_all.reduceByKey(lambda a,b: a if a < b else b) ## Unioning maximum and minimum daily temperatures per station. station_daily_minmax = station_daily_max.union(station_daily_min) ## Extracting year-month, station number (key) and daily min and max temperatures (value). station_monthly_minmax = station_daily_minmax.map(lambda x: ((x[0][0][0:7], x[0][1]), x[1])) ## Aggregating average monthly temperature per station. station_monthly_avg = station_monthly_minmax.reduceByKey(lambda a,b: (a+b)/2) # Calculating average temperature over all stations for a specific year and month 1950-2014. monthly_avg = station_monthly_avg.map(lambda x: (x[0][0], (x[1], 1))) monthly_avg = monthly_avg.reduceByKey(lambda a,b: a+b) monthly_avg = monthly_avg.map(lambda x: (x[0], (x[1][0])/x[1][1])) # Calculating long-term monthly averages in the period of 1950-1980. ## Filtering for period 1950-1980. monthly_avg_longterm = monthly_avg.filter(lambda x: (int(x[0][0:4]) in range(1950, 1981))) ## Setting month as key and average temperature and counter as value. monthly_avg_longterm = monthly_avg_longterm.map(lambda x: (x[0][5:7], (x[1], 1))) ## Calculating monthly averages. monthly_avg_longterm = monthly_avg_longterm.reduceByKey(lambda x,y: x+y) monthly_avg_longterm = monthly_avg_longterm.map(lambda x: (x[0], (x[1][0])/x[1][1])) # Adjusting monthly_avg by adding differnces to long-term averages. ## Preparing monthly_avg for join with monthly_avg_longterm. monthly_avg = monthly_avg.map(lambda x: (x[0][5:7], (x[0], x[1]))) ## Joining monthly_avg with monthly_avg_longterm. monthly_avg = monthly_avg.join(monthly_avg_longterm) ## Remapping monthly_avg to format: year-month, (average, difference to long-term-average). monthly_avg = monthly_avg.map(lambda x: (x[1][0][0], x[1][0][1], x[1][0][1]-x[1][1])) # Printing results. ## Long-term monthly averages 1950-1980. print("Identified long-term monthly averages in the period of 1950-1980:\n") print(monthly_avg_longterm.collect()) ## Monthly averages 1950-2014 compared to long-term monthly averages. print("\nExtract of identified monthly averages in the period of 1950-2014 with differences to long-term monthly averages.") print("Format: (year-month, average, difference to long-term average):\n") print(monthly_avg.take(10)) # Storing results. monthly_avg.repartition(1).saveAsTextFile("result_assignment6") # Closing Spark's execution environment. sc.stop()
f02e02d6d797a7da2879b04022d088024798187d
[ "Markdown", "Python", "C++", "R", "RMarkdown" ]
56
R
lennartsc/MSc-Statistics-and-Machine-Learning
57905f689db794ca9bfe4775859106942d80456a
aa0d920955f12daf79c01d3233fc6381d5923672
refs/heads/main
<repo_name>hieuvoquang87/hacker-news-replica<file_sep>/app/src/widget/hooks/useHistory.ts import { useCallback, useContext } from 'react'; import HistoryContext from '../contexts/HistoryContext'; import { saveHistory } from '../services/cacheService' const useHistory = () => { const { loadedStories, setLoadedStories } = useContext(HistoryContext); const clearHistory = useCallback(() => { saveHistory([]); setLoadedStories([]); }, [setLoadedStories]) return { loadedStories, setLoadedStories, clearHistory } } export default useHistory;<file_sep>/app/src/widget/contexts/HistoryContext.ts import React from 'react' import { Story } from '../types' type HistoryContextProps = { loadedStories: Story[] setLoadedStories: React.Dispatch<React.SetStateAction<Story[]>> } const HistoryContext = React.createContext<HistoryContextProps>({ loadedStories: [], setLoadedStories: () => {} }); export default HistoryContext;<file_sep>/app/src/widget/utils/localStorageUtil.ts export const saveItemWithKey = (key: string, data: Object) => { if(typeof window !== 'undefined') { const dataString = JSON.stringify(data) window.localStorage.setItem(key, dataString) return true; } return false; } export const getItemWithKey = (key: string) => { if(typeof window !== 'undefined') { try { const dataString = window.localStorage.getItem(key); return dataString ? JSON.parse(dataString) : null; } catch (e) { return null; } } }<file_sep>/app/src/widget/types/index.ts export interface Item { id: number type: string by: string kids: number[] } export interface Story extends Item { type: 'story' title: string } export interface Comment extends Item { type: 'comment' text: string } <file_sep>/app/src/widget/contexts/BookmarkContext.ts import React from 'react' type BookmarkContextProps = { bookmarks: number[] setBookmarks: React.Dispatch<React.SetStateAction<number[]>> } const BookmarkContext = React.createContext<BookmarkContextProps>({ bookmarks: [], setBookmarks: () => {} }); export default BookmarkContext;<file_sep>/app/src/widget/hooks/useStory.ts import { useState, useCallback, useMemo } from 'react'; import { Story, Comment } from '../types'; import { getComments } from '../services/hnService'; const useStory = (story: Story) => { const commentIds = useMemo(() => story?.kids || [], [story]) const [comments, setComments] = useState<Comment[]>([]); const loadComment = useCallback(() => { getComments(commentIds).then((data) => { setComments(data) }) }, [commentIds]) return { commentIds, comments, loadComment } } export default useStory;<file_sep>/app/src/widget/hooks/useComment.ts import { useState, useCallback, useMemo } from 'react'; import { Comment } from '../types'; import { getComments } from '../services/hnService' const useComment = (comment: Comment) => { const commentIds = useMemo(() => comment?.kids || [], [comment]) const [comments, setComments] = useState<Comment[]>([]); const loadComment = useCallback(() => { getComments(commentIds).then((data) => { setComments(data) }) }, [commentIds]) return { commentIds, comments, loadComment } } export default useComment;<file_sep>/README.md # hacker-news-replica A Hacker News replica ### Run instruction 1. Clone this repo `git clone https://github.com/hieuvoquang87/hacker-news-replica.git` 2. Go to `app` folder `cd hacker-news-replica/app/` 3. Install dependencies `yarn` 4. Run app in devvelopment mode `yarn start` 5. Open app in browser at `http://localhost:3000` <file_sep>/app/src/widget/services/cacheService.ts import {saveItemWithKey, getItemWithKey } from '../utils/localStorageUtil'; import { Story } from '../types' const BOOKMARK_KEY = 'hn-bookmarks'; const HISTORY_KEY = 'hn-history'; export const saveBookmarkList = (bookmarks: number[]): boolean => { return saveItemWithKey(BOOKMARK_KEY, bookmarks) } export const getBookmarkList = (): number[] => { return getItemWithKey(BOOKMARK_KEY) } export const saveHistory = (history: Story[]): boolean => { return saveItemWithKey(HISTORY_KEY, history) } export const getHistory = (): Story[] => { return getItemWithKey(HISTORY_KEY) }<file_sep>/app/src/widget/hooks/useBookmark.ts import { useContext, useCallback, useMemo } from 'react'; import BookmarkContext from '../contexts/BookmarkContext'; import { saveBookmarkList } from '../services/cacheService' import { Item } from '../types'; const useBookmark = (item: Item) => { const { bookmarks, setBookmarks } = useContext(BookmarkContext); const hasBookmarked = useMemo(() => bookmarks?.length ? bookmarks.includes(item.id) : false, [item, bookmarks]) const bookmarkItem = useCallback(() => { const newBookmarks = [...bookmarks, item.id]; saveBookmarkList(newBookmarks) setBookmarks(newBookmarks) }, [bookmarks, item.id, setBookmarks]) const removeBookmark = useCallback(() => { const bookmarkedItemIdx = bookmarks.indexOf(item.id); if(bookmarkedItemIdx > -1) { bookmarks.splice(bookmarkedItemIdx, 1); const newBookmarks = [...bookmarks]; saveBookmarkList(newBookmarks); setBookmarks(newBookmarks); } }, [bookmarks, item.id, setBookmarks]) return { hasBookmarked, bookmarkItem, removeBookmark } } export default useBookmark;<file_sep>/app/src/widget/hooks/useMain.ts import { useState, useEffect } from 'react'; import { Story } from '../types'; import { getNewStoryIds, getNewStories } from '../services/hnService' import { getBookmarkList, getHistory, saveHistory } from '../services/cacheService' type MainHook = { newStoryIds: number[] newStories: Story[] bookmarks: number[] loadedStories: Story[] setBookmarks: React.Dispatch<React.SetStateAction<number[]>> setLoadedStories: React.Dispatch<React.SetStateAction<Story[]>> loadNextStories: () => void } const ITEMS_PER_PAGE = 10; const generateHistory = (currentHistory: Story[], newStories: Story[] ): Story[] => { const map = [...currentHistory, ...newStories].reduce((acc, item) => { acc.set(item.id, item); return acc; }, new Map<number, Story>()) return Array.from(map.values()); } const useMain = (): MainHook => { const [newStoryIds, setNewStoryIds] = useState<number[]>([]) const [newStories, setNewStories] = useState<Story[]>([]); const [loadedStories, setLoadedStories] = useState<Story[]>([]); const [bookmarks, setBookmarks] = useState<number[]>([]) // Init function useEffect(() => { getNewStoryIds().then((storyIds) => { const loadingIds = storyIds ? storyIds.slice(0, ITEMS_PER_PAGE) : []; getNewStories(loadingIds).then((stories) => { setNewStoryIds(storyIds) setNewStories(stories) const storyHistory = getHistory() || []; const newHistory = generateHistory(storyHistory, stories); setLoadedStories(newHistory) saveHistory(newHistory) }) }) const bookmarkList = getBookmarkList() || []; setBookmarks(bookmarkList) }, []) const loadNextStories = () => { const loadedStoriesLength = loadedStories.length; const loadingIds = newStoryIds.slice(loadedStoriesLength, loadedStoriesLength + ITEMS_PER_PAGE) getNewStories(loadingIds).then((stories) => { setNewStories([...newStories, ...stories]) setNewStoryIds(newStoryIds) const history = generateHistory(loadedStories, stories); setLoadedStories(history) saveHistory(history) }) } return { newStoryIds, newStories, bookmarks, loadedStories, setBookmarks, setLoadedStories, loadNextStories, } } export default useMain;<file_sep>/app/src/widget/services/hnService.ts import axios from 'axios'; import { Story, Comment } from '../types' const HACKER_NEWS_API_BASE_URL = 'https://hacker-news.firebaseio.com/v0'; const getItemPromise = <T>(itemId: number): Promise<T> => { const requestUrl = `${HACKER_NEWS_API_BASE_URL}/item/${itemId}.json`; return axios.get(requestUrl).then((result) => result.data || {}); } export const getNewStoryIds = async (): Promise<number[]> => { try { const requestUrl = `${HACKER_NEWS_API_BASE_URL}/newstories.json`; const result = await axios.get(requestUrl); return result.data || [] } catch (error) { return [] } } export const getNewStories = async (storyIds: number[]): Promise<Story[]> => { try { const promises = storyIds.map((storyId) => { return getItemPromise<Story>(storyId) }) return await Promise.all(promises); } catch (error) { return [] } } export const getComments = async (commentIds: number[]) => { try { const promises = commentIds.map((commentId) => { return getItemPromise<Comment>(commentId) }) return await Promise.all(promises); } catch (error) { return [] } }
0bdff96de35d253cae53994c669b3b02d1b01915
[ "Markdown", "TypeScript" ]
12
TypeScript
hieuvoquang87/hacker-news-replica
0502f1b36af85f82e3885b7f947dc835d4f099be
a068ddbcc34d6aa975df65e8f5d2612e50d18273
refs/heads/master
<repo_name>Souverain73/angular-weather-app<file_sep>/backend/src/shared/consts/user-logins.const.ts export const userLoginConst = [ { login: 'admin', password: '<PASSWORD>' }, { login: 'codedojo', password: '<PASSWORD>' }, { login: 'angular_ru', password: '<PASSWORD>' } ]; <file_sep>/backend/src/login/login.controller.ts import { Body, Controller, Get, HttpCode, HttpStatus, Post, Res, } from '@nestjs/common'; import { UserDto } from './dto/user.dto'; import { LoginService } from './login.service'; @Controller('login') export class LoginController { constructor(private readonly loginService: LoginService) {} @Get() checkLogin() { return 'login is Work'; } @HttpCode(204) @Post() async login(@Res() res, @Body() user: UserDto) { if (this.loginService.checkUser(user)) { res.status(HttpStatus.OK).send(user); } else { res.status(HttpStatus.UNAUTHORIZED).send(); } } } <file_sep>/backend/src/app.module.ts import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { LoginController } from 'login/login.controller'; import { LoginService } from 'login/login.service'; @Module({ imports: [], controllers: [AppController, LoginController], components: [LoginService], }) export class AppModule {} <file_sep>/README.md # О проекте Проект в рамках курса Codedojo - Angular in Action Angular + NestJS ## Логин для доступа login: angular_ru , password: '<PASSWORD>' ## TODO * Регистрация * API geolocation * Расширить список городов (возможно API) * Возможность добавлять избранное (интеграция с сервером) * Detail Card View
df0e05735470aa0b463c7cad3163e51935730fbe
[ "Markdown", "TypeScript" ]
4
TypeScript
Souverain73/angular-weather-app
484bac9e563137541ef03916f5fd075fad4d9779
383b43f7e86200aa8901031e8691dfcd15fe5410
refs/heads/master
<repo_name>yangyuanying/TestScript<file_sep>/upgradetest_ver4.py #encoding:utf-8 import paramiko import time from urllib import request from urllib import parse import json import os import threading # 机器人 Webhook地址 ROBOT_WEBHOOK = "" #磁盘路径 def build_text_msg(msg): params = dict() params["msgtype"] = "text" params["text"] = dict() params["text"]["content"] = msg params["at"] = dict() params["at"]["atMobiles"] = '[""]' params["at"]["isAtAll"] = False print (params) post_data = json.dumps(params) return post_data def send_msg(post_data): global ROBOT_WEBHOOK url_path = ROBOT_WEBHOOK req = request.Request(url_path) req.add_header('Content-Type', 'application/json') try: with request.urlopen(req, data=post_data.encode('utf-8')) as f: print ('Status:', f.status, f.reason) for k,v in f.getheaders(): print ('%s: %s' % (k,v)) resp_data = f.read().decode('utf-8') return resp_data except Exception as e: print ("Error:", e) resp_data = '{"errcode":0}' return resp_data class SSHConnection(object): #初始化 def __init__(self, host, port, username, password): self._host = host self._port = port self._username = username self._password = <PASSWORD> self._transport = None self._client = None #self._sftp = None self._connect() #连接、建立ssh通道 def _connect(self): try: transport = paramiko.Transport(self._host,self._port) transport.connect(username=self._username,password=self._password) self._transport = transport return 1 except paramiko.ssh_exception.SSHException as e: print ('ssh连接发生错误:',e) return 0 #执行命令 def exec_command(self,command): if self._client is None: self._client = paramiko.SSHClient() self._client._transport = self._transport stdin, stdout, stderr = self._client.exec_command(command) data = stdout.read() if len(data) > 0: print (data.strip()) #打印正确结果 return data err = stderr.read() if len(err) > 0: print (err.strip()) #输出错误结果 return err #上传 def upload(self,localpath,remotepath): if self._sftp is None: self._sftp = paramiko.SFTPClient.from_transport(self._transport) self._sftp.put(localpath,remotepath) #下载 def download(self,remotepath,localpath): if self._sftp is None: self._sftp = paramiko.SFTPClient.from_transport(self._transport) self._sftp.get(remotepath,localpath) #关闭ssh通道 def close(self): if self._transport: self._transport.close() if self._client: self._client.close() class MyThread(threading.Thread): def __init__(self,func,args=()): super(MyThread,self).__init__() self.func = func self.args = args def run(self): self.result = self.func(*self.args) def get_result(self): return self.result #重启设备 def reboot(conn): conn.exec_command('ubus call mnt reboot') time.sleep(20) #检查是否重启成功 def check_reboot(): conn = SSHConnection(ip,22,username,password) data = conn.exec_command('ls -la /tmp/before_reboot') data = data.decode('utf8') if ("No such file or directory" in data): print ("********** 设备重启成功 **********") return 1 else: print ("********** 设备重启失败 **********") return 0 #回退后/升级后,检查system包版本是否正确 def request_system_version(conn): result = conn.exec_command('ubus call upgrade get_status') time.sleep(15) return result def check_system_ver(conn): allow_retry_times = 120 retry_times = 0 while retry_times < allow_retry_times: t = MyThread(func=request_system_version,args=(conn,)) t.setDaemon(True) t.start() t.join(20) print ("********** 结束查询system包版本的进程 **********") try: a = t.get_result() print (a) if (a is None): retry_times = retry_times + 1 continue else: version = a.decode('utf8') print ("version: %s" %version) version_1 = "1.0.427" if (version_1 in version): print ("********** 系统版本为 1.0.427 **********") return 1 else: print ("********** 系统版本不为 1.0.427 **********") return 0 except AttributeError as e: print ("********** 查询system包版本子线程超时 **********") retry_times = retry_times + 1 time.sleep(10) continue #回退后/升级后,检查system包挂载结构:/instaboot分区是否挂载 def request_mount_structure(conn): result = conn.exec_command('df -h |grep instaboot |cut -d "\n" -f 2') time.sleep(15) return result def check_mount_structure(conn): allow_retry_times = 120 retry_times = 0 while retry_times < allow_retry_times: t = MyThread(func=request_mount_structure,args=(conn,)) t.setDaemon(True) t.start() t.join(20) print ("********** 结束查询/instaboot分区挂载情况的进程 **********") try: a = t.get_result() print (a) if (a is None): print ("********** /instaboot分区没有挂载 **********") return 0 else: data = a.decode('utf8') print (data) if ("/dev/instaboot" in data and "/instaboot" in data and "/high" not in data): print ("********** /instaboot分区正常挂载 **********") return 1 except AttributeError as e: print ("********** 查询system包版本子线程超时 **********") retry_times = retry_times + 1 time.sleep(10) continue #回退后/升级后,检查系统关键目录 def check_key_catalogues(conn): conn.exec_command('cp -f /media/sda1/change_flags_script/check_key_cata.sh /tmp') conn.exec_command('chmod +x /tmp/check_key_cata.sh') conn.exec_command('sh /tmp/check_key_cata.sh') data = conn.exec_command('cat /tmp/2') data_1 = 'yes\n'.encode() if (data == data_1): print ("********** /instaboot/otc_base目录存在 **********") conn.exec_command('rm -f /tmp/2') return 1 else: print ("********** /instaboot/otc_base目录不存在 **********") conn.exec_command('rm -f /tmp/2') return 0 def check_key_catalogues_1(conn): data = conn.exec_command('cat /tmp/.otc_info/base_part_conf.txt') data = data.decode('utf8') if ("No such file or directory" in data): print ("********** /instaboot/otc_base目录不存在 **********") return 1 else: print ('********** /instaboot/otc_base目录存在 **********') return 0 #回退后/升级后,检查根文件系统的类型 def request_rootfs(conn): result = conn.exec_command('df -h|grep -w "/"|cut -d " " -f 1') time.sleep(15) return result def check_rootfs(conn): allow_retry_times = 120 retry_times = 0 while retry_times < allow_retry_times: t = MyThread(func=request_rootfs,args=(conn,)) t.setDaemon(True) t.start() t.join(20) print ("********** 结束查询根文件系统类型的进程 **********") try: a = t.get_result() print (a) data_1 = 'overlay\n'.encode() if (a == data_1): print ("********** 根文件系统类型为overlay **********") return 1 else: print ("********** 根文件系统类型不为overlay **********") return 0 except AttributeError as e: print ("********** 查询根文件系统类型子线程超时 **********") retry_times = retry_times + 1 time.sleep(10) continue #改变标志位,切换启动分区为/dev/xxx,使得系统版本回退为V1.0.427 def change_flags(conn): conn.exec_command('rm -f /tmp/1') conn.exec_command('cp -f /media/sda1/change_flags_script/change_flags.sh /tmp') conn.exec_command('chmod +x /tmp/change_flags.sh') conn.exec_command('sh /tmp/change_flags.sh') data = conn.exec_command('cat /tmp/1') data_1 = 'yes\n'.encode() if (data == data_1): print ("********** 标志位切换成功 **********") conn.exec_command('rm -f /tmp/1') return 1 else: print ("********** 标志位切换失败 **********") conn.exec_command('rm -f /tmp/1') return 0 #删除/misc/app_master文件 def delete_misc_app_master(conn): conn.exec_command('rm -f /misc/app_master') data = conn.exec_command('ls -la /misc/app_master') data = data.decode('utf8') if ("No such file or directory" in data): print ("********** /misc/app_master文件已经删除 **********") return 1 else: print ('********** /misc/app_master文件未删除 **********') return 0 #删除/misc/base_master文件 def delete_misc_base_master(conn): conn.exec_command('rm -f /misc/base_master') data = conn.exec_command('ls -la /misc/base_master') data = data.decode('utf8') if ("No such file or directory" in data): print ("********** /misc/base_master文件已经删除 **********") return 1 else: print ('********** /misc/base_master文件未删除 **********') return 0 #设备升级 def upgrade(conn): conn.exec_command ('ubus call upgrade install_local \'{"package":"/media/sda1/onecloud-system_V2.0.1_arm.ipk","force":false}\'') def upgrade_1(conn): b = conn.exec_command ('ubus call upgrade probe_server') conn.exec_command ('ubus call upgrade start') time.sleep(10) conn.close() #检查upgrade版本 def request_upgrade_version(conn): result = conn.exec_command('ubus call upgrade get_status') time.sleep(15) return result def check_upgrade_ver(conn): allow_retry_times = 120 retry_times = 0 while retry_times < allow_retry_times: t = MyThread(func=request_upgrade_version,args=(conn,)) t.setDaemon(True) t.start() t.join(20) print ("********** 结束查询upgrade模块版本的进程 **********") try: a = t.get_result() print (a) version = a.decode('utf8') version_1 = "1.2.3" if (version_1 in version): print ("********** upgrade版本为 1.2.3 **********") return 1 else: print ("********** upgrade版本不为 1.2.3 **********") return 0 except AttributeError as e: print ("********** 查询upgrade模块版本子线程超时 **********") retry_times = retry_times + 1 time.sleep(10) continue #检查SSH是否连接成功 def check_ssh_connect(ip,username,password): conn = SSHConnection(ip,22,username,password) result = SSHConnection._connect(conn) return result #检查profile文件大小 def request_profie_size(conn): result = conn.exec_command('ls -la /etc/profile|cut -d " " -f 21') time.sleep(15) return result def check_profile_size(conn): allow_retry_times = 120 retry_times = 0 while retry_times < allow_retry_times: t = MyThread(func=request_profie_size,args=(conn,)) t.setDaemon(True) t.start() t.join(20) print ("********** 结束查询profile文件大小的进程 **********") try: a = t.get_result() print (a) size = a.decode('utf8') size = int(size) if (size >= 1536 and size <= 2600): print ("********** profile文件大小正常 **********") return 1 else: print ("********** profile文件大小异常 **********") return 0 except AttributeError as e: print ("********** 查询profile文件大小子线程超时 **********") retry_times = retry_times + 1 time.sleep(10) continue #检查/etc/passwd、/etc/shadow、/etc/group文件 def request_etc_file_content_1(conn): result = conn.exec_command('cat /etc/passwd|grep "root"') time.sleep(15) return result def check_etc_file_content_1(conn): allow_retry_times = 120 retry_times = 0 while retry_times < allow_retry_times: t = MyThread(func=request_etc_file_content_1,args=(conn,)) t.setDaemon(True) t.start() t.join(20) print ("********** 结束查询/etc/passwd的进程 **********") try: a = t.get_result() print (a) if (a is None): print ("********** 系统配置文件检查错误 **********") return 0 else: print ("********** 系统配置文件检查成功 **********") return 1 except AttributeError as e: print ("********** 查询查询/etc/passwd子进程超时 **********") retry_times = retry_times + 1 time.sleep(10) continue def request_etc_file_content_2(conn): result = conn.exec_command('cat /etc/shadow|grep "root"') time.sleep(15) return result def check_etc_file_content_2(conn): allow_retry_times = 120 retry_times = 0 while retry_times < allow_retry_times: t = MyThread(func=request_etc_file_content_2,args=(conn,)) t.setDaemon(True) t.start() t.join(20) print ("********** 结束查询/etc/shadow的进程 **********") try: a = t.get_result() print (a) if (a is None): print ("********** 系统配置文件检查错误 **********") return 0 else: print ("********** 系统配置文件检查成功 **********") return 1 except AttributeError as e: print ("********** 查询查询/etc/shadow子进程超时 **********") retry_times = retry_times + 1 time.sleep(10) continue def request_etc_file_content_3(conn): result = conn.exec_command('cat /etc/group|grep "root"') time.sleep(15) return result def check_etc_file_content_3(conn): allow_retry_times = 120 retry_times = 0 while retry_times < allow_retry_times: t = MyThread(func=request_etc_file_content_3,args=(conn,)) t.setDaemon(True) t.start() t.join(20) print ("********** 结束查询/etc/group的进程 **********") try: a = t.get_result() print (a) if (a is None): print ("********** 系统配置文件检查错误 **********") return 0 else: print ("********** 系统配置文件检查成功 **********") return 1 except AttributeError as e: print ("********** 查询查询/etc/group子进程超时 **********") retry_times = retry_times + 1 time.sleep(10) continue #重定向upgrade日志的输出 def change_upgrade_log_stdout(conn): conn.exec_command("sed -ie 's#/var/log/upgrade.log#/dev/ttyS0'#g /usr/share/onecloud-upgrade/upgrade_log.conf") time.sleep(1) conn.exec_command('cat /usr/share/onecloud-upgrade/upgrade_log.conf') #检查标志文件 def check_flag_file(conn): data = conn.exec_command('ls -la /test_flags') data = data.decode('utf8') if ("No such file or directory" in data): print ("********** 标志文件删除**********") return 1 else: print ("********** 标志文件存在 **********") return 0 if __name__ == "__main__": check_times = input("请输入测试次数:") check_times = int(check_times) test_times = 1 ip = input("请输入测试设备的IP地址:") username = input("请输入测试设备的用户名:") password = input ("请输入测试设备的密码:") while test_times <= check_times: conn = SSHConnection(ip,22,username,password) time.sleep (5) data = conn.exec_command('ubus call upgrade get_status') data = data.decode('utf8') str_1 = "upgrade_local_version" if (str_1 in data): print ("********** SSH连接建立成功 **********") else: print ("********** SSH连接建立失败,重新尝试建立连接 **********") allow_retry_times = 360 retry_times = 0 while retry_times < allow_retry_times: conn = SSHConnection(ip,22,username,password) data = conn.exec_command('ubus call upgrade get_status') data = data.decode('utf8') str_1 = "upgrade_local_version" if (str_1 in data): print ("********** SSH连接建立成功 **********") break else: retry_times = retry_times + 1 time.sleep(10) if (retry_times == allow_retry_times): print ("********** 无法成功建立SSH连接 **********") continue #修改启动分区 if (change_flags(conn) == 1): t = threading.Thread(target=reboot,args=(conn,)) t.setDaemon(True) t.start() t.join(200) time.sleep(100) print("********** 结束等待重启的进程 **********") else: print ("********** 无法回退系统版本至V1.0.427,重新尝试修改标志位 **********") continue #检查系统是否成功回退至V1.0.427版本 allow_retry_times = 60 retry_times = 0 while retry_times < allow_retry_times: if (check_ssh_connect(ip,username,password) == 1): print ("********** 设备重启完成 *********") conn.close() break else: retry_times = retry_times + 1 time.sleep(10) if(retry_times == allow_retry_times): print ("********** 系统重启后,SSH连接建立超时 **********" ) conn.close() continue else: conn = SSHConnection(ip,22,username,password) time.sleep(5) if (check_system_ver(conn) == 1): if (check_upgrade_ver(conn) == 1): if (check_mount_structure(conn) == 0): if (check_key_catalogues_1(conn) == 1): if (check_rootfs(conn) == 0): if (check_etc_file_content_1(conn) == 1 and check_etc_file_content_2(conn) == 1 and check_etc_file_content_3(conn) == 1): if (check_profile_size(conn) == 1): if (check_flag_file(conn) == 0): print ("********** No.%d:系统版本成功回退至V1.0.427 **********" %test_times) print ("********** 使用过渡版本upgrade升级整包 **********") print ("********** 开始第%d次升级 **********" %test_times) change_upgrade_log_stdout(conn) #conn.exec_command ('cp -f /media/sda1/2.0.1/onecloud-system_V2.0.1_arm.ipk /media/sda1') #time.sleep(5) t = threading.Thread(target=upgrade_1,args=(conn,)) t.setDaemon(True) t.start() t.join(100) time.sleep(500) print("********** 结束等待升级的进程 **********") allow_retry_times = 60 retry_times = 0 while retry_times < allow_retry_times: if (check_ssh_connect(ip,username,password) == 1): print ("********** 设备重启完成 *********") conn.close() break else: retry_times = retry_times + 1 time.sleep(10) if(retry_times == allow_retry_times): print ("********** upgrade过渡版本整包升级测试,第%d次测试失败。 **********" %test_times) print ("********** 系统重启后,SSH连接建立超时 **********" ) test_times = test_times + 1 continue else: print ("********** No.%d:系统版本回滚失败 **********" %test_times) print ("********** 标志文件检查错误 **********") conn.exec_command('rm -f /test_flags') with open('D:/upgrade_1.2.3/427_应该存在标志文件.txt', 'a') as f: f.write('第%d次测试失败\n' %test_times) conn.close() test_times = test_times + 1 continue else: print ("********** No.%d:系统版本回滚失败 **********" %test_times) print ("********** profile文件检查错误 **********") with open('D:/upgrade_1.2.3/427_profile文件大小异常.txt', 'a') as f: f.write('第%d次测试失败\n' %test_times) conn.close() test_times = test_times + 1 continue else: print ("********** No.%d:系统版本回滚失败 **********" %test_times) print ("********** /etc目录下文件检查错误 **********") with open('D:/upgrade_1.2.3/427_系统配置文件不正确.txt', 'a') as f: f.write('第%d次测试失败\n' %test_times) conn.close() test_times = test_times + 1 continue else: print ("********** No.%d:系统版本回滚失败 **********" %test_times) print ("********** 根文件系统类型检查错误 **********") with open('D:/upgrade_1.2.3/427_根文件系统类型为overlay.txt', 'a') as f: f.write('第%d次测试失败\n' %test_times) conn.close() test_times = test_times + 1 continue else: print ("********** No.%d:系统版本回滚失败 **********" %test_times) print ("********** 系统关键目录检查错误 **********") with open('D:/upgrade_1.2.3/427_instaboot_otc_base目录存在.txt', 'a') as f: f.write('第%d次测试失败\n' %test_times) retry_times = retry_times + 1 conn.close() test_times = test_times + 1 continue else: print ("********** No.%d:系统版本回滚失败 **********" %test_times) print ("********** system包挂载结构检查错误 **********") with open('D:/upgrade_1.2.3/427_instaboot分区挂载.txt', 'a') as f: f.write('第%d次测试失败\n' %test_times) conn.close() test_times = test_times + 1 continue else: print ("********** No.%d:系统版本回滚失败 **********" %test_times) print ("********** upgrade版本检查错误,不为ver_1.2.3 **********") with open('D:/upgrade_1.2.3/427_upgrade版本错误.txt', 'a') as f: f.write('第%d次测试失败\n' %test_times) conn.close() test_times = test_times + 1 continue else: print ("********** No.%d:系统版本回滚失败 **********" %test_times) print ("********** 系统版本检查错误,不为ver_1.0.427 **********") with open('D:/upgrade_1.2.3/427_系统版本错误.txt', 'a') as f: f.write('第%d次测试失败\n' %test_times) test_times = test_times + 1 conn.close() continue #检查升级成功与否 conn = SSHConnection(ip,22,username,password) time.sleep(5) if (check_system_ver(conn) == 0): if (check_upgrade_ver(conn) == 0): if (check_mount_structure(conn) == 1): if (check_key_catalogues(conn) == 1): if (check_rootfs(conn) == 1): if (check_etc_file_content_1(conn) == 1 and check_etc_file_content_2(conn) == 1 and check_etc_file_content_3(conn) == 1): if (check_profile_size(conn) == 1): if (check_flag_file(conn) == 1): print ("********** No.%d:过渡版本upgrade升级整包测试成功 **********" %test_times) with open('D:/upgrade_1.2.3/过渡版本upgrade升级整包测试成功.txt', 'a') as f: f.write('第%d次测试成功\n' %test_times) conn.exec_command('touch /test_flags') test_times = test_times + 1 time.sleep(2) conn.close() continue else: print ("********** No.%d:过渡版本upgrade升级整包测试失败 **********" %test_times) print ("********** 标志文件检查错误 **********") with open('D:/upgrade_1.2.3/标志文件不应该存在.txt', 'a') as f: f.write('第%d次测试失败\n' %test_times) conn.close() test_times = tset_times + 1 continue else: print ("********** No.%d:过渡版本upgrade升级整包测试失败 **********" %test_times) print ("********** profile文件检查错误 **********") with open('D:/upgrade_1.2.3/profile文件大小异常.txt', 'a') as f: f.write('第%d次测试失败\n' %test_times) conn.close() test_times = test_times + 1 continue else: print ("********** No.%d:过渡版本upgrade升级整包测试失败 **********" %test_times) print ("********** /etc目录下文件检查错误 **********") with open('D:/upgrade_1.2.3/系统配置文件不正确.txt', 'a') as f: f.write('第%d次测试失败\n' %test_times) conn.close() test_times = test_times + 1 continue else: print ("********** No.%d:过渡版本upgrade升级整包测试失败 **********" %test_times) print ("********** 根文件系统类型不为overlay **********") with open('D:/upgrade_1.2.3/根文件系统类型不为overlay.txt', 'a') as f: f.write('第%d次测试失败\n' %test_times) conn.close() test_times = test_times + 1 continue else: print ("********** No.%d:过渡版本upgrade升级整包测试失败 **********" %test_times) print ("********** /instaboot/otc_base不存在 **********") with open('D:/upgrade_1.2.3/instaboot_otc_base目录不存在.txt', 'a') as f: f.write('第%d次测试失败\n' %test_times) conn.close() test_times = test_times + 1 continue else: print ("********** No.%d:过渡版本upgrade升级整包测试失败 **********" %test_times) print ("********** /instaboot分区没有挂载 **********") with open('D:/upgrade_1.2.3/instaboot分区没有挂载.txt', 'a') as f: f.write('第%d次测试失败\n' %test_times) conn.close() test_times = test_times + 1 continue else: print ("********** No.%d:过渡版本upgrade升级整包测试失败 **********" %test_times) print ("********** upgrade版本检查错误 **********") with open('D:/upgrade_1.2.3/upgrade版本错误.txt', 'a') as f: f.write('第%d次测试失败\n' %test_times) conn.close() test_times = test_times + 1 continue else: print ("********** No.%d:过渡版本upgrade升级整包测试成功 **********" %test_times) print ("********** 系统版本检查错误 **********") with open('D:/upgrade_1.2.3/系统版本错误.txt', 'a') as f: f.write('第%d次测试失败\n' %test_times) conn.close() test_times = test_times + 1 continue print ("********** upgrade过渡版本整包升级测试完成。**********") #msg = build_text_msg("过渡版本upgrade:整包在线升级长跑测试完成") #send_result = send_msg(msg) #r = json.loads(send_result) #if r["errcode"] == 0: # print ("send msg Succ") #else: # print ("send msg Failed")<file_sep>/reboot_ver2.py #encoding:utf-8 import paramiko import time import threading class SSHConnection(object): #初始化 def __init__(self, host, port, username, password): self._host = host self._port = port self._username = username self._password = <PASSWORD> self._transport = None self._client = None #self._sftp = None self._connect() #连接、建立ssh通道 def _connect(self): transport = paramiko.Transport(self._host,self._port) transport.connect(username=self._username,password=self._password) self._transport = transport #执行命令 def exec_command(self,command): if self._client is None: self._client = paramiko.SSHClient() self._client._transport = self._transport stdin, stdout, stderr = self._client.exec_command(command) data = stdout.read() if len(data) > 0: print (data.strip()) #打印正确结果 return data err = stderr.read() if len(err) > 0: print (err.strip()) #输出错误结果 return err #上传 def upload(self,localpath,remotepath): if self._sftp is None: self._sftp = paramiko.SFTPClient.from_transport(self._transport) self._sftp.put(localpath,remotepath) #下载 def download(self,remotepath,localpath): if self._sftp is None: self._sftp = paramiko.SFTPClient.from_transport(self._transport) self._sftp.get(remotepath,localpath) #关闭ssh通道 def close(self): if self._transport: self._transport.close() if self._client: self._client.close() #重启设备 def reboot(conn): conn.exec_command('ubus call mnt reboot') time.sleep (10) conn.close() #检查重启 def check_reboot(conn): data = conn.exec_command('ls -la /tmp/test_flag') data = data.decode('utf8') if ("No such file or directory" in data): print ("********** 设备升级重启成功 **********") return 1 else: print ("********** 设备升级重启失败 **********") return 0 def check_ssh_connect(ip,username,password): conn = SSHConnection(ip,22,username,password) result = SSHConnection._connect(conn) return result if __name__ == "__main__": check_times = input("请输入要测试的次数:") check_times = int(check_times) ip = input("请输入测试设备的IP地址:") username = input("请输入测试设备的用户名:") password = input("请输入测试设备的密码:") test_times = 1 while test_times <= check_times: conn = SSHConnection(ip,22,username,password) print ("********** 第%d次重启测试开始 **********" %test_times) conn.exec_command('rm -f /tmp/test_flag') conn.exec_command('touch /tmp/test_flag') t = threading.Thread(target=reboot,args=(conn,)) t.setDaemon(True) t.start() t.join(100) time.sleep(100) print("********** 结束等待重启的进程 **********") conn = SSHConnection(ip,22,username,password) time.sleep (5) data = conn.exec_command('ubus call upgrade get_status') data = data.decode('utf8') str_1 = "upgrade_local_version" if (str_1 in data): print ("********** SSH连接建立成功 **********") else: print ("********** SSH连接建立失败,重新尝试建立连接 **********") allow_retry_times = 100 retry_times = 0 while retry_times < allow_retry_times: conn = SSHConnection(ip,22,username,password) data = conn.exec_command('ubus call upgrade get_status') data = data.decode('utf8') str_1 = "upgrade_local_version" if (str_1 in data): print ("********** SSH连接建立成功 **********") break else: retry_times = retry_times + 1 time.sleep(10) if (retry_times == allow_retry_times): print ("********** 重启测试,第%d次失败。 **********" %test_times) print ("********** 系统重启后,SSH连接建立超时 **********" ) test_times = test_times + 1 continue if (check_reboot(conn) == 1): print ("********** 第%d次重启测试结束,重启成功 **********" %test_times) test_times = test_times + 1 time.sleep(60) else: print ("********** 第%d次重启测试结束,重启失败 **********" %test_times) test_times = test_times + 1 time.sleep(60)
f94a2c5dc1cded28ac8b11fac5d831afcbf2cdad
[ "Python" ]
2
Python
yangyuanying/TestScript
947461cb04ca2f107e67ed3b9fd7ef5e61c8ca2f
3a35edb1f041d62d7b87180bc73ff40eb18d00e2
refs/heads/master
<repo_name>anousonefs/arduino-basic<file_sep>/Arduino/Robot_Auto/Robot_Auto.ino //CEIT_Robot_2018 In Loas int count_sensor = 0;// Count Line int last_state_sensor = 0; //Check State before Count Line //set PIN data of line direction sensor #define SENSOR_T1 22 #define SENSOR_T2 23 #define SENSOR_T3 24 #define SENSOR_T4 25 #define SENSOR_T5 26 #define SENSOR_T6 6 #define SENSOR_T7 7 //save to read the reperent from line sensor int data_sensor_1 = 0; int data_sensor_2 = 0; int data_sensor_3 = 0; int data_sensor_4 = 0; int data_sensor_5 = 0; int data_sensor_6 = 0; int data_sensor_7 = 0; // set PIN motor and power rolling #define DIR1 12 #define DIR2 10 #define PWM1 11 #define PWM2 9 // in line speed int pwm_l = 90; int pwm_r = 90; // turn in line speed int pwmTurn_l = 45; int pwmTurn_r = 45; // uturn zone speed int pwmUturn_l = 60; int pwmUturn_r = 60; // states of the robot #define START 0 #define WAIT 1 #define GO 2 #define DROP_IN 3 #define DROP_OUT 4 #define BACK 5 // colors #define GREEN 1 #define RED 0 #define BLUE 2 // initial state int state = GO; // initla box color int color = GREEN; // initial count for checkpoint count int count = 0; // IR Box detect #define BOX_IR 27 // slider #define PWM_SLDR 4 #define SLDR 5 // Switch #define SLDR_SW_TOP 52 #define SLDR_SW_BTM 51 // Color Sensor #define COLOR_S0 47 #define COLOR_S1 48 #define COLOR_S2 49 #define COLOR_S3 50 #define COLOR_SENSOR 53 void setup() { Serial.begin(9600); //line direction sensor pinMode(SENSOR_T1, INPUT); pinMode(SENSOR_T2, INPUT); pinMode(SENSOR_T3, INPUT); pinMode(SENSOR_T4, INPUT); pinMode(SENSOR_T5, INPUT); pinMode(SENSOR_T6, INPUT); pinMode(SENSOR_T7, INPUT); //motor and power rolling pinMode(DIR1, OUTPUT); pinMode(DIR2, OUTPUT); pinMode(PWM1, OUTPUT); pinMode(PWM2, OUTPUT); // Slider pinMode(PWM_SLDR, OUTPUT); pinMode(SLDR, OUTPUT); // Switches pinMode(SLDR_SW_TOP, INPUT); pinMode(SLDR_SW_BTM, INPUT); // Color Sensors pinMode(COLOR_S0, OUTPUT); pinMode(COLOR_S1, OUTPUT); pinMode(COLOR_S2, OUTPUT); pinMode(COLOR_S3, OUTPUT); pinMode(COLOR_SENSOR, INPUT); // Setting Color Sensor frequency scaling to 20% digitalWrite(COLOR_S0,HIGH); digitalWrite(COLOR_S1,LOW); } //Ending setup fucntion void loop() { Serial.print("state = "); Serial.println(state); switch(state) { case START: controlFollowLine(); //FollowLine if (detectCheckpoint()) { forward(0, 0); delay(1000); state = WAIT; } break; case WAIT: // replace with wait for infared sonsor // while (!hasBox()) { // forward(0, 0); // delay(100); // } do { delay(100); } while (digitalRead(BOX_IR)); forward(pwm_l, pwm_r); delay(300); state = GO; // color = getBoxColor(); // if (color != -1) { // state = GO; // } else { // color = getBoxColor(); // } break; case GO: controlFollowLine(); //FollowLine if (detectCheckpoint()) { delay(100); ++count; } // count == counts to go for color if (count == goCheckpointCount(GREEN)) { // delay(250); count = 0; state = DROP_IN; } break; case DROP_IN: forward(0, 0); // Drop the box(es) while (digitalRead(SLDR_SW_TOP)) { analogWrite(PWM_SLDR, 120); digitalWrite(SLDR, HIGH); delay(100); } analogWrite(PWM_SLDR, 0); state = DROP_OUT; break; case DROP_OUT: while (digitalRead(SLDR_SW_BTM)) { analogWrite(PWM_SLDR, 120); digitalWrite(SLDR, LOW); delay(100); controlFollowLine(); } analogWrite(PWM_SLDR, 0); // // forward(pwm_l, pwm_r); // delay(300); state = BACK; break; case BACK: controlFollowLine(); //FollowLine if (detectCheckpoint()) { delay(100); ++count; } if (count == backCheckpointCount(color)) { state = WAIT; color = changeToNextColor(color); count = 0; } break; } } //End_Loop //control_Sensor void control_Sensor() { //Line Sensor data_sensor_1 = digitalRead(SENSOR_T1); // PIN 22 data_sensor_2 = digitalRead(SENSOR_T2); // PIN 23 data_sensor_3 = digitalRead(SENSOR_T3); // PIN 24 data_sensor_4 = digitalRead(SENSOR_T4); // PIN 25 data_sensor_5 = digitalRead(SENSOR_T5); // PIN 26 data_sensor_6 = digitalRead(SENSOR_T6); // PIN 6 data_sensor_7 = digitalRead(SENSOR_T7); // PIN 7 } // TODO: SENSOR_T3 is not working must change the new once void controlFollowLine() { control_Sensor(); // always moving if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { forward(pwm_l, pwm_r); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 1) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 1) && (data_sensor_7 == 0)) { forward(pwm_l, pwm_r); } else if ((!data_sensor_6 == 1) && (data_sensor_1 == 0) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 0) && (data_sensor_7 == 1)) { forward(pwm_l, pwm_r); } else if ((!data_sensor_6 == 1) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 0) && (data_sensor_7 == 1)) { forward(pwm_l, pwm_r); } else if ((!data_sensor_6 == 1) && (data_sensor_1 == 0) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 1)) { forward(pwm_l, pwm_r); } else if ((!data_sensor_6 == 1) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 1) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 1)) { forward(pwm_l, pwm_r); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 0) && (data_sensor_7 == 1)) { forward(pwm_l, pwm_r); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 0) && (data_sensor_7 == 1)) { forward(pwm_l, pwm_r); } // turn right in line else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnRightZone(pwmTurn_l, pwmTurn_r); } // turn left in line else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnLeftZone(pwmTurn_l, pwmTurn_r); } // turn right at the uturn zone else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 1) && (data_sensor_7 == 0)) { uturnRightZone(pwmUturn_l - 5, pwmUturn_r - 5); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 1) && (data_sensor_7 == 0)) { uturnRightZone(pwmUturn_l, pwmUturn_r); delay(5); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 0) && (data_sensor_4 == 1)&& (data_sensor_5 == 1) && (data_sensor_7 == 0)) { uturnRightZone(pwmUturn_l, pwmUturn_r); delay(10); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 0) && (data_sensor_4 == 1)&& (data_sensor_5 == 1) && (data_sensor_7 == 1)) { uturnRightZone(pwmUturn_l - 5, pwmUturn_r - 5); delay(20); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 0) && (data_sensor_4 == 0)&& (data_sensor_5 == 1) && (data_sensor_7 == 0)) { uturnRightZone(pwmUturn_l, pwmUturn_r); delay(18); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 0) && (data_sensor_4 == 0)&& (data_sensor_5 == 1) && (data_sensor_7 == 1)) { uturnRightZone(pwmUturn_l + 13, pwmUturn_r + 25); delay(35); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 0) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 1)) { uturnRightZone(pwmUturn_l + 15, pwmUturn_r + 5); delay(40); } //turn left at the uturn zone else if ((!data_sensor_6 == 0) && (data_sensor_1 == 1) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnLeftZone(pwmUturn_l - 5, pwmUturn_r - 5); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 1) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnLeftZone(pwmUturn_l - 5, pwmUturn_r - 5); delay(5); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 1) && (data_sensor_2 == 1) && (data_sensor_3 == 0) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnLeftZone(pwmUturn_l, pwmUturn_r); delay(10); } else if ((!data_sensor_6 == 1) && (data_sensor_1 == 1) && (data_sensor_2 == 1) && (data_sensor_3 == 0) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnLeftZone(pwmUturn_l, pwmUturn_r); delay(20); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 1) && (data_sensor_2 == 0) && (data_sensor_3 == 0) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnLeftZone(pwmUturn_l, pwmUturn_r); delay(18); } else if ((!data_sensor_6 == 1) && (data_sensor_1 == 1) && (data_sensor_2 == 0) && (data_sensor_3 == 0) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnLeftZone(pwmUturn_l + 25, pwmUturn_r + 13); delay(35); } else if ((!data_sensor_6 == 1) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 0) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnLeftZone(pwmUturn_l + 5, pwmUturn_r + 15); delay(40); } else { forward(0, 0); } //delay(100); } //end control follow line void forward(int pwm_l, int pwm_r) { //left motor digitalWrite(DIRL1, LOW); digitalWrite(DIRL2, HIGH); analogWrite(PWML, pwm_l); //right motor digitalWrite(DIRR1, LOW); digitalWrite(DIRR2, HIGH); analogWrite(PWMR, pwm_r); } // End forward void backward(int pwm_l, int pwm_r) { //left motor digitalWrite(DIRL1, HIGH); digitalWrite(DIRL2, LOW); analogWrite(PWML, pwm_l); //right motor digitalWrite(DIRR1, HIGH); digitalWrite(DIRR2, LOW); analogWrite(PWMR, pwm_r); } // end backward void uturnLeftZone (int pwm_l, int pwm_r) { //left motor digitalWrite(DIRL1, HIGH); digitalWrite(DIRL2, LOW); analogWrite(PWML, pwm_l); //right motor digitalWrite(DIRR1, LOW); digitalWrite(DIRR2, HIGH); analogWrite(PWMR, pwm_r); } void uturnRightZone (int pwm_l, int pwm_r) { //left motor digitalWrite(DIRL1, LOW); digitalWrite(DIRL2, HIGH); analogWrite(PWML, pwm_l); //right motor digitalWrite(DIRR1, HIGH); digitalWrite(DIRR2, LOW); analogWrite(PWMR, pwm_r); } <file_sep>/Arduino/i2cslave/i2cslave.ino #include<Wire.h> #define SLAVE_ADDR 8 #define ANSWERSIZE 20 String answer = "<PASSWORD>"; #include "DHT.h" #define DHTPIN 2 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); String temp; void setup() { temp = Dht22(); // put your setup code here, to run once: Wire.begin(SLAVE_ADDR); // Function to run when data requested from master Wire.onRequest(requestEvent); // Function to run when data receive from master Wire.onReceive(receiveEvent); Serial.begin(9600); Serial.println("I2C Slave demonstration"); dht.begin(); } void receiveEvent(){ // Read while data receive while(0 < Wire.available()){ byte x = Wire.read(); } Serial.println("receive Event"); } void requestEvent(){ // Setup byte Variable in the correct size byte response[ANSWERSIZE]; // Format answer as array for(byte i = 0; i < ANSWERSIZE; i++){ response[i] = (byte)answer.charAt(i); } // Send response back to master Wire.write(response, sizeof(response)); Serial.println("request Event"); } float Dht22(){ // Wait a few seconds between measurements. delay(2000); // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) float h = dht.readHumidity(); // Read temperature as Celsius (the default) float t = dht.readTemperature(); // Read temperature as Fahrenheit (isFahrenheit = true) float f = dht.readTemperature(true); // Check if any reads failed and exit early (to try again). if (isnan(h) || isnan(t) || isnan(f)) { Serial.println(F("Failed to read from DHT sensor!")); return; } // Compute heat index in Fahrenheit (the default) float hif = dht.computeHeatIndex(f, h); // Compute heat index in Celsius (isFahreheit = false) float hic = dht.computeHeatIndex(t, h, false); // Serial.print(F("Humidity: ")); // Serial.print(h); // Serial.print(F("% Temperature: ")); // Serial.print(t); // Serial.print(F("°C ")); // Serial.print(f); // Serial.print(F("°F Heat index: ")); // Serial.print(hic); // Serial.print(F("°C ")); // Serial.print(hif); // Serial.println(F("°F")); return t; } void loop() { // put your main code here, to run repeatedly: delay(50); temp = Dht22(); // Serial.print("temp = "); // Serial.println(temp); } <file_sep>/Arduino/press_on_off/press_on_off.ino #define led 2 #define button 3 #define led2 4 int StateButton = LOW, StateLed = LOW, previous = LOW; void setup() { // put your setup code here, to run once: pinMode(led, OUTPUT); pinMode(button, INPUT); pinMode(led2, OUTPUT); } void loop() { // put your main code here, to run repeatedly: StateButton = digitalRead(button); delay(100); if (StateButton == HIGH && previous == LOW){ // digitalWrite(led, StateLed); if(StateLed){ do{ digitalWrite(led , HIGH); delay(100); digitalWrite(led, LOW); delay(100); digitalWrite(led2 , HIGH); delay(100); digitalWrite(led2, LOW); StateButton = digitalRead(button); delay(100); previous = StateButton; }while(StateButton != HIGH && previous != HIGH); }else{ digitalWrite(led, LOW); digitalWrite(led2, LOW); } StateLed = !StateLed; } previous = StateButton; } <file_sep>/Arduino/demo_led/demo_led.ino #define button 7 #define led 8 #define led2 9 int State = 0; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(button, INPUT); pinMode(led, OUTPUT); pinMode(led2, OUTPUT); } void loop() { // put your main code here, to run repeatedly: State = digitalRead(button); if(State == HIGH){ Serial.println("---> result is 1"); digitalWrite(led , HIGH); delay(200); digitalWrite(led, LOW); delay(200); digitalWrite(led2 , HIGH); delay(200); digitalWrite(led2, LOW); delay(200); } else{ digitalWrite(led, LOW); digitalWrite(led2, LOW); Serial.println("---> result is 0"); delay(300); } } <file_sep>/Arduino/keypad/keypad.ino //#include <Arduino.h> #include <Keypad.h> #include <Wire.h> #include <LiquidCrystal_I2C.h> // Set the LCD address to 0x27 for a 16 chars and 2 line display LiquidCrystal_I2C lcd(0x27, 16, 2); String num = "0"; const byte ROWS = 4; const byte COLS = 4; int led = 10; char hexaKeys[ROWS][COLS] = { {'1', '2', '3', 'A'}, {'4', '5', '6', 'B'}, {'7', '8', '9', 'C'}, {'*', '0', '#', 'D'} }; byte rowPins[ROWS] = {5,4,3,2}; byte colPins[COLS] = {9,8,7,6}; Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS); void setup(){ Serial.begin(9600); pinMode(led, OUTPUT); lcd.begin(); lcd.backlight(); } void loop(){ char customKey = customKeypad.getKey(); lcd.clear(); lcd.print("number: "); lcd.setCursor (7,0); lcd.print(num); if (customKey){ num += customKey; Serial.println(customKey); tone(led, 1000); // Send 1KHz sound signal... delay(80); // ...for 1 sec noTone(led); // Stop sound... } delay(100); } <file_sep>/Arduino/libraries/firebase-arduino-master/library.properties name=firebase-arduino version=0.4 author= maintainer= sentence=Fill in later paragraph=Fill in later category=Communication url=http://example.com/ architectures=esp8266 <file_sep>/Arduino/sdcard2/sdcard2.ino #include <SD.h> File myFile; // สร้างออฟเจค File สำหรับจัดการข้อมูล String fileName = "text.txt"; const int chipSelect = 4; int n = 1; void setup(){ connect2sdcard(); write2file(fileName); // readfile(fileName); } void connect2sdcard(){ Serial.begin(9600); while (!Serial) { ; // รอจนกระทั่งเชื่อมต่อกับ Serial port แล้ว (สำหรับ Arduino Leonardo เท่านั้น) } Serial.print("Initializing SD card..."); pinMode(SS, OUTPUT); // Slave select ตัว library มันจะขอให้เป็น OUTPUT เสมอ if (!SD.begin(chipSelect)) { Serial.println("initialization failed!"); return; } Serial.println("initialization done."); SD.remove(fileName); //ถ้าต้องการลบไฟล์ทิ้ง } void readfile(String filename){ // เปิดไฟล์เพื่ออ่าน ================================== myFile = SD.open(filename); // สั่งให้เปิดไฟล์ชื่อ cmlog.txt เพื่ออ่านข้อมูล if (myFile) { Serial.println(filename + ":"); // อ่านข้อมูลทั้งหมดออกมา while (myFile.available()) { Serial.write(myFile.read()); } myFile.close(); // เมื่ออ่านเสร็จ ปิดไฟล์ } else { // ถ้าอ่านไม่สำเร็จ ให้แสดง error Serial.println("error opening " + filename); } } void write2file(String filename){ // เปิดไฟล์ที่ชื่อ fileName เพื่อเขียนข้อมูล โหมด FILE_WRITE =========================== myFile = SD.open(filename, FILE_WRITE); // ถ้าเปิดไฟล์สำเร็จ ให้เขียนข้อมูลเพิ่มลงไป if (myFile) { Serial.print("Writing to " + filename + "..."); myFile.println("bung soud"); for(int j = 2 ; j <= 10 ; j++ ){ for(int i = 1 ; i <= 12 ; i++){ // myFile.println(j, "x" ,i," = ",j*i); // สั่งให้เขียนข้อมูล myFile.print(j); myFile.print(" x "); myFile.print(i); myFile.print(" = "); myFile.println(j*i); } myFile.println("=========="); } myFile.close(); // ปิดไฟล์ Serial.println("done."); } else { // ถ้าเปิดไฟลืไม่สำเร็จ ให้แสดง error Serial.println("error opening "+filename); } } void loop(){ if(n <= 3){ readfile(fileName); n ++; Serial.println("read again"); if(n == 3){ myFile = SD.open(fileName, FILE_WRITE); myFile.println("This is data in SDCard"); myFile.close(); } } } <file_sep>/Arduino/TEST_BUTTON/TEST_BUTTON.ino #define button 7 int State = LOW; void setup() { // put your setup code here, to run once: pinMode(button, INPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: State = digitalRead(button); Serial.println(State); delay(200); } <file_sep>/Arduino/i2cultra_slave/i2cultra_slave.ino #include <NewPing.h> #include <Wire.h> // define slave i2c address #define SLAVE_ADDR 9 // sensor 0 #define TRIGGER_PIN_0 8 #define ECHO_PIN_0 8 // sensor 1 #define TRIGGER_PIN_1 9 #define ECHO_PIN_1 9 // Maximum Distance is 260 cm #define MAX_DISTANCE 260 // create objects for ultrasonic sensors NewPing sensor0(TRIGGER_PIN_0, ECHO_PIN_0, MAX_DISTANCE); NewPing sensor1(TRIGGER_PIN_1, ECHO_PIN_1, MAX_DISTANCE); // variables to represent distances float distance0, distance1; // define return data array, one element per sensor int distance[2]; // define counter to count bytes in response int bcount = 0; void setup() { // initiallize i2c communications as slave Wire.begin(SLAVE_ADDR); // Function to run when data requested from master Wire.onRequest(requestEvent); // Serial monitor for testing Serial.begin(9600); } void requestEvent(){ // define a byte to hold data byte bval; // Cycle through data // First reponse is always 255 to mark beginning switch(bcount){ case 0: bval = 255; break; case 1: bval = distance[0]; break; case 2: bval = distance[1]; break; } // Send.response back to Master Wire.write(bval); // Increment byte counter bcount = bcount + 1; if (bcount > 2) bcount = 0; } void readDistance(){ distance[0] = sensor0.ping_cm(); if(distance[0] > 254){ distance[0] = 254; } delay(20); distance[1] = sensor1.ping_cm(); if(distance[1] > 254){ distance[1] = 254; } delay(20); } void loop() { // Refresh readings every half second readDistance(); delay(500); } <file_sep>/Arduino/string3/string3.ino void setup() { // put your setup code here, to run once: Serial.begin(9600); //String stringOne = "Hello String"; // using a constant String //String stringOne = String('a'); // converting a constant char into a String //String stringTwo = String("This is a string"); // converting a constant string into a String object //String stringOne = String(stringTwo + " with more"); // concatenating two strings //String stringOne = String(13); // using a constant integer //String stringOne = String(analogRead(0), DEC); // using an int and a base //String stringOne = String(45, HEX); // using an int and a base (hexadecimal) //String stringOne = String(255, BIN); // using an int and a base (binary) //String stringOne = String(millis(), DEC); // using a long and a base Serial.println(stringOne); } void loop() { // put your main code here, to run repeatedly: } <file_sep>/Arduino/i2cslave_test/i2cslave_test.ino #include<Wire.h> #define SLAVE_ADDR 10 int bcount = 0; byte bval; void setup() { // put your setup code here, to run once: Wire.begin(SLAVE_ADDR); Wire.onRequest(requestEvent); Serial.begin(9600); } void requestEvent(){ bval = 255; Wire.write(bval); bcount++; if (bcount > 5){ bcount = 0; } } void loop() { // put your main code here, to run repeatedly: } <file_sep>/Arduino/fan/fan.ino int fan = 25; void setup() { // put your setup code here, to run once: pinMode(fan, OUTPUT); } void loop() { // put your main code here, to run repeatedly: digitalWrite(fan, HIGH); delay(4000); digitalWrite(fan, LOW); delay(4000); } <file_sep>/Arduino/esp8266wifi2/esp8266wifi2.ino /* Copyright 2018 Electrical Engineering Enterprise Group. * ESP-EP.7_NTP * * <NAME> */ #include <ESP8266WiFi.h> #include <ESP8266WiFiMulti.h> #include <time.h> //WIFI ESP8266WiFiMulti wifiMulti; #define YOUR_SSID "CEIT-IoT" #define YOUR_PASS "<PASSWORD>" // Config time int timezone = 7; // Zone +7 for Thailand char ntp_server1[20] = "ntp.ku.ac.th"; char ntp_server2[20] = "fw.eng.ku.ac.th"; char ntp_server3[20] = "time.uni.net.th"; int dst = 0; int Sec = 0; void setup() { Serial.begin(115200); /*---- Config WiFi ----*/ wifiMulti.addAP("Year2020", "1235th"); wifiMulti.addAP("AndroidAP", "ifmd0883"); wifiMulti.addAP(YOUR_SSID, YOUR_PASS); while (wifiMulti.run() != WL_CONNECTED) { Serial.println("WiFi not connected!"); delay(1000); } Serial.println("WiFi connected!"); delay(500); /*---- Config Time ----*/ configTime(timezone * 3600, dst, ntp_server1, ntp_server2, ntp_server3); while (!time(nullptr)) { Serial.print("."); delay(500); } } void loop() { ChkWiFi(); NowString(); delay(1000); if(Sec > 30){ Serial.print(" OK "); }else{ Serial.print(" NON "); } } void ChkWiFi(){ if (wifiMulti.run() != WL_CONNECTED) { Serial.println("WiFi not connected!"); delay(1000); } } String NowString() { time_t now = time(nullptr); struct tm* newtime = localtime(&now); String tmpNow = ""; tmpNow += String(newtime->tm_year + 1900); tmpNow += "-"; tmpNow += String(newtime->tm_mon + 1); tmpNow += "-"; tmpNow += String(newtime->tm_mday); tmpNow += " "; tmpNow += String(newtime->tm_hour); tmpNow += ":"; tmpNow += String(newtime->tm_min); tmpNow += ":"; tmpNow += String(newtime->tm_sec); Serial.println(tmpNow); Sec = newtime->tm_sec; return tmpNow; } <file_sep>/Arduino/sensor_led_on_off_2/sensor_led_on_off_2.ino #define button_mode 3 #define led_2 4 #define led_3 5 #define sensor 6 #define sensor_2 7 #define button_1 8 #define led_1 9 #define buzzer 10 int previous = LOW; int state; int present = LOW; int present_2 = LOW; int readingmode = LOW; int reading; int k = HIGH, n; int m = 1; int kon = LOW; int X = LOW; int state_1 = LOW; int state_2 = LOW; int add; int breaker = HIGH; int a, out; // ========================================================== void setup() { // put your setup code here, to run once: pinMode(button_1, INPUT); pinMode(sensor, INPUT); pinMode(sensor_2, INPUT); pinMode(led_1, OUTPUT); pinMode(buzzer, OUTPUT); pinMode(led_2, OUTPUT); pinMode(led_3, OUTPUT); pinMode(button_mode, INPUT); Serial.begin(9600); } // ============================================================== void selectMode(){ do{ readingmode = digitalRead(button_mode); // choose Mode: 1 or 2 if(readingmode == HIGH && kon == LOW){ state_1 = !state_1; state_2 = !state_2; m = !m; breaker = !breaker; } kon = readingmode; }while(readingmode == HIGH); } // ============================================================================== void mode1 (){ do{ digitalWrite(led_1, state_1); digitalWrite(led_2, state_2); chooseMode_2(); reading = digitalRead(button_1); if(reading == HIGH && previous == LOW){ state = !state; } digitalWrite(led_3, state); delay(100); previous = reading; }while( m == 0); // if m = 2 stop Mode 1 ; come in Mode 2 digitalWrite(led_3, LOW); // if stop Mode 1 , led_3 off } // ================================================================== void mode2 (){ do{ digitalWrite(led_2 ,state_2); // state Mode digitalWrite(led_1, state_1); do{ chooseMode_1(); // if button_Mode = HIGH : STOP MODE 2; COME IN MODE 1 }while(readingmode == HIGH); state = LOW; present = LOW; do{ n = 6; present = digitalRead(sensor); // sensor out room if( present == HIGH) add = 1; present_2 = digitalRead(sensor_2); if( present_2 == HIGH && add == 1){ if(state == LOW){ state = HIGH; n = 5; add = 0; } } digitalWrite(led_3, state); if( n == 5){ tone(buzzer, 925, 225); delay(1000); } } while (add == 1); out = 0; k = HIGH; n = 0; a = LOW; present = LOW; if ( state = HIGH){ do{ if( a == LOW ){ do { present_2 = digitalRead(sensor_2); // sensor in room delay(200); if(present_2 == HIGH && a == LOW){ do{ chooseMode_1(); // if button_Mode = HIHG, stop mode 2 ; come in mode 1 } while (readingmode == HIGH); } }while( present_2 == HIGH); present_2 = LOW; } a = HIGH; delay(100); do{ chooseMode_1(); // if button_Mode = HIGH, stop mode 2 ; come in mode 1 } while ( readingmode == HIGH); present_2 = digitalRead(sensor_2); // sensor in room if(present_2 == HIGH){ out = 1; } present = digitalRead(sensor); // sensor out room if( present == HIGH && out == 1){ k = LOW; // led_3 off or on } delay(100); n++; if(n == 40){ tone(buzzer, 988, 250); delay(400); do{ chooseMode_1(); }while(readingmode == HIGH); tone(buzzer, 880, 250); delay(400); do{ chooseMode_1(); }while(readingmode == HIGH); tone(buzzer, 784, 1000); delay(1000); do{ chooseMode_1(); }while(readingmode == HIGH); tone(buzzer, 784, 1000); delay(1000); } } while (k == HIGH && n <= 60); } digitalWrite(led_3, LOW); do{ present = digitalRead(sensor); // sensor out room } while (present == HIGH); delay(100); } while (m == 1); // if m = 1 is Mode 2 off digitalWrite( led_3, LOW ); // if stop Mode 2 is led_3 off } // ====================================================== void chooseMode_1(){ readingmode = digitalRead(button_mode); // if readingmode = HIGH; stop Mode2 come in Mode 1 if(readingmode == HIGH && kon == LOW ){ m = 0; k = LOW; state_1 = HIGH; state_2 = LOW; } } // ===================================================== void chooseMode_2(){ do{ readingmode = digitalRead(button_mode); // if readingmode = high; stop mode 1 come in mode 2 if (readingmode = HIGH && kon == LOW){ m = 1; state_1 = LOW; state_2 = HIGH; } }while(readingmode == HIGH); } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void loop() { // put your main code here, to run repeatedly: X = LOW; state = LOW; reading = LOW; selectMode(); // Mode 1 or 2 digitalWrite(led_3, breaker); switch(m){ case 0: // come in mode 1 if m = 1 mode1(); case 1: // come in Mode 2 mode2(); } } <file_sep>/Arduino/libraries/firebase-arduino-master/test/mock-firebase.h #ifndef TEST_MOCK_FIREBASE_H #define TEST_MOCK_FIREBASE_H #include <memory> #include "gtest/gtest.h" #include "Firebase.h" namespace firebase { namespace modem { class MockFirebase : public Firebase { public: MOCK_METHOD1(getPtr, std::unique_ptr<FirebaseGet>(const String&)); MOCK_METHOD2(setPtr, std::unique_ptr<FirebaseSet>(const String&, const String&)); MOCK_METHOD2(pushPtr, std::unique_ptr<FirebasePush>(const String&, const String&)); MOCK_METHOD1(removePtr, std::unique_ptr<FirebaseRemove>(const String&)); MOCK_METHOD1(streamPtr, std::unique_ptr<FirebaseStream>(const String&)); }; class MockFirebaseGet : public FirebaseGet { public: MOCK_CONST_METHOD0(response, const String&()); MOCK_CONST_METHOD0(error, const FirebaseError&()); }; class MockFirebaseSet : public FirebaseSet { public: MOCK_CONST_METHOD0(json, const String&()); MOCK_CONST_METHOD0(error, const FirebaseError&()); }; class MockFirebasePush : public FirebasePush { public: MOCK_CONST_METHOD0(name, const String&()); MOCK_CONST_METHOD0(error, const FirebaseError&()); }; class MockFirebaseRemove : public FirebaseRemove { public: MOCK_CONST_METHOD0(error, const FirebaseError&()); }; class MockFirebaseStream : public FirebaseStream { public: MOCK_METHOD0(available, bool()); MOCK_METHOD1(read, Event(String& event)); MOCK_CONST_METHOD0(error, const FirebaseError&()); }; } // modem } // firebase #endif // TEST_MOCK_FIREBASE_H <file_sep>/Arduino/ESPMelon/ESPMelon.ino //#include <Arduino.h> #include <ESP8266WiFi.h> #include <EEPROM.h> #include <SoftwareSerial.h> #include <MicroGear.h> // connect to netpie // const char *ssid = "iMac"; // const char *password = "<PASSWORD>"; // const char *ssid = "Guest.Conference"; // const char *password = "<PASSWORD>"; const char *ssid = "CEIT ROBOT"; const char *password = "<PASSWORD>"; #define APPID "SMARTMELON" #define KEY "h2qfmSSoDABtXv6" #define SECRET "<KEY>" #define ALIAS "NodeMCU" #define FEEDID "SMARTMELONFEED" #define FREEBOARDID "SMARTMELONFREEBOARD" #define INTERVAL 15000 #define T_INCREMENT 200 #define T_RECONNECT 5000 #define BAUD_RATE 115200 #define MAX_TEMP 100 #define MAX_HUMID 100 //Solenoid digital pin #define SOLENOID D1 WiFiClient client; // Solenoid variable char state = 0; char stateOutdated = 0; char buff[16]; char solenStatus; int timer = 0; char str[64]; MicroGear microgear(client); #define BAUD_RATE 115200 SoftwareSerial swSer(14, 12, false, 256); // 14 = D5(RX) ; 12 = D6(TX) NodeMCU // sending solenoid state void sendState() { if (state == 0) microgear.publish("/solenoid/state", "0"); else microgear.publish("/solenoid/state", "1"); Serial.println("send state.."); stateOutdated = 0; } // update solenoid state void updateIO() { if (state >= 1) { digitalWrite(SOLENOID, HIGH); } else { state = 0; digitalWrite(SOLENOID, LOW); } } // when the other thing send a msg to this board void onMsghandler(char *topic, uint8_t *msg, unsigned int msglen) { solenStatus = *(char *)msg; Serial.print("Incoming message --> "); msg[msglen] = '\0'; Serial.println((char *)msg); if (solenStatus == '0' || solenStatus == '1') { state = solenStatus == '0' ? 0 : 1; updateIO(); } if (solenStatus == '0' || solenStatus == '1' || solenStatus == '?') stateOutdated = 1; } void onConnected(char *attribute, uint8_t *msg, unsigned int msglen) { Serial.println("Connected to NETPIE..."); microgear.setAlias(ALIAS); stateOutdated = 1; } // call function void communi(); void netpieCon(); void debuging(); String MyinputString = ""; char inChar; // in and out humd, temp variable int inHumd = 0; int inTemp = 0; int outHumd = 0; int outTemp = 0; int inLight = 0; int outLight = 0; int mois0 = 0; int mois1 = 0; int mois2 = 0; void setup() { // Open serial communications and wait for port to open: Serial.begin(115200); Serial.println("Smart Melon Farm [NODE]"); Serial.println("Starting..."); swSer.begin(BAUD_RATE); // solenoid pinMode pinMode(SOLENOID, OUTPUT); if (WiFi.begin(ssid, password)) { while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } } Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); // netpie setup microgear.on(MESSAGE, onMsghandler); microgear.on(CONNECTED, onConnected); microgear.init(KEY, SECRET, ALIAS); microgear.connect(APPID); // serial port communications setup while (!swSer) { ; // wait for serial port to connect. Needed for native USB port only } } void loop() { // run over and over // communications with arduino MEGA communi(); // connect to netpie netpieCon(); // print to serial monitor debuging(); } // communications function void communi() { while (swSer.available()) { inChar = (char)swSer.read(); // get the new byte: MyinputString += inChar; // add it to the inputString: //Serial.println(inChar); if (MyinputString[0] == 'H') // check array [0] is H { if (inChar == 0x0D) // check received 'enter' (0x0D) { inHumd = ((MyinputString[1] - 48) * 10) + (MyinputString[2] - 48); // change Char to Integer MyinputString = ""; } } else if (MyinputString[0] == 'T') // check array [0] is T { if (inChar == 0x0D) // check received 'enter' (0x0D) { inTemp = ((MyinputString[1] - 48) * 10) + (MyinputString[2] - 48); MyinputString = ""; } } else if (MyinputString[0] == 'I') // check array [0] is I { if (inChar == 0x0D) // check received 'enter' (0x0D) { outHumd = ((MyinputString[1] - 48) * 10) + (MyinputString[2] - 48); MyinputString = ""; } } else if (MyinputString[0] == 'U') // check array [0] is U { if (inChar == 0x0D) // check received 'enter' (0x0D) { outTemp = ((MyinputString[1] - 48) * 10) + (MyinputString[2] - 48); MyinputString = ""; } } else if (MyinputString[0] == 'L') // check array [0] is L { if (inChar == 0x0D) // check received 'enter' (0x0D) { inLight = ((MyinputString[1] - 48) * 10) + (MyinputString[2] - 48); MyinputString = ""; } } else if (MyinputString[0] == 'M') // check array [0] is M { if (inChar == 0x0D) // check received 'enter' (0x0D) { outLight = ((MyinputString[1] - 48) * 10) + (MyinputString[2] - 48); MyinputString = ""; } } else if (MyinputString[0] == 'N') // check array [0] is N { if (inChar == 0x0D) // check received 'enter' (0x0D) { mois0 = ((MyinputString[1] - 48) * 10) + (MyinputString[2] - 48); MyinputString = ""; } } else if (MyinputString[0] == 'O') // check array [0] is O { if (inChar == 0x0D) // check received 'enter' (0x0D) { mois1 = ((MyinputString[1] - 48) * 10) + (MyinputString[2] - 48); MyinputString = ""; } } else if (MyinputString[0] == 'P') // check array [0] is P { if (inChar == 0x0D) // check received 'enter' (0x0D) { mois2 = ((MyinputString[1] - 48) * 10) + (MyinputString[2] - 48); MyinputString = ""; } } else { MyinputString = ""; } } } // connect to netpie void netpieCon() { if (microgear.connected()) { //Serial.print("Connected"); // solenoid sending state if (stateOutdated) sendState(); microgear.loop(); if (timer >= INTERVAL) { // communications function communi(); // Sending to the Feed String data = "{\"inHumd\":"; data += inHumd; data += ", \"inTemp\":"; data += inTemp; data += ", \"inLight\":"; data += inLight; data += ", \"outHumd\":"; data += outHumd; data += ", \"outTemp\":"; data += outTemp; data += ", \"outLight\":"; data += outLight; data += ", \"mois1\":"; data += mois0; data += ", \"mois2\":"; data += mois1; data += ", \"mois3\":"; data += mois2; data += "}"; //sending data to freeboard String str = (String)inHumd + ", " + (String)inTemp + ", " + (String)inLight + ", " + (String)outHumd + ", " + (String)outTemp + ", " + (String)outLight + ", " + (String)mois0 + ", " + (String)mois1 + ", " + (String)mois2 + ", "; microgear.publish("/sensors", str); //Serial.println(str); if (isnan(inHumd) || isnan(inTemp) || inHumd >= MAX_HUMID || inTemp >= MAX_TEMP) { Serial.println("Failed to read from DHT sensor!"); } else { //Serial.print("Sending -->"); //Serial.println((char *)data.c_str()); microgear.writeFeed(FEEDID, data); //YOUR FEED ID, API KEY } timer = 0; } else timer += T_INCREMENT; } else { Serial.println("connection lost, reconnect..."); if (timer >= T_RECONNECT) { microgear.connect(APPID); timer = 0; } else timer += T_INCREMENT; } delay(200); } // debuging monitor void debuging() { Serial.println("\t\t\tSmart Melon Farm [ESP]"); Serial.println("------------------------------------------------------------------------"); // show in MG module as realtime Serial.print("Inside Humidity: \t"); Serial.print(inHumd); Serial.print(" %\t|\t"); Serial.print("Inside Temperature: \t"); Serial.print(inTemp); Serial.println(" *C \t|"); // Serial.println("------------------------------------------------------------------------"); Serial.print("Outside Humidity: \t"); Serial.print(outHumd); Serial.print(" %\t|\t"); Serial.print("Outside Temperature: \t"); Serial.print(outTemp); Serial.println(" *C \t|"); Serial.println("------------------------------------------------------------------------"); // showing status in monitor Serial.print("Inside Light: \t\t"); Serial.print(inLight); Serial.print(" %\t|\tOutside Light: \t\t"); Serial.print(outLight); Serial.println(" %\t|"); Serial.println("------------------------------------------------------------------------"); // showing each moisture sensors to screen Serial.print("Soil moisture one: \t"); Serial.print(mois0); Serial.print(" %\t|\t"); Serial.print("Soil moisture two: \t"); Serial.print(mois1); Serial.print(" %\t|\t"); Serial.print("Soil moisture three: \t"); Serial.print(mois2); Serial.println(" %\t|\t"); Serial.println("-----------------------------------------------------------------------------------------------------------------"); //showing solenoid state if (solenStatus == '1') { Serial.print("Solenoid: \t\tON"); Serial.print(" \t|\n"); } else { Serial.print("Solenoid: \t\tOFF"); Serial.print(" \t|\n"); } Serial.println("-----------------------------------------------------------------------------------------------------------------\n\n"); //delay(2000); } <file_sep>/Arduino/kidLDR/kidLDR.ino #define LIGHT 36 #define BUTTON1 16 #define BUZZER 13 int light; bool valbtn1; void setup() { // put your setup code here, to run once: pinMode(LIGHT, INPUT); pinMode(BUTTON1, INPUT); pinMode(BUZZER, OUTPUT); Serial.begin(115200); } void loop() { // put your main code here, to run repeatedly: light = analogRead(LIGHT); valbtn1 = digitalRead(BUTTON1); Serial.println("light = " + String(light)); Serial.println("valbtn1 = " + String(valbtn1)); } <file_sep>/Arduino/m2/m2.ino #define s1 A0 #define s2 A1 int StateS1; int StateS2; int S1; int S2; #define DIR1 2 #define PWM1 3 #define DIR2 4 #define PWM2 5 void setup() { Serial.begin(57600); pinMode(s1, INPUT); pinMode(s2, INPUT); pinMode(DIR1, OUTPUT); pinMode(DIR2, OUTPUT); pinMode(PWM1, OUTPUT); pinMode(PWM2, OUTPUT); analogWrite(PWM1, 100); analogWrite(PWM2, 100); } void loop() { FollowLine(); } void FollowLine(){ S1 = analogRead(s1); S2 = analogRead(s2); StateS1 = map(S1, 1, 825, 1, 100); StateS2 = map(S2, 1, 825, 1, 100); if( StateS1 < 10){ StateS1 = 1; }else{ StateS1 = 0; } if( StateS2 < 10){ StateS2 = 1; }else{ StateS2 = 0; } Serial.print("State S1 and S2 = "); Serial.print(StateS1); Serial.print(" , "); Serial.println(StateS2); if(StateS1 == 0 && StateS2 == 1){ TurnLeft(); }else if(StateS1 == 1 && StateS2 == 0){ TurnRight(); }else if(StateS1 == 1 && StateS2 == 1){ ForWard(); }else{ Stop(); } } void ForWard(){ digitalWrite(DIR1, HIGH); digitalWrite(DIR2, HIGH); analogWrite(PWM1, 80); analogWrite(PWM2, 80); } void BackWard(){ digitalWrite(DIR1, LOW); digitalWrite(DIR2, LOW); analogWrite(PWM1, 80); analogWrite(PWM2, 80); } void TurnLeft(){ digitalWrite(DIR1, HIGH); digitalWrite(DIR2, LOW); analogWrite(PWM1, 80); analogWrite(PWM2, 80); } void TurnRight(){ digitalWrite(DIR1, LOW); digitalWrite(DIR2, HIGH); analogWrite(PWM1, 80); analogWrite(PWM2, 80); } void Stop(){ analogWrite(PWM1, 0); analogWrite(PWM2, 0); } <file_sep>/Arduino/test100/test100.ino #define button 7 #define led1 6 #define led2 5 bool StateBTN = 0; bool previous = 0; bool State = 0; void setup() { // put your setup code here, to run once: pinMode(button, INPUT); pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); } void loop() { // put your main code here, to run repeatedly: StateBTN = digitalRead(button); if(StateBTN == 1 && previous == 0){ State = !State; if(State == 1){ digitalWrite(led1, HIGH); digitalWrite(led2, LOW); }else{ digitalWrite(led1, LOW); digitalWrite(led2, HIGH); } } previous = StateBTN; } <file_sep>/Arduino/test_button1/test_button1.ino #define button_mode 3 #define led_2 4 #define led_3 5 #define sensor 6 #define sensor_2 7 #define button_1 8 #define led_1 9 void setup() { // put your setup code here, to run once: pinMode(button_mode, INPUT); pinMode(led_1, OUTPUT); pinMode(led_2, OUTPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: Serial.println(digitalRead(button_mode)); delay(200); } <file_sep>/Arduino/if_else/if_else.ino int a = 9; int b = 7; void setup() { // put your setup code here, to run once: Serial.begin(9600); if(a > b){ Serial.print("max = "); Serial.println(a); }else{ Serial.print("max = "); Serial.println(b); } Serial.println("Bye...."); } void loop() { // put your main code here, to run repeatedly: } <file_sep>/Arduino/lora_sender/lora_sender.ino #include <SPI.h> #include <LoRa.h> //#include “SSD1306.h” #include <Adafruit_SSD1306.h> int counter = 0; // GPIO5 — SX1278’s SCK // GPIO19 — SX1278’s MISO // GPIO27 — SX1278’s MOSI // GPIO18 — SX1278’s CS // GPIO14 — SX1278’s RESET // GPIO26 — SX1278’s IRQ(Interrupt Request) //OLED pins to ESP32 0.96OLEDGPIOs via this connecthin: //OLED_SDA — GPIO4 //OLED_SCL — GPIO15 //OLED_RST — GPIO16 SSD1306 display(0x3c, 4, 15); #define SS 18 #define RST 14 #define DI0 26 #define BAND 433.175E6 //915E6 void setup() { Serial.begin(9600); pinMode(25, OUTPUT); //Send success, LED will bright 1 second while (!Serial); pinMode(16, OUTPUT); digitalWrite(16, LOW); // set GPIO16 low to reset OLED delay(50); digitalWrite(16, HIGH); // while OLED is running, must set GPIO16 in high Serial.println(“LoRa Sender”); SPI.begin(5, 19, 27, 18); LoRa.setPins(SS, RST, DI0); if (!LoRa.begin(BAND)) { Serial.println(“Starting LoRa failed!”); while (1); } Serial.println(“LoRa Initial OK!”); // Initialising the UI will init the display too. display.init(); display.flipScreenVertically(); display.setFont(ArialMT_Plain_10); } void loop() { Serial.print(“Sending packet: “); Serial.println(counter); // send packet LoRa.beginPacket(); LoRa.print(“ThePom”); LoRa.print(counter); LoRa.endPacket(); display.clear(); display.setTextAlignment(TEXT_ALIGN_LEFT); display.drawString(10, 5, “Sending:”); // display.drawString(10, 20, “ThePom ” + String(counter)); // write the buffer to the display display.display(); counter++; digitalWrite(25, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(25, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second delay(5000); } <file_sep>/Arduino/test22/test22.ino #include <Wire.h> #include <LiquidCrystal_I2C.h> // Set the LCD address to 0x27 for a 16 chars and 2 line display LiquidCrystal_I2C lcd(0x27, 20, 4); int num1 = 5, num2 = 2, num3 = 3, num4 = 4; void setup(){ lcd.begin(); } void loop(){ lcd.setCursor(0, 0); lcd.print("NUM1 = "); lcd.setCursor(0, 1); lcd.print("NUM2 = "); lcd.setCursor(0, 2); lcd.print("NUM3 = "); lcd.setCursor(0, 3); lcd.print("NUM4 = "); lcd.setCursor(7, 0); lcd.print(num1); lcd.setCursor(7, 1); lcd.print(num2); lcd.setCursor(7, 2); lcd.print(num3); lcd.setCursor(7, 3); lcd.print(num4); lcd.setCursor(10, 3); lcd.print("freestyle"); } //พิมพ์ข้อความ... <file_sep>/Arduino/libraries/firebase-arduino-master/test/FirebaseArduino_test.cpp // // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "FirebaseObject.h" #include "gtest/gtest.h" TEST(FirebaseObjectTest, JsonLiteral) { EXPECT_EQ(bool(FirebaseObject("true")), true); EXPECT_EQ(bool(FirebaseObject("false")), false); EXPECT_EQ(int(FirebaseObject("42")), 42); EXPECT_EQ(float(FirebaseObject("43.0")), 43.0); EXPECT_EQ(String(FirebaseObject("\"foo\"")), "foo"); } TEST(FirebaseObjectTest, JsonObject) { { const JsonObject& obj = FirebaseObject("{\"foo\":\"bar\"}"); String foo = obj["foo"]; EXPECT_EQ(foo, "bar"); } { String foo = FirebaseObject("{\"foo\":\"bar\"}")["foo"]; EXPECT_EQ(foo, "bar"); } } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <file_sep>/Arduino/5ledBrink2/5ledBrink2.ino #define led1 2 #define led2 3 #define led3 4 #define led4 5 #define led5 6 int dl = 100; void setup() { // put your setup code here, to run once: pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); pinMode(led3, OUTPUT); pinMode(led4, OUTPUT); pinMode(led5, OUTPUT); } void loop() { // put your main code here, to run repeatedly: for (int i = 2; i <= 6; i++){ digitalWrite(i, HIGH); delay(dl); digitalWrite(i, LOW); delay(dl); } for(int i = 5;i >= 3; i--){ digitalWrite(i, HIGH); delay(dl); digitalWrite(i, LOW); delay(dl); } } <file_sep>/Arduino/clockModule/clockModule.ino #include <virtuabotixRTC.h> //Library used //Wiring SCLK -> 6, I/O -> 7, CE -> 8 //Or CLK -> 6 , DAT -> 7, Reset -> 8 #define D5 6 #define D6 7 #define D7 8 int previous; int current; int diff = 1; virtuabotixRTC myRTC(D5, D6, D7); //If you change the wiring change the pins here also void setup() { Serial.begin(9600); // Set the current date, and time in the following format: // seconds, minutes, hours, day of the week, day of the month, month, year myRTC.setDS1302Time(33, 35, 9, 1, 16, 11, 2019); //Here you write your actual time/date as shown above //but remember to "comment/remove" this function once you're done //The setup is done only one time and the module will continue counting it automatically } void loop() { // This allows for the update of variables for time or accessing the individual elements. myRTC.updateTime(); previous = int(myRTC.seconds); Serial.print("previous= "); Serial.println(previous); // Start printing elements as individuals Serial.print("Current Date / Time: "); Serial.print(myRTC.dayofmonth); //You can switch between day and month if you're using American system Serial.print("/"); Serial.print(myRTC.month); Serial.print("/"); Serial.print(myRTC.year); Serial.print(" "); Serial.print(myRTC.hours); Serial.print(":"); Serial.print(myRTC.minutes); Serial.print(":"); Serial.println(myRTC.seconds); // Serial.print(":"); // Serial.println(minute); // Delay so the program doesn't print non-stop delay(3000); myRTC.updateTime(); current = int(myRTC.seconds); Serial.print("current: "); Serial.println(current); //diff = current - previous; //Serial.print("diff = "); //Serial.println(diff); //Serial.println(myRTC.seconds % 60); } <file_sep>/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient.h #ifndef FIREBASE_HTTP_CLIENT_H #define FIREBASE_HTTP_CLIENT_H #include "Arduino.h" #include "Stream.h" struct HttpStatus { static const int TEMPORARY_REDIRECT = 307; }; class FirebaseHttpClient { public: static FirebaseHttpClient* create(); virtual void setReuseConnection(bool reuse) = 0; virtual void begin(const String& url) = 0; virtual void begin(const String& host, const String& path) = 0; virtual void end() = 0; virtual void addHeader(const String& name, const String& value) = 0; virtual void collectHeaders(const char* header_keys[], const int header_key_count) = 0; virtual String header(const String& name) = 0; virtual int sendRequest(const String& method, const String& data) = 0; virtual String getString() = 0; virtual Stream* getStreamPtr() = 0; virtual String errorToString(int error_code) = 0; protected: static const uint16_t kFirebasePort = 443; }; static const String kFirebaseFingerprint = // "7A 54 06 9B DC 7A 25 B3 86 8D 66 53 48 2C 0B 96 42 C7 B3 0A"; // "9A E1 A3 B7 88 E0 C9 A3 3F 13 72 4E B5 CB C7 27 41 B2 0F 6A"; //Dec 15, 2016 // "B8 4F 40 70 0C 63 90 E0 07 E8 7D BD B4 11 D0 4A EA 9C 90 F6"; //2017-8-18 4:34:24 // "6F D0 9A 52 C0 E9 E4 CD A0 D3 02 A4 B7 A1 92 38 2D CA 2F 26"; //2018-8-3 // "E2 34 53 7A 1E D9 7D B8 C5 02 36 0D B2 77 9E 5E 0F 32 71 17"; // 3/3/2019 // "C2 00 62 1D F7 ED AF 8B D1 D5 1D 24 D6 F0 A1 3A EB F1 B4 92"; // "B6 F5 80 C8 B1 DA 61 C1 07 9D 80 42 D8 A9 1F AF 9F C8 96 7D"; //Apr19, 2019 "03 D6 42 23 03 D1 0C 06 73 F7 E2 BD 29 47 13 C3 22 71 37 1B"; //Feb29, 2020 #endif // FIREBASE_HTTP_CLIENT_H <file_sep>/Arduino/lcd4x20/lcd4x20.ino // |———————————————————————————————————————————————————————| // | made by Arduino_uno_guy 11/13/2019 | // | https://create.arduino.cc/projecthub/arduino_uno_guy| // |———————————————————————————————————————————————————————| #include LiquidCrystal_I2C.h #include Wire.h //initialize the liquid crystal library LiquidCrystal_I2C lcd(0x27, 16, 2); void setup() { //initialize lcd screen lcd.init(); // turn on the backlight lcd.backlight(); } void loop() { //wait for a second delay(1000) // tell the screen to write on the top row lcd.setCursor(0,0); // tell the screen to write “hello, from” on the top row lcd.print(“Hello, From”); // tell the screen to write on the bottom row lcd.setCursor(0,1); // tell the screen to write “Arduino_uno_guy” on the bottom row // you can change whats in the quotes to be what you want it to be! lcd.print(“Arduino_uno_guy”); } <file_sep>/Arduino/Ultrasonic_newping/Ultrasonic_newping.ino #include <NewPing.h> #define trigPin 4 #define echoPin 4 #define MAX_DISTANCE 350 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. NewPing sonar(trigPin, echoPin, MAX_DISTANCE); // NewPing setup of pins and maximum distance. float distance; void setup() { Serial.begin(9600); // Open serial monitor at 9600 baud to see ping results. } void loop() { delay(200); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings. distance = sonar.ping_cm(); Serial.print("Distance = "); Serial.print(distance); // Distance will be 0 when out of set max range. Serial.println(" cm"); } <file_sep>/Arduino/sdcard3/sdcard3.ino #include <SD.h> //Connect VCC with 5V in the Arduino. //Then, connect the GND of SD card to the ground of Arduino. //Connect CS to pin 4 //Connect SCK to pin 13 //MOSI connect to the pin 11 //Lastly, connect MISO to pin 12 File myFile; // สร้างออฟเจค File สำหรับจัดการข้อมูล String fileName = "temp.csv"; const int chipSelect = 4; //====================== #include "DHT.h" #define DHTPIN 2 #define DHTTYPE DHT22 DHT dht(DHTPIN, DHTTYPE); int n = 0; void setup() { Serial.begin(9600); Serial.println(F("DHTxx test!")); dht.begin(); connect2sdcard(); // write2file(fileName); readfile(fileName); } void connect2sdcard(){ Serial.begin(9600); while (!Serial) { ; // รอจนกระทั่งเชื่อมต่อกับ Serial port แล้ว (สำหรับ Arduino Leonardo เท่านั้น) } Serial.print("Initializing SD card..."); pinMode(SS, OUTPUT); // Slave select ตัว library มันจะขอให้เป็น OUTPUT เสมอ if (!SD.begin(chipSelect)) { Serial.println("initialization failed!"); return; } Serial.println("initialization done."); // SD.remove(fileName); //ถ้าต้องการลบไฟล์ทิ้ง } void readfile(String filename){ // เปิดไฟล์เพื่ออ่าน ================================== myFile = SD.open(filename); // สั่งให้เปิดไฟล์ชื่อ cmlog.txt เพื่ออ่านข้อมูล if (myFile) { Serial.println(filename + ":"); // อ่านข้อมูลทั้งหมดออกมา while (myFile.available()) { Serial.write(myFile.read()); } myFile.close(); // เมื่ออ่านเสร็จ ปิดไฟล์ } else { // ถ้าอ่านไม่สำเร็จ ให้แสดง error Serial.println("error opening " + filename); } } //*************************************** void write2file(String filename){ // ถ้าเปิดไฟล์สำเร็จ ให้เขียนข้อมูลเพิ่มลงไป myFile = SD.open(filename, FILE_WRITE); if (myFile) { Serial.print("Writing to " + filename + "..."); myFile.println("save data to SD Card"); // เปิดไฟล์ที่ชื่อ fileName เพื่อเขียนข้อมูล โหมด FILE_WRITE =========================== myFile = SD.open(filename, FILE_WRITE); delay(2000); float h = dht.readHumidity(); float t = dht.readTemperature(); float f = dht.readTemperature(true); // Check if any reads failed and exit early (to try again). if (isnan(h) || isnan(t) || isnan(f)) { Serial.println(F("Failed to read from DHT sensor!")); return; } // Compute heat index in Fahrenheit (the default) float hif = dht.computeHeatIndex(f, h); // Compute heat index in Celsius (isFahreheit = false) float hic = dht.computeHeatIndex(t, h, false); Serial.print(n); Serial.print(".) "); Serial.print(F("Humidity: ")); Serial.print(h); Serial.print(F("% Temperature: ")); Serial.print(t); Serial.print(F("°C ")); Serial.print(f); Serial.print(F("°F Heat index: ")); Serial.print(hic); Serial.print(F("°C ")); Serial.print(hif); Serial.println(F("°F")); myFile.print(n); myFile.print(","); myFile.print(h); myFile.print(","); myFile.print(t); myFile.print(","); myFile.print(f); myFile.print(","); myFile.print(hic); myFile.print(","); myFile.println(hif); n++; myFile.close(); // ปิดไฟล์ Serial.println("done."); } else { // ถ้าเปิดไฟลืไม่สำเร็จ ให้แสดง error Serial.println("error opening "+filename); } } void loop() { // write2file(fileName); } <file_sep>/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp // // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "FirebaseObject.h" namespace { template<typename T> T decodeJsonLiteral(const String& json) { return JsonVariant{ArduinoJson::RawJson{json.c_str()}}; } // ugly workaround to https://github.com/bblanchon/ArduinoJson/issues/265 template<> String decodeJsonLiteral<String>(const String& json) { StaticJsonBuffer<JSON_ARRAY_SIZE(1)> buf; String array = "[" + json + "]"; return buf.parseArray(&array[0])[0]; } } // namespace FirebaseObject::FirebaseObject(const String& data) : data_{data} { if (data_[0] == '{') { json_ = &buffer_.parseObject(&data_[0]); } else if (data_[0] == '"') { data_ = decodeJsonLiteral<String>(data_); } } FirebaseObject::operator bool() { return decodeJsonLiteral<bool>(data_); } FirebaseObject::operator int() { return decodeJsonLiteral<int>(data_); } FirebaseObject::operator float() { return decodeJsonLiteral<float>(data_); } FirebaseObject::operator const String&() { return data_; } FirebaseObject::operator const JsonObject&() { return *json_; } JsonObjectSubscript<const char*> FirebaseObject::operator[](const char* key) { return json_->operator[](key); } JsonObjectSubscript<const String&> FirebaseObject::operator[](const String& key) { return json_->operator[](key); } JsonVariant FirebaseObject::operator[](JsonObjectKey key) const { return json_->operator[](key); } <file_sep>/Arduino/i2ctest/i2ctest.ino String answer = "Hello anousone"; #define ANSWERSIZE 20 void setup() { // put your setup code here, to run once: Serial.begin(9600); byte response[ANSWERSIZE]; // Format answer as array for(byte i = 0; i < ANSWERSIZE; i++){ response[i] = (byte)answer.charAt(i); // Serial.println(response[i]); } Serial.println(response[]); // delay(2000); } void requestEvent(){ // Setup byte Variable in the correct size byte response[ANSWERSIZE]; // Format answer as array for(byte i = 0; i < ANSWERSIZE; i++){ response[i] = (byte)answer.charAt(i); } // Send response back to master // Wire.write(response, sizeof(response)); // Serial.println("request Event"); } void loop() { // put your main code here, to run repeatedly: //Serial.print("String = "); //Serial.println(); } <file_sep>/Arduino/Servo/Servo.ino #include<Servo.h> Servo myServo; Servo myServo2; #define button 3 int dataX; int dataY; int StateBTN ; int initial_position1; int initial_position2; void setup() { // put your setup code here, to run once: Serial.begin(57600); pinMode(button, INPUT); myServo.attach(2); myServo2.attach(5); myServo.write(initial_position1); myServo2.write(initial_position2); delay(15); // myServo.write(0); // delay(15); // myServo.write(180); // delay(15); // myServo.write(90); // delay(15); } void loop() { // put your main code here, to run repeatedly: dataX = analogRead(A0); dataY = analogRead(A1); StateBTN = digitalRead(button); dataX = map(dataX, 0, 1023, 0, 180); dataY = map(dataY, 0, 1023, 0, 180); Serial.print("press button , DataX and DataY : "); Serial.print(StateBTN); Serial.print(" , "); Serial.print(dataX); Serial.print(" , "); Serial.println(dataY); myServo.write(dataX); myServo2.write(dataY); delay(15); // myServo.write(90); // delay(600); } <file_sep>/Arduino/test11/test11.ino #define button 7 int StateBTN = LOW; int num; int Previous; void setup() { // put your setup code here, to run once: pinMode(button, INPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: StateBTN = digitalRead(button); if(StateBTN == HIGH && Previous == LOW){ num ++; Serial.print("CountPress = "); Serial.println(num); } Previous = StateBTN; if(num == 5){ digitalWrite(led1, HIGH); delay(dl); digitalWrite(led1, LOW); delay(dl); digitalWrite(led2, HIGH); delay(dl); digitalWrite(led2, LOW); delay(dl); digitalWrite(led3, HIGH); delay(dl); digitalWrite(led3, LOW); delay(dl); digitalWrite(led4, HIGH); delay(dl); digitalWrite(led4, LOW); delay(dl); digitalWrite(led5, HIGH); delay(dl); digitalWrite(led5, LOW); delay(dl); digitalWrite(led4, HIGH); delay(dl); digitalWrite(led4, LOW); delay(dl); digitalWrite(led3, HIGH); delay(dl); digitalWrite(led3, LOW); delay(dl); digitalWrite(led2, HIGH); delay(dl); digitalWrite(led2, LOW); delay(dl); } } <file_sep>/Arduino/readUltrasonic/readUltrasonic.ino #define TRIG 5 #define ECHO 6 #define led 4 long duration; int distance; int previous ; int State = LOW; void setup(){ Serial.begin(9600); pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT); pinMode(led, OUTPUT); } bool readUltrasonic(){ digitalWrite(TRIG, LOW); delayMicroseconds(2); digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG, LOW); //distance = pulseIn(ECHO, HIGH)/58.2; duration = pulseIn(ECHO, HIGH); distance = duration * 0.034 / 2; if( distance < 15){ return HIGH; }else{ return LOW; } } void loop(){ readUltrasonic(); Serial.print("Distance: "); Serial.print(distance); Serial.println(" cm"); //delay(distance*10); delay(100); // digitalWrite(led, readUltrasonic()); State = readUltrasonic(); if(State == HIGH && previous == LOW){ State = !State; digitalWrite(led, State); } previous = State; } <file_sep>/Arduino/test_LDR/test_LDR.ino #define TRIG 5 #define ECHO 6 #define led 7 long duration; int distance; int count = 0; int previous ; int State = LOW; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT); pinMode(led, OUTPUT); } bool readUltrasonic() { digitalWrite(TRIG, LOW); delayMicroseconds(2); digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG,LOW); duration = pulseIn (ECHO, HIGH); distance = duration * 0.034 / 2; if(distance < 15){ return HIGH; }else{ return LOW; } } void loop() { // put your main code here, to run repeatedly: readUltrasonic(); Serial.print("Distance: "); Serial.print(distance); Serial.println(" cm"); delay(100); digitalWrite(led,readUltrasonic()); } <file_sep>/Arduino/on_off_led/on_off_led.ino #define led 4 #define button 5 int StateB; int previous; int StateL = HIGH; void setup() { // put your setup code here, to run once: pinMode(led, OUTPUT); pinMode(button, INPUT); } void loop() { // put your main code here, to run repeatedly: StateB = digitalRead(button); if(StateB == HIGH && previous == LOW){ StateL = !StateL; digitalWrite(led, StateL); } previous = StateB; } <file_sep>/Arduino/netpie2020/netpie2020.ino #include <ESP8266WiFi.h> //#include <WiFi.h> #include <PubSubClient.h> #include <DHT.h> const char* ssid = "XLGO-0AF7"; const char* password = "<PASSWORD>"; const char* mqtt_server = "broker.netpie.io"; const int mqtt_port = 1883; const char* mqtt_Client = "b773645d-9aa1-41af-88e3-0410d354ee9c"; const char* mqtt_username = "EhZQwVqYda7oZjeg86wMm8g6kRFtXRFY"; const char* mqtt_password = "<PASSWORD>"; WiFiClient espClient; PubSubClient client(espClient); char msg[256]; #define DHTTYPE DHT11 #define DHTPIN 2 DHT dht(DHTPIN, DHTTYPE); float data0; String data = ""; unsigned long previousMillis=0, previous=0; int x=0; float temp, humid; float sumtemp, sumhumid, sumdata; #define LED 4 void reconnect() { while (!client.connected()) { Serial.print("Sensor MQTT connection…"); if (client.connect(mqtt_Client, mqtt_username, mqtt_password)) { Serial.println("connected"); client.subscribe("@msg/power"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println("try again in 5 seconds"); delay(5000); } } } void setup() { pinMode(LED, OUTPUT); Serial.begin(115200); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); client.setServer(mqtt_server, mqtt_port); client.setCallback(callback); dht.begin(); } void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("]: "); String message; for (int i = 0; i < length; i++) { message = message + (char)payload[i]; } Serial.println(message); if (String(topic) == "@msg/power") { if (message == "reset") { digitalWrite(LED, HIGH); }else{ digitalWrite(LED, LOW); } } } void loop() { unsigned long currentMillis = millis(); if(currentMillis - previous >= 1000){ previous = currentMillis; data0 = random(20,80); temp = dht.readTemperature(); humid = dht.readHumidity(); Serial.print("temperature : "); Serial.print(temp); Serial.print(", humidity : "); Serial.println(humid); data = String(temp) + "," + String(humid) + "," + String(data0) ; Serial.println(data); data.toCharArray(msg, (data.length() + 1)); client.publish("@msg/update", msg); sumdata += data0; sumtemp += temp; sumhumid += humid; x++; } // Serial.println(" %"); if (!client.connected()) { reconnect(); } client.loop(); if( currentMillis - previousMillis >= 10000){ previousMillis = currentMillis; temp = sumtemp / x; humid = sumhumid / x; data0 = sumdata / x; data = "{\"data\": {\"Temperature\":" + String(temp) + ", \"Humidity\":" + String(humid) +", \"LIGHT\":" + String(data0) + "}}"; Serial.println(data); data.toCharArray(msg, (data.length() + 1)); client.publish("@shadow/data/update", msg); sumtemp = 0; sumhumid = 0; sumdata = 0; x = 0; } } <file_sep>/Arduino/challeng1_2/challeng1_2.ino #define button 7 int num = 0; int n = 0; int countLED = 5; bool btnState = LOW; bool State = 0; void setup() { // put your setup code here, to run once: for(int i = 2; i <= countLED+1; i++){ pinMode(i, OUTPUT); } pinMode(button, INPUT); Serial.begin(9600); } void led_off(){ for (int i = n + 1; i <= countLED + 2; i++){ digitalWrite(i, LOW); } for (int i = n - 1; i >= 2; i--){ digitalWrite(i, LOW); } } void loop() { // put your main code here, to run repeatedly: btnState = digitalRead(button); while(btnState == LOW){ while(btnState == LOW){ btnState = digitalRead(button); } num++; Serial.print("num = "); Serial.println(num); n = (num % (countLED + 1)) + 1; if(n != 0){ digitalWrite(n, HIGH); }else{ digitalWrite(n, LOW); } led_off(); } } <file_sep>/Arduino/interrupt/interrupt.ino int led_01 = 8; int led_02 = 9; volatile int toggle = LOW; void setup() { // put your setup code here, to run once: pinMode(led_01, OUTPUT); pinMode(led_02, OUTPUT); attachInterrupt(0, toggle_isr, FALLING); } void loop() { // put your main code here, to run repeatedly: digitalWrite(led_01, HIGH); delay(100); digitalWrite(led_01, LOW); delay(100); } void toggle_isr(){ toggle = !toggle; digitalWrite(led_02, toggle); } <file_sep>/Arduino/test_led/test_led.ino //#define 7 const int led1 = 2; #define led2 3 int led3 = 4; int led4 = 5; int led5 = 6; void setup() { // put your setup code here, to run once: pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); pinMode(led3, OUTPUT); pinMode(led4, OUTPUT); pinMode(led5, OUTPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: for (int i = 2; i < 7; i++) { digitalWrite(i, HIGH); delay(100); digitalWrite(i, LOW); delay(100); } for (int i = 5; i > 1 ; i--) { digitalWrite(i, HIGH); delay(100); digitalWrite(i, LOW); delay(100); } // digitalWrite(led1, HIGH); // delay(100); // digitalWrite(led1, LOW); // delay(100); // // digitalWrite(led2, HIGH); // delay(100); // digitalWrite(led2, LOW); // delay(100); // // digitalWrite(led3, HIGH); // delay(100); // digitalWrite(led3, LOW); // delay(100); // // digitalWrite(led4, HIGH); // delay(100); // digitalWrite(led4, LOW); // delay(100); // // digitalWrite(led5, HIGH); // delay(100); // digitalWrite(led5, LOW); // delay(100); // // /////////// // // digitalWrite(led4, HIGH); // delay(100); // digitalWrite(led4, LOW); // delay(100); // // digitalWrite(led3, HIGH); // delay(100); // digitalWrite(led3, LOW); // delay(100); // // digitalWrite(led2, HIGH); // delay(100); // digitalWrite(led2, LOW); // delay(100); } <file_sep>/Arduino/i2cUltrasonic/i2cUltrasonic.ino #include <NewPing.h> // sensor 0 #define TRIGGER_PIN_0 8 #define ECHO_PIN_0 8 // sensor 1 #define TRIGGER_PIN_1 9 #define ECHO_PIN_1 9 // Maximum Distance is 400 cm #define MAX_DISTANCE 400 // create objects for ultrasonic sensors NewPing sensor0(TRIGGER_PIN_0, ECHO_PIN_0, MAX_DISTANCE); NewPing sensor1(TRIGGER_PIN_1, ECHO_PIN_1, MAX_DISTANCE); // variables to represent distances float distance0, distance1; void setup() { // Serial monitor for testing Serial.begin(9600); } void loop() { // Read sensors in CM // sensor 0 distance0 = sensor0.ping_cm(); delay(20); // sensor 1 distance1 = sensor1.ping_cm(); delay(20); // send results to Serial monitor // sensor 0 Serial.print("Distance 0 = "); if(distance0 >= 400 || distance0 <= 2){ Serial.println("Out of range"); }else{ Serial.print(distance0); Serial.println(" cm"); delay(500); } // Sensor 1 Serial.print("Distance 1 = "); if(distance1 >= 400 || distance1 <= 2){ Serial.println("Out of range"); }else{ Serial.print(distance1); Serial.println(" cm"); delay(500); } } <file_sep>/Arduino/present2/present2.ino #define button_mode 3 #define led_2 4 #define led_3 5 #define Echo_1 6 #define Trig_1 7 #define button_1 8 #define led_1 9 #define buzzer 10 #define Echo_2 11 #define Trig_2 12 int previous = LOW; int State; int present = LOW; int present_2 = LOW; int readingmode = LOW; int reading; int k = HIGH, n; int m ; int kon = LOW; int X = LOW; int State_1 = LOW; int State_2 = HIGH; int add; int breaker = HIGH; int a, out; long duration; int distance; // ========================================================== void setup() { // put your setup code here, to run once: pinMode(button_1, INPUT); pinMode(Echo_1, INPUT); pinMode(Trig_1, OUTPUT); pinMode(led_1, OUTPUT); pinMode(buzzer, OUTPUT); pinMode(led_2, OUTPUT); pinMode(led_3, OUTPUT); pinMode(button_mode, INPUT); pinMode(Echo_2, INPUT); pinMode(Trig_2, OUTPUT); Serial.begin(9600); } bool readUltrasonic(){ digitalWrite(Trig_1, LOW); delayMicroseconds(2); digitalWrite(Trig_1, HIGH); delayMicroseconds(10); digitalWrite(Trig_1, LOW); duration = pulseIn(Echo_1, HIGH); distance = duration * 0.034 / 2; Serial.println(distance); if( distance < 100){ return HIGH; }else{ return LOW; } } // =========================================== bool readUltrasonic2(){ digitalWrite(Trig_2, LOW); delayMicroseconds(2); digitalWrite(Trig_2, HIGH); delayMicroseconds(10); digitalWrite(Trig_2, LOW); duration = pulseIn(Echo_2, HIGH); distance = duration * 0.034 / 2; Serial.println(distance); if( distance < 100){ return HIGH; }else{ return LOW; } } // ============================================================== void selectMode(){ do{ readingmode = digitalRead(button_mode); // choose Mode: 1 or 2 if(readingmode == HIGH && kon == LOW){ State_1 = !State_1 ; State_2 = !State_2 ; breaker = !breaker; k = LOW; if(m == 1){ m = 2; }else{ m = 1; } } kon = readingmode; }while(readingmode == HIGH); Serial.println("selectMode"); } // ============================================================================== void mode1 (){ do{ digitalWrite(led_1, State_1); digitalWrite(led_2, State_2); selectMode(); reading = digitalRead(button_1); if(reading == HIGH && previous == LOW){ State = !State; } digitalWrite(led_3, State); delay(100); previous = reading; }while( m == 1); // if m = 2 stop Mode 1 ; come in Mode 2 digitalWrite(led_3, LOW); // if stop Mode 1 , led_3 off } // ================================================================== void mode2 (){ do{ digitalWrite(led_2 ,State_2); // State Mode digitalWrite(led_1, State_1); do{ selectMode(); // if button_Mode = HIGH : STOP MODE 2; COME IN MODE 1 }while(readingmode == HIGH); State = LOW; present = LOW; do{ n = 6; present = readUltrasonic(); // sensor out room Serial.println(present); if( present == HIGH){ add = 1; Serial.println("sensor111111"); } present_2 = readUltrasonic2(); Serial.println(present_2); if( present_2 == HIGH && add == 1){ if(State == LOW){ State = HIGH; n = 5; add = 0; Serial.println("sensor222222"); } } digitalWrite(led_3, State); Serial.println("hhhhhh"); selectMode(); if( n == 5){ tone(buzzer, 925, 225); delay(1000); } } while (add == 1); Serial.println("outtttt"); out = 0; k = HIGH; n = 0; a = LOW; present = LOW; if ( State == HIGH){ Serial.println("state = high"); do{ if( a == LOW ){ do { present_2 = readUltrasonic2(); // sensor in room delay(200); if(present_2 == HIGH && a == LOW){ do{ selectMode(); // if button_Mode = HIHG, stop mode 2 ; come in mode 1 } while (readingmode == HIGH); } }while( present_2 == HIGH); present_2 = LOW; } a = HIGH; delay(100); do{ selectMode(); // if button_Mode = HIGH, stop mode 2 ; come in mode 1 } while ( readingmode == HIGH); present_2 = readUltrasonic2(); // sensor in room if(present_2 == HIGH){ out = 1; } present = readUltrasonic(); // sensor out room if( present == HIGH && out == 1){ k = LOW; // led_3 off or on } delay(100); n++; if(n == 40){ tone(buzzer, 988, 250); delay(400); do{ selectMode(); }while(readingmode == HIGH); tone(buzzer, 880, 250); delay(400); do{ selectMode(); }while(readingmode == HIGH); tone(buzzer, 784, 1000); delay(1000); do{ selectMode(); }while(readingmode == HIGH); tone(buzzer, 784, 1000); delay(1000); } } while (k == HIGH && n <= 60); } digitalWrite(led_3, LOW); do{ present = readUltrasonic(); // sensor out room } while (present == HIGH); selectMode(); } while (m == 2); // if m = 1 is Mode 2 off digitalWrite( led_3, LOW ); // if stop Mode 2 is led_3 off } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void loop() { X = LOW; State = LOW; reading = LOW; selectMode(); // Mode 1 or 2 digitalWrite(led_3, breaker); switch(m){ case 1: // come in mode 1 if m = 1 mode1(); case 2: // come in Mode 2 mode2(); } } <file_sep>/Arduino/buzzer/buzzer.ino #define R_1 3 #define R_2 4 #define L_1 5 #define L_2 6 int dl = 1000; void setup() { // put your setup code here, to run once: pinMode(R_1, OUTPUT); pinMode(R_2, OUTPUT); pinMode(L_1, OUTPUT); pinMode(L_2, OUTPUT); } void forward(){ digitalWrite(R_1, HIGH); // forward digitalWrite(R_2, LOW); digitalWrite(L_1, HIGH); digitalWrite(L_2, LOW); } void back(){ digitalWrite(R_1, LOW); // forward digitalWrite(R_2, HIGH); digitalWrite(L_1, LOW); digitalWrite(L_2, HIGH); } void Stop(){ digitalWrite(R_1, LOW); // forward digitalWrite(R_2, LOW); digitalWrite(L_1, LOW); digitalWrite(L_2, LOW); } void loop() { Stop(); delay(400); forward(); delay(dl); Stop(); delay(400); back(); delay(dl); } <file_sep>/Arduino/MGMelonfarm/MGMelonfarm.ino //#include <Arduino.h> #include "DHT.h" #include <Adafruit_Sensor.h> #include "Wire.h" #include <Adafruit_LiquidCrystal.h> // what digital pin we're connected to #define inDHT 8 #define outDHT 9 // Uncomment whatever type you're using! //#define DHTTYPE DHT11 // DHT 11 #define inDHTTYPE DHT22 // DHT 22 (AM2302), AM2321 #define outDHTTYPE DHT22 // photoresistor are defined #define inLight A8 #define outLight A9 // define moisPin0 for Soil moisture sensor one // define moisPin1 for Soil moisture sensor two // define moisPin2 for Soil moisture sensor three #define moisPin0 A0 #define moisPin1 A1 #define moisPin2 A2 // Define status variable to stall the realtime data from inDHT & outDHT int inHumdStatus = 0; int outHumdStatus = 0; int inTempStatus = 0; int outTempStatus = 0; // inLightStaus and outLightStatus are Read value from sensor directly. int inLightStatus = 0; int outLightStatus = 0; int inLightPercent; int outLightPercent; // Standard photoresistor value is 1024 that mean it will start from 0 to 1023 int lightMin = 0; int lightMax = 1023; // define status variable to stall the realtime data form moisture sensor 1, 2, and 3;] int moisStatus0 = 0; int moisStatus1 = 0; int moisStatus2 = 0; // Sending str to Nodemcu // String str; // Communication String String strInH; String strInT; String strOutH; String strOutT; String strInLig; String strOutLig; String strMois0; String strMois1; String strMois2; // as the current DHT reading algorithm adjusts itself to work on faster procs. DHT dht1(inDHT, inDHTTYPE); DHT dht2(outDHT, outDHTTYPE); // initialize the library with the numbers of the interface pins Adafruit_LiquidCrystal lcd(12, 11, 5, 4, 3, 2); int Contrast = 125; //calling function void humidTemp(); void photoresis(); void soilMoisture(); void comnuni(); void LCDSetup(); void setup() { Serial.begin(115200); Serial1.begin(115200); Serial.println("Smart Melon Farm [MEGE]"); // DHT22 begin dht1.begin(); dht2.begin(); // inform the MCU that photoresistor is an input pinMode(inLight, INPUT); pinMode(inLight, INPUT); // inform the MCU that Soil Moisture is an input pinMode(moisPin0, INPUT); pinMode(moisPin1, INPUT); pinMode(moisPin2, INPUT); } void loop() { // Wait a few seconds between measurements. delay(2000); // humidity and Temperature humidTemp(); // photoresistor photoresis(); // soil Moisture soilMoisture(); // show in Nodemcu by serial Monitor as realtime comnuni(); // LCD Disply LCDSetup(); } // humidity and Temperature function void humidTemp() { // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) inHumdStatus = dht1.readHumidity(); outHumdStatus = dht2.readHumidity(); // Read temperature as Celsius (the default) inTempStatus = dht1.readTemperature(); outTempStatus = dht2.readTemperature(); // Check if any reads failed and exit early (to try again). if (isnan(inHumdStatus) || isnan(inTempStatus)) { Serial.println("Failed to read from Inside DHT22 sensor!"); return; } if (isnan(outHumdStatus) || isnan(outTempStatus)) { Serial.println("Failed to read from Outside DHT22 sensor!"); return; } Serial.println("\t\t\tSmart Melon Farm [MEGE]"); Serial.println("------------------------------------------------------------------------"); // show in MG module as realtime Serial.print("Inside Humidity: \t"); Serial.print(inHumdStatus); Serial.print(" %\t|\t"); Serial.print("Inside Temperature: \t"); Serial.print(inTempStatus); Serial.println(" *C\t|"); Serial.print("Outside Humidity: \t"); Serial.print(outHumdStatus); Serial.print(" %\t|\t"); Serial.print("Outside Temperature: \t"); Serial.print(outTempStatus); Serial.println(" *C\t|"); Serial.println("------------------------------------------------------------------------"); } // photoresistor function void photoresis() { // Reading the value from sensor directly. inLightStatus = analogRead(inLight); outLightStatus = analogRead(outLight); // if inLightStatus is less than 0, set it equal 0, but if greater than 1023 set it equal 1023 if (inLightStatus < lightMin) inLightStatus = lightMin; else if (inLightStatus > lightMax) inLightStatus = lightMax; // if outLightstatus is less than 0, set it equal 0, but if greater than 1023, set it equal 1023 if (outLightStatus < lightMin) outLightStatus = lightMin; else if (outLightStatus > lightMax) outLightStatus = lightMax; // calculate to % inLightPercent = (inLightStatus / 1023.0 * 100.0); outLightPercent = (outLightStatus / 1023.0 * 100.0); // showing status in monitor Serial.print("Inside Light: \t\t"); Serial.print(inLightPercent); Serial.print(" %\t|\tOutside Light: \t\t"); Serial.print(outLightPercent); Serial.println(" %\t|"); Serial.println("------------------------------------------------------------------------"); } // Soil moisture function void soilMoisture() { // reading data from each moisture sensors directly moisStatus0 = (analogRead(moisPin0) / 1024.0) * 100.0; moisStatus1 = (analogRead(moisPin1) / 1024.0) * 100.0; moisStatus2 = (analogRead(moisPin2) / 1024.0) * 100.0; // showing each moisture sensors to screen Serial.print("Soil moisture one \t"); Serial.print(moisStatus0); Serial.print(" %\t|\t"); Serial.print("Soil moisture two \t"); Serial.print(moisStatus1); Serial.print(" %\t|\t"); Serial.print("Soil moisture three \t"); Serial.print(moisStatus2); Serial.println(" %\t|\t"); Serial.println("----------------------------------------------------------------------------------------------------------------- \n\n"); } // Serial Communication function void comnuni() { // in and out dht communication sending string strInH = String('H') + String(inHumdStatus); strInT = String('T') + String(inTempStatus); strOutH = String('I') + String(outHumdStatus); strOutT = String('U') + String(outTempStatus); Serial1.println(strInH); Serial1.println(strInT); Serial1.println(strOutH); Serial1.println(strOutT); // in and out light communication sending string strInLig = String('L') + String(inLightPercent); strOutLig = String('M') + String(outLightPercent); Serial1.println(strInLig); Serial1.println(strOutLig); //mois 1, 2, and 3 communication sending string strMois0 = String('N') + String(moisStatus0); strMois1 = String('O') + String(moisStatus1); strMois2 = String('P') + String(moisStatus2); Serial1.println(strMois0); Serial1.println(strMois1); Serial1.println(strMois2); } void LCDSetup() { analogWrite(6, Contrast); lcd.begin(20, 4); lcd.setCursor(0, 0); lcd.print("IH:"); lcd.print(inHumdStatus); lcd.print(" IT:"); lcd.print(inTempStatus); lcd.print(" IL:"); lcd.print(inLightStatus); lcd.setCursor(0, 1); lcd.print("OH:"); lcd.print(outHumdStatus); lcd.print(" OT:"); lcd.print(outTempStatus); lcd.print(" OL:"); lcd.print(outLightStatus); lcd.setCursor(0, 2); lcd.print("S1:"); lcd.print(moisStatus0); lcd.print(" S2:"); lcd.print(moisStatus1); lcd.print(" S3:"); lcd.print(moisStatus2); } <file_sep>/Arduino/pwmtest/pwmtest.ino #define DIR_1 2 // PIN ควบคุมทิศทางการหมุนของมอเตอร์ 1 #define PWM_1 3 // PIN ความเร็วของมอเตอร์ 1 #define DIR_2 4 // PIN ควบคุมทิศทางการหมุนของมอเตอร์ 2 #define PWM_2 5 // PIN ความเร็วของมอเตอร์ 2 #define SPEED_MOTOR_1 50 // ค่าความเร็วมอเตอร์ 1 มีค่าตั้งแต่ 0 – 255 (Duty Cycle) #define SPEED_MOTOR_2 50 // ค่าความเร็วมอเตอร์ 2 มีค่าตั้งแต่ 0 – 255 (Duty Cycle) void setup() { pinMode(DIR_1, OUTPUT); // ตั้งค่า DIR_1 ของมอเตอร์ 1 เป็น Output pinMode(PWM_1, OUTPUT); // ตั้งค่า PWM_1 ของมอเตอร์ 1 เป็น Output pinMode(DIR_2, OUTPUT); // ตั้งค่า DIR_2 ของมอเตอร์ 2 เป็น Output pinMode(PWM_2, OUTPUT); // ตั้งค่า PWM_2 ของมอเตอร์ 2 เป็น Output analogWrite(PWM_1, SPEED_MOTOR_1); // สร้างสัญญาณ PWM เป็น Output ให้กับมอเตอร์ 1 analogWrite(PWM_2, SPEED_MOTOR_2); // สร้างสัญญาณ PWM เป็น Output ให้กับมอเตอร์ 2 } void loop() { digitalWrite(DIR_1, LOW); // กำหนดทิศทางให้มอเตอร์ 1 หมุนตามเข็มนาฬิกา digitalWrite(DIR_2, LOW); // กำหนดทิศทางให้มอเตอร์ 2 หมุนตามเข็มนาฬิกา // delay(1000); // หน่วงเวลา 1 วินาที // digitalWrite(DIR_1, HIGH); // กำหนดทิศทางให้มอเตอร์ 1 หมุนทวนเข็มนาฬิกา // digitalWrite(DIR_2, HIGH); // กำหนดทิศทางให้มอเตอร์ 2 หมุนทวนเข็มนาฬิกา // delay(1000); // หน่วงเวลา 1 วินาที } <file_sep>/Arduino/i2cultra_master/i2cultra_master.ino // include arduino wire library for i2c #include<Wire.h> // define slave i2c address #define SLAVE_ADDR 9 // define counter to count bytes in response int bcount; // define array for return data byte distance[2]; void setup() { // put your setup code here, to run once: Wire.begin(); Serial.begin(9600); } byte readI2C(int address){ //define a variable to hold byte of data byte bval; long entry = millis(); // read one byte at a time Wire.requestFrom(address, 1); //Wait 100 ms for data to stabilize while(Wire.available() == 0 && (millis() - entry) < 100){ Serial.println("Waiting"); } // Place data into byte if(millis() - entry < 100) bval = Wire.read(); return bval; } void loop() { while(readI2C(SLAVE_ADDR) < 255){ // Until first byte has been received print a waiting message Serial.println("first byte Waiting"); } for(bcount = 0; bcount < 2; bcount++){ distance[bcount] = readI2C(SLAVE_ADDR); } for(int i = 0; i<2; i++){ Serial.print(distance[i]); Serial.print("\t"); } Serial.println(); delay(500); } <file_sep>/Arduino/esp8266_firebase/esp8266_firebase.ino /* Copyright 2018 Electrical Engineering Enterprise Group. * ESP-EP.9_Firebase * * <NAME> */ #include <DHT.h> #include <FirebaseArduino.h> #include <ESP8266WiFi.h> #include <ESP8266WiFiMulti.h> ESP8266WiFiMulti WiFiMulti; // FIREBASE NAME/SECRET Config #define PROJECT_IO "smart-farm-3ef1a.firebaseio.com" #define DATA_SECRET "<KEY>" // WiFi Access Config #define SSID_1 "CEIT-IoT" #define PASS_1 "<PASSWORD>" #define LED 4 #define DHTPIN 5 #define DHTTYPE DHT22 DHT dht(DHTPIN, DHTTYPE); void setup() { pinMode(LED, OUTPUT); Serial.end(); Serial.begin(115200); delay(10); SetWiFi(); CheckWiFi(); Firebase.begin(PROJECT_IO, DATA_SECRET); dht.begin(); } void loop() { CheckWiFi(); Firebase_SET(); Firebase_GET(); } void Firebase_SET(){ float h = dht.readHumidity(); float t = dht.readTemperature(); Firebase.set("temp", t); Firebase.set("humid", h); delay(500); } void Firebase_GET(){ int VALUE_A = Firebase.get("users/my key"); Serial.println("users/my key: " + String(VALUE_A)); if(VALUE_A == 0){ digitalWrite(LED, LOW); }else{ digitalWrite(LED, HIGH); } delay(500); } void CheckWiFi(){ while(WiFiMulti.run() != WL_CONNECTED) { Serial.println("WiFi not connected!"); delay(1000); } } void SetWiFi(){ Serial.print("\n\nElectricl Engineering Enterprise Group\n"); WiFiMulti.addAP(SSID_1, PASS_1); WiFiMulti.addAP("AndroidAP", "ifmd0883"); Serial.println("Connecting Wifi..."); delay(2000); Serial.println("Connecting Wifi..."); if (WiFiMulti.run() == WL_CONNECTED) { Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } } <file_sep>/Arduino/challeng1/challeng1.ino #define button 7 #define led1 2 #define led2 3 #define led3 4 #define led4 5 #define led5 6 int num = 0; bool btnState = LOW; bool State = 0; void setup() { // put your setup code here, to run once: pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); pinMode(led3, OUTPUT); pinMode(led4, OUTPUT); pinMode(led5, OUTPUT); pinMode(button, INPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: btnState = digitalRead(button); while(btnState == LOW){ while(btnState == LOW){ btnState = digitalRead(button); } num++; Serial.print("num = "); Serial.println(num); } if(num % 6 == 0){ digitalWrite(led1, LOW); digitalWrite(led2, LOW); digitalWrite(led3, LOW); digitalWrite(led4, LOW); digitalWrite(led5, LOW); }else if(num % 6 == 1){ digitalWrite(led1, HIGH); digitalWrite(led2, LOW); digitalWrite(led3, LOW); digitalWrite(led4, LOW); digitalWrite(led5, LOW); }else if(num % 6 == 2){ digitalWrite(led1, LOW); digitalWrite(led2, HIGH); digitalWrite(led3, LOW); digitalWrite(led4, LOW); digitalWrite(led5, LOW); }else if(num % 6 == 3){ digitalWrite(led1, LOW); digitalWrite(led2, LOW); digitalWrite(led3, HIGH); digitalWrite(led4, LOW); digitalWrite(led5, LOW); }else if(num % 6 == 4){ digitalWrite(led1, LOW); digitalWrite(led2, LOW); digitalWrite(led3, LOW); digitalWrite(led4, HIGH); digitalWrite(led5, LOW); }else{ digitalWrite(led1, LOW); digitalWrite(led2, LOW); digitalWrite(led3, LOW); digitalWrite(led4, LOW); digitalWrite(led5, HIGH); } } <file_sep>/Arduino/else_if/else_if.ino int a = 5; int b = 10; int c = 12; int d = 20; int e = 11; int Max; int num = 12972; void setup() { // put your setup code here, to run once: Serial.begin(9600); Max = a; // if(b > Max){ // Max = b; // }if(c > Max){ // Max = c; // }if(d > Max){ // Max = d; // }if(e > Max){ // Max = e; // } // if(b > Max){ // Max = b; // }else if(c > Max){ // Max = c; // }else if(d > Max){ // Max = d; // }else if(e > Max){ // Max = e; // } if(num % 10 == 0){ Serial.println("end num = 0"); }else if(num % 10 == 1){ Serial.println("end num = 1"); }else if(num % 10 == 2){ Serial.println("end num = 2"); }else if(num % 10 == 3){ Serial.println("end num = 3"); }else if(num % 10 == 4){ Serial.println("end num = 4"); }else if(num % 10 == 5){ Serial.println("end num = 5"); }else if(num % 10 == 6){ Serial.println("end num = 6"); }else if(num % 10 == 7){ Serial.println("end num = 7"); }else if(num % 10 == 8){ Serial.println("end num = 8"); }else if(num % 10 == 9){ Serial.println("end num = 9"); } // Serial.print("end num = "); // Serial.println(num % 10); // Serial.print("Max = "); // Serial.println(Max); } void loop() { // put your main code here, to run repeatedly: } <file_sep>/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp // // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "FirebaseArduino.h" void FirebaseArduino::begin(const char* host, const char* auth) { http_.reset(FirebaseHttpClient::create()); http_->setReuseConnection(true); host_ = host; auth_ = auth; } String FirebaseArduino::FirebaseArduino::push(const String& path, const JsonVariant& value) { String buf; value.printTo(buf); auto push = FirebasePush(host_, auth_, path, buf, http_.get()); error_ = push.error(); return push.name(); } void FirebaseArduino::set(const String& path, const JsonVariant& value) { String buf; value.printTo(buf); auto set = FirebaseSet(host_, auth_, path, buf, http_.get()); error_ = set.error(); } FirebaseObject FirebaseArduino::get(const char* path) { auto get = FirebaseGet(host_, auth_, path, http_.get()); error_ = get.error(); if (failed()) { return FirebaseObject{""}; } return FirebaseObject(get.response()); } void FirebaseArduino::remove(const char* path) { auto remove = FirebaseRemove(host_, auth_, path, http_.get()); error_ = remove.error(); } void FirebaseArduino::stream(const char* path) { auto stream = FirebaseStream(host_, auth_, path, http_.get()); error_ = stream.error(); } bool FirebaseArduino::available() { return http_->getStreamPtr()->available(); } FirebaseObject FirebaseArduino::readEvent() { auto client = http_->getStreamPtr(); String type = client->readStringUntil('\n').substring(7);; String event = client->readStringUntil('\n').substring(6); client->readStringUntil('\n'); // consume separator FirebaseObject obj = FirebaseObject(event); obj["type"] = type; return obj; } bool FirebaseArduino::success() { return error_.code() == 0; } bool FirebaseArduino::failed() { return error_.code() != 0; } const String& FirebaseArduino::error() { return error_.message(); } FirebaseArduino Firebase; <file_sep>/Arduino/test_lcd2/test_lcd2.ino #include <LiquidCrystal_PCF8574.h> #include <Wire.h> LiquidCrystal_PCF8574 lcd(0x27); // set the LCD address to 0x27 for a 16 chars and 2 line display int show; void setup() { lcd.begin (20,4); lcd.setBacklight(255); lcd.print("Welcome ALL To"); } // setup() void loop() { } <file_sep>/Arduino/eeprom/eeprom.ino #include<EEPROM.h> #define BUTTON 2 bool val; int n = 0; int State; int previous; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(BUTTON, INPUT); // n = EEPROM.read(1); } void loop() { // put your main code here, to run repeatedly: int line=0; val = digitalRead(BUTTON); delay(100); if(val == HIGH && previous == LOW){ State = !State; n++; } previous = val; // EEPROM.write(0, 80); // EEPROM.write(4, 254); // EEPROM.write(512, 124); // if(val != LOW){ // EEPROM.write(1, n); // } // Serial.println("n = " + String(n)); // Serial.print("eeprom = "); // Serial.println(EEPROM.read(1)); for(int i=0; i<=512;i++){ Serial.print(EEPROM.read(i)); Serial.print(" "); if(line++ > 20){ Serial.println(); line = 0; } } while(1); } <file_sep>/Arduino/i2cmasterbtn/i2cmasterbtn.ino // include Arduino Wire for i2c #include<Wire.h> //Define Slave i2c Address #define SLAVE_ADDR 8 // Define Slave answer size //#define ANSWERSIZE 5 bool StateBTN = LOW; bool previous; bool State; void setup() { // put your setup code here, to run once: Wire.begin(); Serial.begin(9600); Serial.println("I2C Master Demonstration"); pinMode(3, INPUT); } void loop() { // put your main code here, to run repeatedly: StateBTN = digitalRead(3); if(StateBTN == 1 && previous == 0){ State = !State; } previous = StateBTN; // Write charactre from the Slave Wire.beginTransmission(SLAVE_ADDR); Wire.write(State); Wire.endTransmission(); } <file_sep>/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.h // // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef FIREBASE_ARDUINO_H #define FIREBASE_ARDUINO_H #include "Firebase.h" #include "FirebaseObject.h" #ifndef FIREBASE_JSONBUFFER_SIZE #define FIREBASE_JSONBUFFER_SIZE 200 #endif // FIREBASE_JSONBUFFER_SIZE class FirebaseArduino { public: void begin(const char* host, const char* auth = ""); String push(const String& path, const JsonVariant& value); void set(const String& path, const JsonVariant& value); FirebaseObject get(const char* path); void remove(const char* path); void stream(const char* path); bool available(); FirebaseObject readEvent(); bool success(); bool failed(); const String& error(); private: String host_; String auth_; FirebaseError error_; std::unique_ptr<FirebaseHttpClient> http_; }; extern FirebaseArduino Firebase; #endif // FIREBASE_ARDUINO_H <file_sep>/Arduino/libraries/firebase-arduino-master/src/modem/json_util.h #ifndef MODEM_JSON_UTIL_H #define MODEM_JSON_UTIL_H namespace firebase { namespace modem { // TODO(edcoyne): We should use a json library to escape. inline String EncodeForJson(String input) { input.replace("\\", "\\\\"); input.replace("\"", "\\\""); return "\"" + input + "\""; } } // modem } // firebase #endif // MODEM_JSON_UTIL_H <file_sep>/Arduino/libraries/firebase-arduino-master/src/SerialTransceiver.h #include "modem/SerialTransceiver.h" // Bring them into the base namespace for easier use in arduino ide. using firebase::modem::SerialTransceiver; <file_sep>/Arduino/blynk_led/blynk_led.ino //char ssid[] = "XLGO-0AF7"; //char pass[] = "<PASSWORD>"; #define BLYNK_PRINT Serial #define SOLENOID D2 #include <ESP8266WiFi.h> #include <BlynkSimpleEsp8266.h> //char auth[] = "<KEY>"; char auth[] = "<KEY>"; char ssid[] = "XLGO-0AF7"; char pass[] = "<PASSWORD>"; bool switchStatus = 0; // 0 = manual,1=auto int soilMoistureLimit = 0; bool manualSwitch = 0; BlynkTimer timer; // sync all status BLYNK_CONNECTED() { Blynk.syncAll(); } // update switchStatus BLYNK_WRITE(V0) { switchStatus = param.asInt(); // Get value as integer } // update soilMosture setting BLYNK_WRITE(V1) { soilMoistureLimit = param.asInt(); // Get value as integer } // update manualSwitch BLYNK_WRITE(V2) { manualSwitch = param.asInt(); } void manualAutoAction() { Serial.print("switchStatus = "); Serial.println(switchStatus); Serial.print("soimoi = "); Serial.println(soilMoistureLimit); Serial.print("manualSwitch = "); Serial.println(manualSwitch); if(switchStatus) { // auto if(analogRead(A0) < soilMoistureLimit) { // D6 connect relay digitalWrite(SOLENOID,LOW); } else { digitalWrite(SOLENOID,HIGH); } } else { if(manualSwitch) { digitalWrite(SOLENOID,LOW); } else { digitalWrite(SOLENOID,HIGH); } // manaul } } void checkTemp() { Serial.println("CheckTemp"); } void setup() { // Debug console Serial.begin(9600); pinMode(SOLENOID,OUTPUT); digitalWrite(SOLENOID,HIGH); Blynk.begin(auth, ssid, pass); // key timer.setInterval(1000L, manualAutoAction); timer.setInterval(10000L, checkTemp); } void loop() { Blynk.run(); timer.run(); } <file_sep>/Arduino/auto/auto.ino //CEIT_Robot_2018 In Loas int count_sensor = 0;// Count Line int last_state_sensor = 0; //Check State before Count Line //set PIN data of line direction sensor #define SENSOR_T1 22 #define SENSOR_T2 23 #define SENSOR_T3 24 #define SENSOR_T4 25 #define SENSOR_T5 26 #define SENSOR_T6 6 #define SENSOR_T7 7 //save to read the reperent from line sensor int data_sensor_1 = 0; int data_sensor_2 = 0; int data_sensor_3 = 0; int data_sensor_4 = 0; int data_sensor_5 = 0; int data_sensor_6 = 0; int data_sensor_7 = 0; // set PIN motor and power rolling #define DIR1 12 #define DIR2 10 #define PWM1 11 #define PWM2 9 // in line speed int pwm_l = 90; int pwm_r = 90; // turn in line speed int pwmTurn_l = 45; int pwmTurn_r = 45; // uturn zone speed int pwmUturn_l = 60; int pwmUturn_r = 60; // states of the robot #define START 0 #define WAIT 1 #define GO 2 #define DROP_IN 3 #define DROP_OUT 4 #define BACK 5 // colors #define GREEN 1 #define RED 0 #define BLUE 2 // initial state int state = GO; // initla box color int color = GREEN; // initial count for checkpoint count int count = 0; // IR Box detect #define BOX_IR 27 // slider #define PWM_SLDR 4 #define SLDR 5 // Switch #define SLDR_SW_TOP 52 #define SLDR_SW_BTM 51 // Color Sensor #define COLOR_S0 47 #define COLOR_S1 48 #define COLOR_S2 49 #define COLOR_S3 50 #define COLOR_SENSOR 53 void setup() { Serial.begin(9600); //line direction sensor pinMode(SENSOR_T1, INPUT); pinMode(SENSOR_T2, INPUT); pinMode(SENSOR_T3, INPUT); pinMode(SENSOR_T4, INPUT); pinMode(SENSOR_T5, INPUT); pinMode(SENSOR_T6, INPUT); pinMode(SENSOR_T7, INPUT); //motor and power rolling pinMode(DIR1, OUTPUT); pinMode(DIR2, OUTPUT); pinMode(PWM1, OUTPUT); pinMode(PWM2, OUTPUT); // Slider pinMode(PWM_SLDR, OUTPUT); pinMode(SLDR, OUTPUT); // Switches pinMode(SLDR_SW_TOP, INPUT); pinMode(SLDR_SW_BTM, INPUT); // Color Sensors pinMode(COLOR_S0, OUTPUT); pinMode(COLOR_S1, OUTPUT); pinMode(COLOR_S2, OUTPUT); pinMode(COLOR_S3, OUTPUT); pinMode(COLOR_SENSOR, INPUT); // Setting Color Sensor frequency scaling to 20% digitalWrite(COLOR_S0,HIGH); digitalWrite(COLOR_S1,LOW); } //Ending setup fucntion void loop() { Serial.print("state = "); Serial.println(state); switch(state) { case START: controlFollowLine(); //FollowLine if (detectCheckpoint()) { forward(0, 0); delay(1000); state = WAIT; } break; case WAIT: // replace with wait for infared sonsor // while (!hasBox()) { // forward(0, 0); // delay(100); // } do { delay(100); } while (digitalRead(BOX_IR)); forward(pwm_l, pwm_r); delay(300); state = GO; // color = getBoxColor(); // if (color != -1) { // state = GO; // } else { // color = getBoxColor(); // } break; case GO: controlFollowLine(); //FollowLine if (detectCheckpoint()) { delay(100); ++count; } // count == counts to go for color if (count == goCheckpointCount(GREEN)) { // delay(250); count = 0; state = DROP_IN; } break; case DROP_IN: forward(0, 0); // Drop the box(es) while (digitalRead(SLDR_SW_TOP)) { analogWrite(PWM_SLDR, 120); digitalWrite(SLDR, HIGH); delay(100); } analogWrite(PWM_SLDR, 0); state = DROP_OUT; break; case DROP_OUT: while (digitalRead(SLDR_SW_BTM)) { analogWrite(PWM_SLDR, 120); digitalWrite(SLDR, LOW); delay(100); controlFollowLine(); } analogWrite(PWM_SLDR, 0); // // forward(pwm_l, pwm_r); // delay(300); state = BACK; break; case BACK: controlFollowLine(); //FollowLine if (detectCheckpoint()) { delay(100); ++count; } if (count == backCheckpointCount(color)) { state = WAIT; color = changeToNextColor(color); count = 0; } break; } // controlFollowLine(); //FollowLine // control_Sensor(); //Read Data From Sensor // Serial.print("SENSOR_T1 : "); // Serial.println(data_sensor_1); // Serial.print("SENSOR_T2 : "); // Serial.println(data_sensor_2); // Serial.print("SENSOR_T3 : "); // Serial.println(data_sensor_3); // Serial.print("SENSOR_T4 : "); // Serial.println(data_sensor_4); // Serial.print("SENSOR_T5 : "); // Serial.println(data_sensor_5); // Serial.print("SENSOR_T6 : "); // Serial.println((!data_sensor_6)); // Serial.print("SENSOR_T7 : "); // Serial.println(data_sensor_7); // Serial.println("-------------"); // delay(500); } //End_Loop //control_Sensor void control_Sensor() { //Line Sensor data_sensor_1 = digitalRead(SENSOR_T1); // PIN 22 data_sensor_2 = digitalRead(SENSOR_T2); // PIN 23 data_sensor_3 = digitalRead(SENSOR_T3); // PIN 24 data_sensor_4 = digitalRead(SENSOR_T4); // PIN 25 data_sensor_5 = digitalRead(SENSOR_T5); // PIN 26 data_sensor_6 = digitalRead(SENSOR_T6); // PIN 6 data_sensor_7 = digitalRead(SENSOR_T7); // PIN 7 } // TODO: SENSOR_T3 is not working must change the new once void controlFollowLine() { control_Sensor(); // always moving if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { forward(pwm_l, pwm_r); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 1) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 1) && (data_sensor_7 == 0)) { forward(pwm_l, pwm_r); } else if ((!data_sensor_6 == 1) && (data_sensor_1 == 0) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 0) && (data_sensor_7 == 1)) { forward(pwm_l, pwm_r); } else if ((!data_sensor_6 == 1) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 0) && (data_sensor_7 == 1)) { forward(pwm_l, pwm_r); } else if ((!data_sensor_6 == 1) && (data_sensor_1 == 0) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 1)) { forward(pwm_l, pwm_r); } else if ((!data_sensor_6 == 1) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 1) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 1)) { forward(pwm_l, pwm_r); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 0) && (data_sensor_7 == 1)) { forward(pwm_l, pwm_r); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 0) && (data_sensor_7 == 1)) { forward(pwm_l, pwm_r); } // turn right in line else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnRightZone(pwmTurn_l, pwmTurn_r); } // turn left in line else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnLeftZone(pwmTurn_l, pwmTurn_r); } // turn right at the uturn zone else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 1) && (data_sensor_7 == 0)) { uturnRightZone(pwmUturn_l - 5, pwmUturn_r - 5); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 1) && (data_sensor_7 == 0)) { uturnRightZone(pwmUturn_l, pwmUturn_r); delay(5); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 0) && (data_sensor_4 == 1)&& (data_sensor_5 == 1) && (data_sensor_7 == 0)) { uturnRightZone(pwmUturn_l, pwmUturn_r); delay(10); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 0) && (data_sensor_4 == 1)&& (data_sensor_5 == 1) && (data_sensor_7 == 1)) { uturnRightZone(pwmUturn_l - 5, pwmUturn_r - 5); delay(20); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 0) && (data_sensor_4 == 0)&& (data_sensor_5 == 1) && (data_sensor_7 == 0)) { uturnRightZone(pwmUturn_l, pwmUturn_r); delay(18); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 0) && (data_sensor_4 == 0)&& (data_sensor_5 == 1) && (data_sensor_7 == 1)) { uturnRightZone(pwmUturn_l + 13, pwmUturn_r + 25); delay(35); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 0) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 1)) { uturnRightZone(pwmUturn_l + 15, pwmUturn_r + 5); delay(40); } //turn left at the uturn zone else if ((!data_sensor_6 == 0) && (data_sensor_1 == 1) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnLeftZone(pwmUturn_l - 5, pwmUturn_r - 5); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 1) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnLeftZone(pwmUturn_l - 5, pwmUturn_r - 5); delay(5); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 1) && (data_sensor_2 == 1) && (data_sensor_3 == 0) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnLeftZone(pwmUturn_l, pwmUturn_r); delay(10); } else if ((!data_sensor_6 == 1) && (data_sensor_1 == 1) && (data_sensor_2 == 1) && (data_sensor_3 == 0) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnLeftZone(pwmUturn_l, pwmUturn_r); delay(20); } else if ((!data_sensor_6 == 0) && (data_sensor_1 == 1) && (data_sensor_2 == 0) && (data_sensor_3 == 0) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnLeftZone(pwmUturn_l, pwmUturn_r); delay(18); } else if ((!data_sensor_6 == 1) && (data_sensor_1 == 1) && (data_sensor_2 == 0) && (data_sensor_3 == 0) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnLeftZone(pwmUturn_l + 25, pwmUturn_r + 13); delay(35); } else if ((!data_sensor_6 == 1) && (data_sensor_1 == 0) && (data_sensor_2 == 0) && (data_sensor_3 == 0) && (data_sensor_4 == 0)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { uturnLeftZone(pwmUturn_l + 5, pwmUturn_r + 15); delay(40); } else { forward(0, 0); } //delay(100); } //end control follow line bool detectCheckpoint() { bool isAtCheckpoint = false; if(data_sensor_1 != last_state_sensor && data_sensor_2 != last_state_sensor && data_sensor_3 != last_state_sensor && data_sensor_4 != last_state_sensor && data_sensor_5 != last_state_sensor) { if(data_sensor_1 == 1 && data_sensor_2 == 1 && data_sensor_3 == 1 && data_sensor_4 == 1 && data_sensor_5 == 1) { isAtCheckpoint = true; // Serial.print("Line: "); // Serial.println(count_sensor); } } last_state_sensor = data_sensor_1 && data_sensor_2 && data_sensor_3 && data_sensor_4 && data_sensor_5; return isAtCheckpoint; } bool dropInTurnSucceed() { control_Sensor(); if ((!data_sensor_6 == 0) && (data_sensor_1 == 0) && (data_sensor_2 == 1) && (data_sensor_3 == 1) && (data_sensor_4 == 1)&& (data_sensor_5 == 0) && (data_sensor_7 == 0)) { return true; } return false; } void forward(int pwm_l, int pwm_r) { //left motor digitalWrite(DIR1, LOW); analogWrite(PWM1, pwm_l); //right motor digitalWrite(DIR2, LOW); analogWrite(PWM2, pwm_r); } // End forward void backward(int pwm_l, int pwm_r) { //left motor digitalWrite(DIR1, HIGH); analogWrite(PWM1, pwm_l); //right motor digitalWrite(DIR2, HIGH); analogWrite(PWM2, pwm_r); } // end backward void uturnLeftZone (int pwm_l, int pwm_r) { //left motor digitalWrite(DIR1, HIGH); analogWrite(PWM1, pwm_l); //right motor digitalWrite(DIR2, LOW); analogWrite(PWM2, pwm_r); } void uturnRightZone (int pwm_l, int pwm_r) { //left motor digitalWrite(DIR1, LOW); analogWrite(PWM1, pwm_l); //right motor digitalWrite(DIR2, HIGH); analogWrite(PWM2, pwm_r); } int goCheckpointCount(int color) { switch(color) { case GREEN: return 2; case BLUE: return 3; case RED: return 1; } } int backCheckpointCount(int color) { switch(color) { case GREEN: return 2; case BLUE: return 1; case RED: return 3; } } // change current box color int changeToNextColor(int color) { switch(color) { case GREEN: return RED; case RED: return BLUE; case BLUE: return GREEN; } } bool hasBox() { do { delay(100); } while (digitalRead(BOX_IR)); // bool hasBox = false; // int hb_count; // int i; // for (i = 0; i < 3; i++) { // if (hasBox == !digitalRead(BOX_IR)) { // hb_count++; // } else { // hb_count = 0; // hasBox = !digitalRead(BOX_IR); // } // delay(75); // } // // if (hb_count >= 3) { // return true; // } // // return false; } bool sliderOnTop() { bool onTop = false; int sldr_count = 0; int i; for (i = 0; i < 5; i++) { if (onTop == !digitalRead(SLDR_SW_TOP)) { sldr_count++; } else { onTop = !digitalRead(SLDR_SW_TOP); } delay(75); } if (count >= 3) { return true; } return false; } bool sliderOnBottom() { bool onBottom = false; int sldr_count = 0; int i; for (i = 0; i < 5; i++) { if (onBottom == !digitalRead(SLDR_SW_TOP)) { sldr_count++; } else { onBottom = !digitalRead(SLDR_SW_TOP); } delay(75); } if (count >= 3) { return true; } return false; } int getBoxColor() { // Stores frequency read by the photodiodes int redFrequency = 0; int greenFrequency = 0; int blueFrequency = 0; // Stores the red. green and blue colors int redColor = 0; int greenColor = 0; int blueColor = 0; int color = GREEN; int color_count = 0; int i; for(i = 0; i < 5; i++) { // Setting RED (R) filtered photodiodes to be read digitalWrite(COLOR_S2,LOW); digitalWrite(COLOR_S3,LOW); // Reading the output frequency redFrequency = pulseIn(COLOR_SENSOR, LOW); // Remaping the value of the RED (R) frequency from 0 to 255 // You must replace with your own values. Here's an example: redColor = map(redFrequency, 70, 120, 255,0); // redColor = map(redFrequency, XX, XX, 255,0); // Printing the RED (R) value // Serial.print("R = "); // Serial.print(redColor); delay(100); // Setting GREEN (G) filtered photodiodes to be read digitalWrite(COLOR_S2,HIGH); digitalWrite(COLOR_S3,HIGH); // Reading the output frequency greenFrequency = pulseIn(COLOR_SENSOR, LOW); // Remaping the value of the GREEN (G) frequency from 0 to 255 // You must replace with your own values. Here's an example: greenColor = map(greenFrequency, 100, 199, 255, 0); // greenColor = map(greenFrequency, XX, XX, 255, 0); // Printing the GREEN (G) value // Serial.print(" G = "); // Serial.print(greenColor); // Serial.print(greenFrequency); delay(100); // Setting BLUE (B) filtered photodiodes to be read digitalWrite(COLOR_S2,LOW); digitalWrite(COLOR_S3,HIGH); // Reading the output frequency blueFrequency = pulseIn(COLOR_SENSOR, LOW); // Remaping the value of the BLUE (B) frequency from 0 to 255 // You must replace with your own values. Here's an example: blueColor = map(blueFrequency, 38, 180, 255, 0); // blueColor = map(blueFrequency, XX, XX, 255, 0); // Printing the BLUE (B) value // Serial.print(" B = "); // Serial.print(blueColor); delay(100); // Checks the current detected color and prints // a message in the serial monitor if(redColor > greenColor && redColor > blueColor){ // Serial.println(" - RED detected!"); if (color == RED) { color_count++; } else { color_count = 0; color = RED; } }else if(greenColor > redColor && greenColor > blueColor){ // Serial.println(" - GREEN detected!"); if (color == GREEN) { color_count++; } else { color_count = 0; color = GREEN; } } else if(blueColor > redColor && blueColor > greenColor){ // Serial.println(" - BLUE detected!"); if (color == BLUE) { color_count++; } else { color_count = 0; color = BLUE; } } } if (color_count >= 3) { return color; } else { return -1; } } <file_sep>/Arduino/btn/btn.ino bool btn = 1; void setup() { // put your setup code here, to run once: pinMode(4, INPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: btn = digitalRead(4); Serial.println(btn); } <file_sep>/Arduino/LDR_TEST/LDR_TEST.ino #define led 7 int sensorReading; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(led, OUTPUT); } void loop() { // put your main code here, to run repeatedly: sensorReading = analogRead(0); if(sensorReading < 200){ digitalWrite(led, HIGH); }else{ digitalWrite(led, LOW); } Serial.println(sensorReading); delay(200); } <file_sep>/Arduino/challeng1_3/challeng1_3.ino #define button 7 int num = 0; int pin = 0; int countLED = 5; bool btnState = LOW; bool State = 0; void setup() { // put your setup code here, to run once: for(int i = 2; i <= countLED+1; i++){ pinMode(i, OUTPUT); } pinMode(button, INPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: btnState = digitalRead(button); while(btnState == LOW){ while(btnState == LOW){ btnState = digitalRead(button); } num++; Serial.print("num = "); Serial.println(num); pin = (num % (countLED + 1)) + 1; // pin = [2,3,4,5,6,1] Serial.println(pin); if(pin == 2){ digitalWrite(pin, HIGH); }else if(pin != 1){ digitalWrite(pin, HIGH); digitalWrite(pin-1, LOW); }else{ digitalWrite(pin+countLED, LOW); } } } <file_sep>/Arduino/motortest2/motortest2.ino // left wheel #define OUT1 6 #define OUT2 7 #define ENA 3 // right wheel #define OUT3 8 #define OUT4 5 #define ENB 9 void setup() { // put your setup code here, to run once: pinMode(OUT1, OUTPUT); pinMode(OUT2, OUTPUT); pinMode(OUT3, OUTPUT); pinMode(OUT4, OUTPUT); pinMode(ENA, OUTPUT); pinMode(ENB, OUTPUT); analogWrite(ENA, 150); analogWrite(ENB, 150); } void loop() { // put your main code here, to run repeatedly: moveForward(); } void moveForward() { digitalWrite(OUT1, LOW); digitalWrite(OUT2, HIGH); digitalWrite(OUT3, LOW); digitalWrite(OUT4, HIGH); } <file_sep>/Arduino/servotest/servotest.ino #include<Servo.h> Servo servo; int pos = 0; int StateBTN ; #define button 2 void setup() { // put your setup code here, to run once: servo.attach(9, 500, 2500); pinMode(button, INPUT); Serial.begin(9600); servo.writeMicroseconds(1500); } void loop() { // put your main code here, to run repeatedly: //StateBTN = digitalRead(button); //Serial.print("StateBTN = "); //Serial.println(StateBTN); //delay(100); //if(StateBTN == HIGH){ // servo.writeMicroseconds(1700); //} // //if(StateBTN == LOW){ // servo.writeMicroseconds(1500); // Serial.print("degree = "); // Serial.println(servo.read(), DEC); //} //servo.writeMicroseconds(1800); //delay(2000); //servo.write(-90); //delay(1000); //servo.write(0); //delay(1000); //servo.write(90); //delay(1000); servo.write(30); delay(2000); servo.write(-30); delay(2000) } <file_sep>/Arduino/sketch_oct03b/sketch_oct03b.ino #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); #define TRIG 5 #define ECHO 6 #define led 10 long duration; int distance; int count = 0; int previous ; int State = LOW; void setup(){ Serial.begin(9600); lcd.begin(16, 2); lcd.setCursor(0, 0); lcd.print("No. of customer"); pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT); pinMode(led, OUTPUT); } void readUltrasonic(){ digitalWrite(TRIG, LOW); delayMicroseconds(2); digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG, LOW); //distance = pulseIn(ECHO, HIGH)/58.2; duration = pulseIn(ECHO, HIGH); distance = duration * 0.034 / 2; //previous = distance; } void loop(){ readUltrasonic(); //tone(8, 2000, 150); //delay(100); //tone(8, 1000, 50); do{ readUltrasonic(); if(distance < 15 && previous >= 15){ count = count + 1; digitalWrite(led, HIGH); } Serial.print("Distance: "); Serial.print(distance); Serial.println(" cm"); delay(100); previous = distance; }while(distance < 15); digitalWrite(led, LOW); lcd.setCursor(4,1); lcd.print(count); // Serial.print("Count: "); // Serial.println(count); // delay(200); } <file_sep>/Arduino/libraries/firebase-arduino-master/examples/Firebase_ESP8266_LEDs/Firebase_ESP8266_Neopixel/Firebase_ESP8266_Neopixel.ino // // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Firebase_ESP8266-Neopixel is a sample that demonstrates how // to set pixel data using a firebase stream. #include <Firebase.h> #include <ArduinoJson.h> #include <ESP8266WiFi.h> #include <Adafruit_NeoPixel.h> #include "colors_ext.h" const int PIN=13; Adafruit_NeoPixel strip = Adafruit_NeoPixel(32, PIN, NEO_GRB + NEO_KHZ800); #define JSON_BUFFER_SIZE 10*4 // TODO: Replace with your own credentials and keep these safe. Firebase fbase = Firebase("YOUR-PROJECT.firebaseio.com") .auth("YOUR_AUTH_SECRET"); void setup() { Serial.begin(9600); strip.begin(); strip.setBrightness(25); // 0 ... 255 strip.show(); // Initialize all pixels to 'off' // Not connected, set the LEDs red colorWipe(&strip, 0xFF0000, 50); // connect to wifi. WiFi.begin("GoogleGuest", ""); Serial.print("connecting"); int count = 0; while (WiFi.status() != WL_CONNECTED) { // Draw rainbows while connecting Serial.print("."); if (count < strip.numPixels()){ strip.setPixelColor(count++, Wheel(&strip, count * 8)); strip.show(); } delay(20); } Serial.println(); Serial.print("connected: "); Serial.println(WiFi.localIP()); // Connected, set the LEDs green colorWipe(&strip, 0x00FF00, 50); } void loop() { // Get all entries. // TODO: Replace with streaming FirebaseGet get = fbase.get("/rgbdata"); if (get.error()) { Serial.println("Firebase get failed"); Serial.println(get.error().message()); return; } // Use dynamic for large JSON objects // DynamicJsonBuffer jsonBuffer; StaticJsonBuffer<JSON_OBJECT_SIZE(JSON_BUFFER_SIZE)> jsonBuffer; // create an empty object String ref = get.json(); Serial.println(ref); JsonObject& pixelJSON = jsonBuffer.parseObject((char*)ref.c_str()); if(pixelJSON.success()){ for (int i=0; i < strip.numPixels(); i++) { String pixelAddress = "pixel" + String(i); String pixelVal = pixelJSON[pixelAddress]; Serial.println(pixelVal); strip.setPixelColor(i, pixelVal.toInt()); } strip.show(); } else { Serial.println("Parse fail."); Serial.println(get.json()); } } <file_sep>/Arduino/i2cmaster_test/i2cmaster_test.ino #include<Wire.h> #define SLAVE_ADDR 10 String response = ""; byte bval; void setup() { // put your setup code here, to run once: Wire.begin(); Serial.begin(9600); } byte readFromSlave(){ Wire.requestFrom(SLAVE_ADDR, 6); if(Wire.available() != 0){ Serial.print("."); } Serial.println(""); bval = Wire.read(); Serial.println(bval); } void loop() { // put your main code here, to run repeatedly: delay(1000); Serial.print("data From Slave = "); Serial.println(readFromSlave()); } <file_sep>/Arduino/manual/manual.ino #include <Arduino.h> #include <PS2X_lib.h> //for v1.6 #include <Servo.h> #define SERVO 9 // left wheel #define OUT1 2 #define OUT2 3 #define ENA 6 // right wheel #define OUT3 4 #define OUT4 5 #define ENB 7 #define ACT_OUT1 22 #define ACT_OUT2 24 #define ACT_ENA 26 /****************************************************************** * set pins connected to PS2 controller: * - 1e column: original * - 2e colmun: Stef? * replace pin numbers by the ones you use ******************************************************************/ #define PS2_DAT 13 #define PS2_CMD 11 #define PS2_SEL 10 #define PS2_CLK 12 /****************************************************************** * select modes of PS2 controller: * - pressures = analog reading of push-butttons * - rumble = motor rumbling * uncomment 1 of the lines for each mode selection ******************************************************************/ #define pressures false #define rumble false Servo myservo; // create servo object to control a servo int pos;// variable to rotate the servo int add; PS2X ps2x; // create PS2 Controller Class //right now, the library does NOT support hot pluggable controllers, meaning //you must always either restart your Arduino after you connect the controller, //or call config_gamepad(pins) again after connecting the controller. int error = 0; byte type = 0; byte vibrate = 0; void setup() { Serial.begin(57600); myservo.attach(SERVO); myservo.write(90); pinMode(OUT1, OUTPUT); pinMode(OUT2, OUTPUT); pinMode(OUT3, OUTPUT); pinMode(OUT4, OUTPUT); pinMode(ENA, OUTPUT); pinMode(ENB, OUTPUT); pinMode(ACT_OUT1, OUTPUT); pinMode(ACT_OUT2, OUTPUT); pinMode(ACT_ENA, OUTPUT); analogWrite(ENA, 180); analogWrite(ENB, 255); analogWrite(ACT_ENA, 255); delay(300); //added delay to give wireless ps2 module some time to startup, before configuring it //CHANGES for v1.6 HERE!!! **************PAY ATTENTION************* //setup pins and settings: GamePad(clock, command, attention, data, Pressures?, Rumble?) check for error error = ps2x.config_gamepad(PS2_CLK, PS2_CMD, PS2_SEL, PS2_DAT, pressures, rumble); if(error == 0){ Serial.print("Found Controller, configured successful "); Serial.print("pressures = "); if (pressures) Serial.println("true "); else Serial.println("false"); Serial.print("rumble = "); if (rumble) Serial.println("true)"); else Serial.println("false"); Serial.println("Try out all the buttons, X will vibrate the controller, faster as you press harder;"); Serial.println("Note: Go to www.billporter.info for updates and to report bugs."); } else if(error == 1) Serial.println("No controller found, check wiring, see readme.txt to enable debug. visit www.billporter.info for troubleshooting tips"); else if(error == 2) Serial.println("Controller found but not accepting commands. see readme.txt to enable debug. Visit www.billporter.info for troubleshooting tips"); else if(error == 3) Serial.println("Controller refusing to enter Pressures mode, may not support it. "); // Serial.print(ps2x.Analog(1), HEX); // type = ps2x.readType(); // switch(type) { // case 0: // Serial.print("Unknown Controller type found "); // break; // case 1: // Serial.print("DualShock Controller found "); // break; // case 2: // Serial.print("GuitarHero Controller found "); // break; // case 3: // Serial.print("Wireless Sony DualShock Controller found "); // break; // } } void loop() { /* You must Read Gamepad to get new values and set vibration values ps2x.read_gamepad(small motor on/off, larger motor strenght from 0-255) if you don't enable the rumble, use ps2x.read_gamepad(); with no values You should call this at least once a second */ if(error == 1) //skip loop if no controller found return; ps2x.read_gamepad(false, vibrate); //read controller and set large motor to spin at 'vibrate' speed // Digital Reading // ps2x.Button(PSB_BUTTON) // Anaglog Reading // ps2x.Analog(PSAB_BUTTON) // convert analog signal to Decimal number when print, eg. Serial.println(ps2x.Analog(PSAB_BUTTON), DEC); // Using ButtonPressed, NewButtonState, ButonReleased // if(ps2x.ButtonPressed(PSB_CIRCLE)) //will be TRUE if button was JUST pressed // Serial.println("Circle just pressed"); // if(ps2x.NewButtonState(PSB_CROSS)) //will be TRUE if button was JUST pressed OR released // Serial.println("X just changed"); // if(ps2x.ButtonReleased(PSB_SQUARE)) //will be TRUE if button was JUST released // Buttons reading // ps2x.Button(PSB_START) ps2x.Button(PSB_SELECT) // ps2x.Button(PSB_PAD_UP) ps2x.Button(PSB_PAD_LEFT) ps2x.Button(PSB_PAD_DOWN) ps2x.Button(PSB_PAD_RIGHT) // ps2x.Button(PSB_TRIANGLE) ps2x.Button(PSB_SQUARE) ps2x.Button(PSB_CROSS) ps2x.Button(PSB_CIRCLE) // ps2x.Button(PSB_L1) ps2x.Button(PSB_L2) ps2x.Button(PSB_L3) ps2x.Button(PSB_R1) ps2x.Button(PSB_R2) ps2x.Button(PSB_R3) // Sticcks reading (Analog only) // ps2x.Analog(PSS_LY) Left stick, Y axis // ps2x.Analog(PSS_LX) Left stick, X axis // ps2x.Analog(PSS_RY) Right stick, Y axis // ps2x.Analog(PSS_RX) Right stick, X axis // to print value, convert to DEC first eg. Serial.println(ps2x.Analog(PSS_LY), DEC); // default: stop moveStop(); actuatorStop(); if(ps2x.Button(PSB_START)) { Serial.println("START"); } if(ps2x.Button(PSB_SELECT)) { Serial.println("SELECT"); } if(ps2x.Button(PSB_PAD_UP)) { Serial.println("UP"); analogWrite(ENA, 220); analogWrite(ENB, 255); moveForward(); } if(ps2x.Button(PSB_PAD_DOWN)) { Serial.println("DOWN"); analogWrite(ENA, 230); analogWrite(ENB, 255); moveBackward(); } if(ps2x.Button(PSB_PAD_LEFT)) { Serial.println("LEFT"); turnLeft(); } if(ps2x.Button(PSB_PAD_RIGHT) ) { Serial.println("RIGHT"); turnRight(); } if(ps2x.Button(PSB_TRIANGLE)) { Serial.println("/_\\"); actuatorBackward(); } if(ps2x.Button(PSB_SQUARE)) { Serial.println("[]"); servoCatch(); // Serial.println(myservo.read(), DEC); // while(ps2x.Button(PSB_SQUARE)) { // if ((myservo.read()-1) >= 0) { // myservo.write(myservo.read()-1); // } // } // delay(15); } if(ps2x.Button(PSB_CROSS)) { Serial.println("X"); actuatorForward(); } if(ps2x.Button(PSB_CIRCLE)) { Serial.println("O"); servoRelease(); // Serial.println(myservo.read(), DEC); // while(ps2x.Button(PSB_CIRCLE)) { // if ((myservo.read()+1) <= 180) { // myservo.write(myservo.read()+1); // } // } } if(ps2x.Button(PSB_L1)) { Serial.println("L1"); } if(ps2x.Button(PSB_L2)) { Serial.println("L2"); } if(ps2x.Button(PSB_L3)) { Serial.println("L3"); } if(ps2x.Button(PSB_R1)) { Serial.println("R1"); } if(ps2x.Button(PSB_R2)) { Serial.println("R2"); } if(ps2x.Button(PSB_R3)) { Serial.println("R3"); } // if ((ps2x.Analog(PSS_LY) != 127) || (ps2x.Analog(PSS_LX) != 128) || (ps2x.Analog(PSS_RY) != 127) || (ps2x.Analog(PSS_RX) != 128)) { // Serial.print("("); // Serial.print(ps2x.Analog(PSS_LY)); // Serial.print(", "); // Serial.print(ps2x.Analog(PSS_LX), DEC); // Serial.print(", "); // Serial.print(ps2x.Analog(PSS_RY), DEC); // Serial.print(", "); // Serial.print(ps2x.Analog(PSS_RX), DEC); // Serial.println(")"); // } delay(15); } void turnLeft() { digitalWrite(OUT1, HIGH); digitalWrite(OUT2, LOW); digitalWrite(OUT3, LOW); digitalWrite(OUT4, HIGH); } void turnRight() { digitalWrite(OUT1, LOW); digitalWrite(OUT2, HIGH); digitalWrite(OUT3, HIGH); digitalWrite(OUT4, LOW); } void moveForward() { digitalWrite(OUT1, LOW); digitalWrite(OUT2, HIGH); digitalWrite(OUT3, LOW); digitalWrite(OUT4, HIGH); } void moveBackward() { digitalWrite(OUT1, HIGH); digitalWrite(OUT2, LOW); digitalWrite(OUT3, HIGH); digitalWrite(OUT4, LOW); } void moveStop() { digitalWrite(OUT1, LOW); digitalWrite(OUT2, LOW); digitalWrite(OUT3, LOW); digitalWrite(OUT4, LOW); } void actuatorForward() { digitalWrite(ACT_OUT1, HIGH); digitalWrite(ACT_OUT2, LOW); } void actuatorBackward() { digitalWrite(ACT_OUT1, LOW); digitalWrite(ACT_OUT2, HIGH); } void actuatorStop() { digitalWrite(ACT_OUT1, LOW); digitalWrite(ACT_OUT2, LOW); } void servoCatch() { pos = 0; myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } void servoRelease() { pos = 180; myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } <file_sep>/Arduino/AutoVersionArduino/AutoVersionArduino.ino #define MOTOR_A_DIR 2 #define MOTOR_B_DIR 3 #define MOTOR_C_DIR 4 #define MOTOR_D_DIR 5 #define MOTOR_A_PWM 6 #define MOTOR_B_PWM 7 #define MOTOR_C_PWM 8 #define MOTOR_D_PWM 9 void setup(){ Serial.begin(9600); pinMode(MOTOR_A_DIR, OUTPUT); pinMode(MOTOR_B_DIR, OUTPUT); pinMode(MOTOR_C_DIR, OUTPUT); pinMode(MOTOR_D_DIR, OUTPUT); pinMode(MOTOR_A_PWM, OUTPUT); pinMode(MOTOR_B_PWM, OUTPUT); pinMode(MOTOR_C_PWM, OUTPUT); pinMode(MOTOR_D_PWM, OUTPUT); } void loop(){ MoveForward(); delay(2000); AllMotorStop(); delay(1000); MoveBackward(); delay(2000); AllMotorStop(); delay(1000); TurnLeft(); delay(2000); AllMotorStop(); delay(1000); TurnRight(); delay(2000); AllMotorStop(); delay(1000); } void MoveForward(){ digitalWrite(MOTOR_A_DIR, LOW); digitalWrite(MOTOR_B_DIR, LOW); analogWrite(MOTOR_A_PWM, 180); analogWrite(MOTOR_B_PWM, 180); } void MoveBackward(){ digitalWrite(MOTOR_A_DIR, HIGH); digitalWrite(MOTOR_B_DIR, HIGH); analogWrite(MOTOR_A_PWM, 180); analogWrite(MOTOR_B_PWM, 180); } void TurnLeft(){ digitalWrite(MOTOR_C_DIR, HIGH); digitalWrite(MOTOR_D_DIR, HIGH); analogWrite(MOTOR_C_PWM, 180); analogWrite(MOTOR_D_PWM, 180); } void TurnRight(){ digitalWrite(MOTOR_C_DIR, LOW); digitalWrite(MOTOR_D_DIR, LOW); analogWrite(MOTOR_C_PWM, 180); analogWrite(MOTOR_D_PWM, 180); } void RotateLeft(){ digitalWrite(MOTOR_A_DIR, LOW); digitalWrite(MOTOR_B_DIR, LOW); digitalWrite(MOTOR_C_DIR, LOW); digitalWrite(MOTOR_D_DIR, LOW); } void RotateRight(){ digitalWrite(MOTOR_A_DIR, HIGH); digitalWrite(MOTOR_B_DIR, HIGH); digitalWrite(MOTOR_C_DIR, HIGH); digitalWrite(MOTOR_D_DIR, HIGH); } void AllMotorStop(){ analogWrite(MOTOR_A_PWM, 0); analogWrite(MOTOR_B_PWM, 0); analogWrite(MOTOR_C_PWM, 0); analogWrite(MOTOR_D_PWM, 0); } <file_sep>/Arduino/m3/m3.ino #define DIR1 2 #define PWM1 3 #define DIR2 4 #define PWM2 5 void setup() { // put your setup code here, to run once: pinMode(DIR1, OUTPUT); pinMode(PWM1 , OUTPUT); pinMode(DIR2, OUTPUT); pinMode(PWM2, OUTPUT); } void loop() { // put your main code here, to run repeatedly: digitalWrite(DIR1, HIGH); analogWrite(PWM1, 255); digitalWrite(DIR2, HIGH); analogWrite(PWM2, 255); } <file_sep>/Arduino/led7/led7.ino int dl = 100; void setup() { // put your setup code here, to run once: for(int i = 2; i <= 7; i++){ pinMode(i, OUTPUT); } } void loop() { // put your main code here, to run repeatedly: for(int i = 2; i <= 7; i++){ digitalWrite(i, HIGH); delay(dl); digitalWrite(i, LOW); delay(dl); } for(int i = 7; i >= 2; i--){ digitalWrite(i, HIGH); delay(dl); digitalWrite(i, LOW); delay(dl); } digitalWrite(2, HIGH); delay(dl); } <file_sep>/Arduino/UltraLED/UltraLED.ino //#define button 8 #define TRIG 9 #define ECHO 10 int buzzer=11; int num = 0; int pin; int countLED = 6; bool StateBTN = LOW; bool State = 0; int distance; int duration; void setup() { // put your setup code here, to run once: for(int i = 2; i <= countLED+1; i++){ pinMode(i, OUTPUT); } // pinMode(button, INPUT); pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT); pinMode(buzzer, OUTPUT); Serial.begin(9600); } bool readUltrasonic(){ digitalWrite(TRIG, LOW); delayMicroseconds(2); digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG, LOW); //distance = pulseIn(ECHO, HIGH)/58.2; duration = pulseIn(ECHO, HIGH); distance = duration * 0.034 / 2; Serial.print("Distance: "); Serial.print(distance); Serial.println(" cm"); delay(100); if( distance < 20){ return HIGH; }else{ return LOW; } } void loop() { // put your main code here, to run repeatedly: StateBTN = readUltrasonic(); while(StateBTN == LOW){ while(StateBTN == LOW){ StateBTN = readUltrasonic(); } analogWrite(buzzer,100); delay(400); analogWrite(buzzer,0); delay(400); num++; Serial.print("num = "); Serial.println(num); pin = (num % (countLED + 1)) + 1; // pin = [2,3,4,5,6,1] Serial.println(pin); if(pin == 2){ digitalWrite(pin, HIGH); }else if(pin != 1){ digitalWrite(pin, HIGH); digitalWrite(pin-1, LOW); }else{ digitalWrite(pin+countLED, LOW); } } } <file_sep>/Arduino/esp32wifi/esp32wifi.ino #include <WiFi.h> #include <IOXhop_FirebaseESP32.h> // Set these to run example. #define FIREBASE_HOST "smart-farm-3ef1a.firebaseio.com" #define FIREBASE_AUTH "<KEY>" #define WIFI_SSID "vivo 1718" #define WIFI_PASSWORD "<PASSWORD>" #define LIGHT 36 void setup() { Serial.begin(9600); pinMode(LIGHT, INPUT); // connect to wifi. WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("connecting"); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.print("connected: "); Serial.println(WiFi.localIP()); Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); } void loop() { // set value Firebase.setInt("LIGHT", analogRead(LIGHT)); // handle error if (Firebase.failed()) { Serial.print("setting /LIGHT failed:"); Serial.println(Firebase.error()); return; } // get value Serial.println("LIGHT: " + String(Firebase.getInt("LIGHT"))); delay(1000); } <file_sep>/Arduino/esp8266wifi/esp8266wifi.ino #include<ESP8266WiFi.h> #define SSID_NAME "CEIT-IoT " #define SSID_PASS "<PASSWORD>" //IPAddress staticIP(192,168,1,2); //IPAddress gateway(192,168,1,1); //IPAddress subnet(255,255,255,0); void setup() { // put your setup code here, to run once: Serial.begin(115200); Serial.println(); Serial.println(); WiFi.begin(SSID_NAME, SSID_PASS); // WiFi.config(staticIP, gateway, subnet); Serial.print("Connecting"); while(WiFi.status() != WL_CONNECTED){ delay(500); Serial.print("."); } Serial.println(); Serial.print("Connected, IP address: "); Serial.println(WiFi.localIP()); } void loop() { // put your main code here, to run repeatedly: } <file_sep>/Arduino/Ultrasonic_on_off_led/Ultrasonic_on_off_led.ino #define TRIG 5 #define ECHO 6 #define led 4 long duration; int distance; int previous; int State = 1; int State1 = LOW; void setup(){ Serial.begin(9600); pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT); pinMode(led, OUTPUT); } bool readUltrasonic(){ digitalWrite(TRIG, LOW); delayMicroseconds(2); digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG, LOW); //distance = pulseIn(ECHO, HIGH)/58.2; duration = pulseIn(ECHO, HIGH); distance = duration * 0.034 / 2; Serial.print("Distance: "); Serial.print(distance); Serial.println(" cm"); delay(100); if( distance < 15){ return HIGH; }else{ return LOW; } } void loop(){ // Ultrasonic Started State = readUltrasonic(); if(State == HIGH && previous == LOW){ State1 = !State1; } digitalWrite(led, State1); previous = State; } <file_sep>/Arduino/libraries/firebase-arduino-master/examples/Firebase_ESP8266_LEDs/Firebase_ESP8266_Neopixel/colors_ext.h // The following methods are extracted from the Adafruit Neopixel example, strandtest. // https://github.com/adafruit/Adafruit_NeoPixel #ifndef COLORS_EXT_H #define COLORS_EXT_H // Input a value 0 to 255 to get a color value. // The colours are a transition r - g - b - back to r. uint32_t Wheel(Adafruit_NeoPixel* strip, byte WheelPos) { WheelPos = 255 - WheelPos; if(WheelPos < 85) { return strip->Color(255 - WheelPos * 3, 0, WheelPos * 3); } if(WheelPos < 170) { WheelPos -= 85; return strip->Color(0, WheelPos * 3, 255 - WheelPos * 3); } WheelPos -= 170; return strip->Color(WheelPos * 3, 255 - WheelPos * 3, 0); } // Fill the dots one after the other with a color void colorWipe(Adafruit_NeoPixel* strip, uint32_t c, uint8_t wait) { for(uint16_t i=0; i<strip->numPixels(); i++) { strip->setPixelColor(i, c); strip->show(); delay(wait); } } void rainbow(Adafruit_NeoPixel* strip, uint8_t wait) { uint16_t i, j; for(j=0; j<256; j++) { for(i=0; i<strip->numPixels(); i++) { strip->setPixelColor(i, Wheel(strip, (i+j) & 255)); } strip->show(); delay(wait); } } // Slightly different, this makes the rainbow equally distributed throughout void rainbowCycle(Adafruit_NeoPixel* strip, uint8_t wait) { uint16_t i, j; for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel for(i=0; i< strip->numPixels(); i++) { strip->setPixelColor(i, Wheel(strip, ((i * 256 / strip->numPixels()) + j) & 255)); } strip->show(); delay(wait); } } //Theatre-style crawling lights. void theaterChase(Adafruit_NeoPixel* strip, uint32_t c, uint8_t wait) { for (int j=0; j<10; j++) { //do 10 cycles of chasing for (int q=0; q < 3; q++) { for (int i=0; i < strip->numPixels(); i=i+3) { strip->setPixelColor(i+q, c); //turn every third pixel on } strip->show(); delay(wait); for (int i=0; i < strip->numPixels(); i=i+3) { strip->setPixelColor(i+q, 0); //turn every third pixel off } } } } //Theatre-style crawling lights with rainbow effect void theaterChaseRainbow(Adafruit_NeoPixel* strip, uint8_t wait) { for (int j=0; j < 256; j++) { // cycle all 256 colors in the wheel for (int q=0; q < 3; q++) { for (int i=0; i < strip->numPixels(); i=i+3) { strip->setPixelColor(i+q, Wheel(strip, (i+j) % 255)); //turn every third pixel on } strip->show(); delay(wait); for (int i=0; i < strip->numPixels(); i=i+3) { strip->setPixelColor(i+q, 0); //turn every third pixel off } } } } #endif <file_sep>/Arduino/string2/string2.ino int num = 2; char str[] = "test"; // create a string char out_str[40]; // output from string functions placed here // general purpose integer int n = 0; String fileName = String("test"); void setup() { Serial.begin(9600); } void loop() { num++; String number = String(num); fileName = String("test" + number + ".csv"); Serial.println(fileName); delay(1000); } <file_sep>/Arduino/i2cmaster/i2cmaster.ino // include Arduino Wire for i2c #include<Wire.h> //Define Slave i2c Address #define SLAVE_ADDR 8 // Define Slave answer size #define ANSWERSIZE 20 char b; void setup() { // put your setup code here, to run once: Wire.begin(); Serial.begin(9600); Serial.println("I2C Master Demonstration"); } void loop() { // put your main code here, to run repeatedly: delay(5); Serial.println("Write data from Slave"); // Write charactre from the Slave Wire.beginTransmission(SLAVE_ADDR); Wire.write(0); Wire.endTransmission(); Serial.println("Receive Data"); //Read response from Slave // Read back 5 characters Wire.requestFrom(SLAVE_ADDR, ANSWERSIZE); // Add characters to String String response = ""; while(Wire.available()){ b = Wire.read(); response += b; } // print to Serial Monitor Serial.println(response); delay(100); } <file_sep>/Arduino/esp32_firebase/esp32_firebase.ino #include <WiFi.h> #include <IOXhop_FirebaseESP32.h> #include <DHT.h> // Set these to run example. #define FIREBASE_HOST "smart-farm-3ef1a.firebaseio.com" #define FIREBASE_AUTH "<KEY>" #define WIFI_SSID "XLGO-0AF7" #define WIFI_PASSWORD "<PASSWORD>" //#define WIFI_SSID "M2_Core" //#define WIFI_PASSWORD "<PASSWORD>" #define DHTPIN 23 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); void setup() { Serial.begin(9600); // connect to wifi. WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("connecting"); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.print("connected: "); Serial.println(WiFi.localIP()); Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); dht.begin(); } void CheckWiFi(){ while(WiFi.status() != WL_CONNECTED) { Serial.println("WiFi not connected!"); delay(1000); } } void loop() { delay(2000); // float t = dht.readTemperature(); // float h = dht.readHumidity(); // Serial.println(t , h); // set value // Firebase.setFloat("temp", t); // Firebase.setFloat("humid", h); // handle error if (Firebase.failed()) { Serial.print("setting /temp & humid failed:"); Serial.println(Firebase.error()); return; } delay(1000); // get value Serial.print("temperature: "); Serial.println(Firebase.getFloat("temp")); Serial.print("humidity: "); Serial.println(Firebase.getFloat("humid")); CheckWiFi(); } <file_sep>/Arduino/libraries/firebase-arduino-master/examples/Firebase_ESP8266_LEDs/www/README.md # Firebase Neopixel Web demo # This demo console shows you how to synchronize data from the web to a device. ## Installation ## The demo uses [Bower](http://bower.io/) and [Polymer](http://www.polymer-project.org/) to simplify the UI and dependencies of the project. For Bower, you need to install [Node.js](http://nodejs.org/). After node is installed, install the Bower package by calling: `npm install -g bower` After Bower is installed, you are ready to update the project dependencies with Bower by running: `bower install` With the dependencies set, serve the www folder from a web server. For example, you can use the Python Simple HTTP server module by running: `python -m SimpleHTTPServer [port]` With the web server running, navigate to /web-demo.html and you should see the demo load. <file_sep>/Arduino/sdcardClockModule/sdcardClockModule.ino #include <SD.h> #include <virtuabotixRTC.h> //Library used #define D5 6 #define D6 7 #define D7 8 virtuabotixRTC myRTC(D5, D6, D7); //Connect VCC with 5V in the Arduino. //Then, connect the GND of SD card to the ground of Arduino. //Connect CS to pin 4 //Connect SCK to pin 13 //MOSI connect to the pin 11 //Lastly, connect MISO to pin 12 File myFile; // สร้างออฟเจค File สำหรับจัดการข้อมูล String fileName ="test4.csv"; String number; int num = 21; int exit1 = 0; const int chipSelect = 4; //====================== #include "DHT.h" #define DHTPIN 2 #define DHTTYPE DHT22 DHT dht(DHTPIN, DHTTYPE); int n = 0; void setup() { // myRTC.setDS1302Time(00, 30, 23, 1, 16, 11, 2019); Serial.begin(9600); Serial.println(F("DHTxx test!")); dht.begin(); connect2sdcard(); // write2file(fileName); // writeallfile(); // readfile(fileName); readallfile(); } void connect2sdcard(){ Serial.begin(9600); while (!Serial) { ; // รอจนกระทั่งเชื่อมต่อกับ Serial port แล้ว (สำหรับ Arduino Leonardo เท่านั้น) } Serial.print("Initializing SD card..."); pinMode(SS, OUTPUT); // Slave select ตัว library มันจะขอให้เป็น OUTPUT เสมอ if (!SD.begin(chipSelect)) { Serial.println("initialization failed!"); return; } Serial.println("initialization done."); // SD.remove(fileName); //ถ้าต้องการลบไฟล์ทิ้ง } void readfile(String filename){ // เปิดไฟล์เพื่ออ่าน ================================== myFile = SD.open(filename); // สั่งให้เปิดไฟล์ชื่อ cmlog.txt เพื่ออ่านข้อมูล if (myFile) { Serial.println(filename + ":"); // อ่านข้อมูลทั้งหมดออกมา while (myFile.available()) { Serial.write(myFile.read()); } exit1 = 0; myFile.close(); // เมื่ออ่านเสร็จ ปิดไฟล์ } else { // ถ้าอ่านไม่สำเร็จ ให้แสดง error Serial.println("error opening " + filename); exit1 = 1; } } //*************************************** void write2file(String filename){ // ถ้าเปิดไฟล์สำเร็จ ให้เขียนข้อมูลเพิ่มลงไป myFile = SD.open(filename, FILE_WRITE); if (myFile) { Serial.println("Writing to " + filename + "..."); myFile.println("save data to SD Card"); // เปิดไฟล์ที่ชื่อ fileName เพื่อเขียนข้อมูล โหมด FILE_WRITE =========================== myFile = SD.open(filename, FILE_WRITE); myRTC.updateTime(); Serial.print("Current Date / Time: "); Serial.print(myRTC.dayofmonth); //You can switch between day and month if you're using American system Serial.print("/"); Serial.print(myRTC.month); Serial.print("/"); Serial.print(myRTC.year); Serial.print(" "); Serial.print(myRTC.hours); Serial.print(":"); Serial.print(myRTC.minutes); Serial.print(":"); Serial.println(myRTC.seconds); myFile.println(""); myFile.print("===> Current Time: "); myFile.print(myRTC.hours); myFile.print(":"); myFile.print(myRTC.minutes); myFile.print(":"); myFile.println(myRTC.seconds); myFile.println(""); do{ delay(2000); float h = dht.readHumidity(); float t = dht.readTemperature(); float f = dht.readTemperature(true); // Check if any reads failed and exit early (to try again). if (isnan(h) || isnan(t) || isnan(f)) { Serial.println(F("Failed to read from DHT sensor!")); return; } // Compute heat index in Fahrenheit (the default) float hif = dht.computeHeatIndex(f, h); // Compute heat index in Celsius (isFahreheit = false) float hic = dht.computeHeatIndex(t, h, false); Serial.print(n); Serial.print(".) "); Serial.print(F("Humidity: ")); Serial.print(h); Serial.print(F("% Temperature: ")); Serial.print(t); Serial.print(F("°C ")); Serial.print(f); Serial.print(F("°F Heat index: ")); Serial.print(hic); Serial.print(F("°C ")); Serial.print(hif); Serial.println(F("°F")); myFile.print(n); myFile.print(","); myFile.print(h); myFile.print(","); myFile.print(t); myFile.print(","); myFile.print(f); myFile.print(","); myFile.print(hic); myFile.print(","); myFile.println(hif); n++; }while(n <= 1000); n = 0; myFile.close(); // ปิดไฟล์ Serial.println("done."); } else { // ถ้าเปิดไฟลืไม่สำเร็จ ให้แสดง error Serial.println("error opening "+filename); } } void readallfile(){ do{ number = String(num); fileName = String("test" + number + ".csv"); Serial.println(fileName); readfile(fileName); //SD.remove(fileName); num++; Serial.print("exit1 = "); Serial.println(exit1); }while(num <= 102 ); Serial.println("end---------"); } void writeallfile(){ do{ number = String(num); fileName = String("test" + number + ".csv"); Serial.println(fileName); write2file(fileName); num++; }while(num <= 102); Serial.println("end---------"); } void loop() { } <file_sep>/Arduino/joe/joe.ino #include <LiquidCrystal.h> // initialize the library with the numbers of the interface pins LiquidCrystal lcd(12, 11, 5, 4, 3, 2); int ledPin = 13; int pirPin = 10; int pirState = LOW; // we start, assuming no motion detected int val = 0; // variable for reading the pin status int counter = 0; int currentState = 0; int previousState = 0; void setup() { pinMode(ledPin, OUTPUT); // declare LED as output pinMode(pirPin, INPUT); // declare sensor as input lcd.begin(16, 2); lcd.setCursor(0, 0); lcd.print("No. of customer"); Serial.begin(9600); } void loop(){ val = digitalRead(pirPin); // read PIR sensor input value if(val == HIGH && previousState == LOW){ counter = counter + 1; lcd.setCursor(4,1); lcd.print(counter); } digitalWrite(ledPin, val); previousState = val; } <file_sep>/Arduino/netpie2020_led/netpie2020_led.ino #include <ESP8266WiFi.h> #include <PubSubClient.h> #define PIR 15 #define relay 4 const char* ssid = "XLGO-0AF7"; const char* password = "<PASSWORD>"; const char* mqtt_server = "broker.netpie.io"; const int mqtt_port = 1883; const char* mqtt_Client = "475b6ac8-27ce-46ca-b187-187f4b42ac39"; const char* mqtt_username = "6frcemX79qwTnftzqbs4L1UU2oreca8g"; const char* mqtt_password = "<PASSWORD>"; char msg[100]; char Msg[100]; int lighting = 0; int PIRstate = 0; int period = 1500; unsigned long countTime = 0; String data; WiFiClient espClient; PubSubClient client(espClient); void reconnect() { while (!client.connected()) { Serial.print("Attempting MQTT connection…"); if (client.connect(mqtt_Client, mqtt_username, mqtt_password)) { Serial.println("Connected"); client.subscribe("@msg/LEDstatus"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println("Try again in 5 seconds..."); delay(5000); } } } void onoff(int lighting) { if (lighting == 1){ Serial.println("Turn on the light!"); digitalWrite(relay,HIGH); data = "{\"data\" : {\"LEDstatus\" : \"on\"}}"; data.toCharArray(Msg, (data.length() + 1)); client.publish("@shadow/data/update", msg); } else if (lighting == 0) { Serial.println("Turn off the light!"); digitalWrite(relay,LOW); data = "{\"data\" : {\"LEDstatus\" : \"off\"}}"; data.toCharArray(Msg, (data.length() + 1)); client.publish("@shadow/data/update", msg); } } void callback(char* topic,byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("]: "); String msg; for (int i = 0; i < length; i++) { msg = msg + (char)payload[i]; } Serial.println(msg); if (String(topic) == "@msg/LEDstatus") { if (msg == "on"){ lighting = 1; onoff(lighting); } else if (msg == "off") { lighting = 0; onoff(lighting); } } } void setup() { Serial.begin(115200); Serial.println("HELLO :)"); pinMode(relay,OUTPUT); pinMode(PIR,INPUT); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); client.setServer(mqtt_server, mqtt_port); client.setCallback(callback); } void loop() { if (!client.connected()) { reconnect(); } if(millis() >= countTime + period) { PIRstate = digitalRead(PIR); countTime += period; if (PIRstate == LOW) { Serial.println("Motion absent"); } else if (PIRstate == HIGH) { Serial.println("Motion detected :)"); lighting = lighting + 1; if (lighting == 2) { lighting = 0; } onoff(lighting); } } client.loop(); } <file_sep>/README.md # my_arduino backup <file_sep>/Arduino/sdcard/sdcard.ino #include <SD.h> File myFile; // สร้างออฟเจค File สำหรับจัดการข้อมูล String fileName = "cmlog.txt"; const int chipSelect = 4; void setup(){ Serial.begin(9600); while (!Serial) { ; // รอจนกระทั่งเชื่อมต่อกับ Serial port แล้ว (สำหรับ Arduino Leonardo เท่านั้น) } Serial.print("Initializing SD card..."); pinMode(SS, OUTPUT); // Slave select ตัว library มันจะขอให้เป็น OUTPUT เสมอ if (!SD.begin(chipSelect)) { Serial.println("initialization failed!"); return; } Serial.println("initialization done."); SD.remove(fileName); //ถ้าต้องการลบไฟล์ทิ้ง // เปิดไฟล์ที่ชื่อ fileName เพื่อเขียนข้อมูล โหมด FILE_WRITE =========================== myFile = SD.open(fileName, FILE_WRITE); // ถ้าเปิดไฟล์สำเร็จ ให้เขียนข้อมูลเพิ่มลงไป if (myFile) { Serial.print("Writing to " + fileName + "..."); myFile.println("arduino.codemobiles.com \ncounting.. 1, 2, 3."); // สั่งให้เขียนข้อมูล myFile.close(); // ปิดไฟล์ Serial.println("done."); } else { // ถ้าเปิดไฟลืไม่สำเร็จ ให้แสดง error Serial.println("error opening "+fileName); } // เปิดไฟล์เพื่ออ่าน ================================== myFile = SD.open(fileName); // สั่งให้เปิดไฟล์ชื่อ cmlog.txt เพื่ออ่านข้อมูล if (myFile) { Serial.println(fileName + ":"); // อ่านข้อมูลทั้งหมดออกมา while (myFile.available()) { Serial.write(myFile.read()); } myFile.close(); // เมื่ออ่านเสร็จ ปิดไฟล์ } else { // ถ้าอ่านไม่สำเร็จ ให้แสดง error Serial.println("error opening " + fileName); } } void loop(){ } <file_sep>/Arduino/i2cslaveled/i2cslaveled.ino #include<Wire.h> #define SLAVE_ADDR 8 //#define ANSWERSIZE 5 bool btnState; int num; int led = 10; //bool rd; // recieve data void setup() { // put your setup code here, to run once: Wire.begin(SLAVE_ADDR); // Function to run when data receive from master Wire.onReceive(receiveEvent); pinMode(led, OUTPUT); Serial.begin(9600); Serial.println("I2C Slave demonstration"); } void receiveEvent(){ // Read while data receive btnState = Wire.read(); } void loop() { Serial.println(btnState); if (btnState == HIGH){ digitalWrite(led, HIGH); }else{ digitalWrite(led, LOW); } } <file_sep>/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.h // // Copyright 2015 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef FIREBASE_OBJECT_H #define FIREBASE_OBJECT_H #include "third-party/arduino-json-5.2/include/ArduinoJson.h" #define FIREBASE_JSONBUFFER_SIZE 200 class FirebaseObject { public: FirebaseObject(const String& data); operator bool(); operator int(); operator float(); operator const String&(); operator const JsonObject&(); JsonObjectSubscript<const char*> operator[](const char* key); JsonObjectSubscript<const String&> operator[](const String& key); JsonVariant operator[](JsonObjectKey key) const; private: String data_; StaticJsonBuffer<FIREBASE_JSONBUFFER_SIZE> buffer_; JsonObject* json_; }; #endif // FIREBASE_OBJECT_H
052719a94ed99fba7e5c93a952ba2713f2edbac7
[ "Markdown", "C", "C++", "INI" ]
87
C++
anousonefs/arduino-basic
f15a109950b8709117a9f618cbe4ac9225f65a65
4d2a760c177ad03c30aef1b37934e5c10b927421
refs/heads/master
<file_sep>package com.setecs.mobile.safe.apps.shared; import org.json.JSONException; import org.json.JSONObject; public class AccountBalanceParser { public static String parse(String response) { String output = response; try { JSONObject object = new JSONObject(response); String accountNo = "Account No: " + object.getJSONObject("accountId").getString("accountNo") + "\n"; String accountType = "Account Type: " + object.getJSONObject("accountId").getString("type") + "\n"; String balance = "Balance: " + object.getString("balanceAvailable") + "\n"; String currency = "Currency: " + object.getString("currency") + "\n"; output = accountType + accountNo + balance + currency; } catch (JSONException e) { // ignore } return output; } } <file_sep>package com.setecs.mobile.safe.apps.util.security; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class SymmetricCryption { private static int AES_blocksize = 32; private static int DES_blocksize = 16; private static byte[] ivBytesForAES = "tyrgfhsjcbzloiqa".getBytes(); private static byte[] ivBytesForDES = { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; public SymmetricCryption() { } public byte[] AESEncryptor(byte[] cleartext, byte[] key) { byte[] ciphertext = null; byte[] symmetrickey; SecretKeySpec keySpec; symmetrickey = key; int ciphertextLength = 0; int remainder = cleartext.length % AES_blocksize; IvParameterSpec iv = new IvParameterSpec(ivBytesForAES, 0, ivBytesForAES.length); int numofBytes = 0; try { Cipher AES = Cipher.getInstance("AES/CBC/PKCS5Padding"); keySpec = new SecretKeySpec(symmetrickey, 0, symmetrickey.length, "AES"); if (remainder == 0) { ciphertextLength = cleartext.length + AES_blocksize; } else { ciphertextLength = cleartext.length - remainder + AES_blocksize; } ciphertext = new byte[ciphertextLength]; AES.init(Cipher.ENCRYPT_MODE, keySpec, iv); numofBytes = AES.doFinal(cleartext, 0, cleartext.length, ciphertext, 0); } catch (NoSuchAlgorithmException e) { System.out.println(e.toString()); } catch (NoSuchPaddingException e) { System.out.println(e.toString()); } catch (InvalidKeyException e) { System.out.println(e.toString()); } catch (ShortBufferException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { System.out.println(e.toString()); } catch (BadPaddingException e) { System.out.println(e.toString()); } catch (InvalidAlgorithmParameterException e) { System.out.println(e.toString()); } catch (NullPointerException e) { System.out.println(e.toString()); } byte[] result = new byte[numofBytes]; System.arraycopy(ciphertext, 0, result, 0, numofBytes); return result; } public byte[] AESDecryptor(byte[] cihpertext, byte[] key) { byte[] cleartext = new byte[cihpertext.length]; byte[] symmetrickey = key; SecretKeySpec keySpec; IvParameterSpec iv = new IvParameterSpec(ivBytesForAES, 0, ivBytesForAES.length); int numofBytes = 0; try { Cipher AES = Cipher.getInstance("AES/CBC/PKCS5Padding"); keySpec = new SecretKeySpec(symmetrickey, 0, symmetrickey.length, "AES"); AES.init(Cipher.DECRYPT_MODE, keySpec, iv); numofBytes = AES.doFinal(cihpertext, 0, cihpertext.length, cleartext, 0); } catch (NoSuchAlgorithmException e) { System.out.println(e.toString()); } catch (NoSuchPaddingException e) { System.out.println(e.toString()); } catch (InvalidKeyException e) { System.out.println(e.toString()); } catch (ShortBufferException e) { System.out.println(e.toString()); } catch (IllegalBlockSizeException e) { System.out.println(e.toString()); } catch (BadPaddingException e) { System.out.println(e.toString()); } catch (InvalidAlgorithmParameterException e) { System.out.println(e.toString()); } catch (NullPointerException e) { System.out.println(e.toString()); } byte[] result = new byte[numofBytes]; System.arraycopy(cleartext, 0, result, 0, numofBytes); return result; } public byte[] DESEncryptor(byte[] cleartext, byte[] key) { byte[] ciphertext = null; byte[] symmetrickey; SecretKeySpec keySpec; symmetrickey = key; int ciphertextLength = 0; int remainder = cleartext.length % DES_blocksize; int numofBytes = 0; try { // Cipher DES = Cipher.getInstance("DES/CBC/NoPadding"); Cipher DES = Cipher.getInstance("DES"); keySpec = new SecretKeySpec(symmetrickey, 0, symmetrickey.length, "DES"); if (remainder == 0) { ciphertextLength = cleartext.length + DES_blocksize; } else { ciphertextLength = cleartext.length - remainder + DES_blocksize; } ciphertext = new byte[ciphertextLength]; DES.init(Cipher.ENCRYPT_MODE, keySpec); numofBytes = DES.doFinal(cleartext, 0, cleartext.length, ciphertext, 0); } catch (NoSuchAlgorithmException e) { System.out.println(e.toString()); } catch (NoSuchPaddingException e) { System.out.println(e.toString()); } catch (InvalidKeyException e) { System.out.println(e.toString()); } catch (ShortBufferException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { System.out.println(e.toString()); } catch (BadPaddingException e) { System.out.println(e.toString()); } catch (NullPointerException e) { System.out.println(e.toString()); } byte[] result = new byte[numofBytes]; System.arraycopy(ciphertext, 0, result, 0, numofBytes); return result; } public byte[] DESDecryptor(byte[] cihpertext, byte[] key) { byte[] cleartext = new byte[cihpertext.length]; byte[] symmetrickey = key; SecretKeySpec keySpec; IvParameterSpec iv = new IvParameterSpec(ivBytesForDES, 0, ivBytesForDES.length); int numofBytes = 0; try { Cipher DES = Cipher.getInstance("DES/CBC/PKCS5Padding"); // Cipher DES = Cipher.getInstance("DES"); keySpec = new SecretKeySpec(symmetrickey, 0, symmetrickey.length, "DES"); DES.init(Cipher.DECRYPT_MODE, keySpec, iv); // DES.init(Cipher.DECRYPT_MODE, keySpec); numofBytes = DES.doFinal(cihpertext, 0, cihpertext.length, cleartext, 0); } catch (NoSuchAlgorithmException e) { System.out.println(e.toString()); } catch (NoSuchPaddingException e) { System.out.println(e.toString()); } catch (InvalidKeyException e) { System.out.println(e.toString()); } catch (ShortBufferException e) { System.out.println(e.toString()); } catch (IllegalBlockSizeException e) { System.out.println(e.toString()); } catch (BadPaddingException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { System.out.println(e.toString()); } catch (NullPointerException e) { System.out.println(e.toString()); } byte[] result = new byte[numofBytes]; System.arraycopy(cleartext, 0, result, 0, numofBytes); return result; } public static void main(String args[]) { SymmetricCryption se = new SymmetricCryption(); byte[] ciphertmp = se.DESEncryptor("as 900002".getBytes(), "01234567".getBytes()); String temp = new String(ciphertmp); System.out.println("The DES cipher text is: " + temp); byte[] cleartext = se.DESDecryptor(ciphertmp, "01234567".getBytes()); String temp1 = new String(cleartext); System.out.println("The DES clear text is: " + temp1); } } <file_sep>package com.setecs.mobile.safe.apps.shared; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import android.annotation.SuppressLint; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.widget.Toast; @SuppressLint("Registered") public class SocketService extends Service { public static Socket socket; @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return myBinder; } private final IBinder myBinder = new LocalBinder(); public class LocalBinder extends Binder { public SocketService getService() { return SocketService.this; } } @Override public void onCreate() { super.onCreate(); socket = new Socket(); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Toast.makeText(this, "Service created ...", Toast.LENGTH_LONG).show(); Runnable connect = new connectSocket(); new Thread(connect).start(); } class connectSocket implements Runnable { @Override public void run() { SocketAddress socketAddress = new InetSocketAddress(SharedMethods.serverIpAddress, SharedMethods.SERVERPORT); try { socket.connect(socketAddress); } catch (IOException e) { e.printStackTrace(); } } } @Override public void onDestroy() { super.onDestroy(); try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } socket = null; } }
a5f18fa26f7da4f23fcb8149d44f0d829a521f04
[ "Java" ]
3
Java
wajanga/SAFE-Wallet-Support-Library-
6d0676ec9cb887917324897791a81171d9100cea
4a0c43fdbfb6acadfb6932af03cee344f5c3adc9
refs/heads/master
<file_sep>/* (c) <NAME>. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/demo.h> #include <engine/keys.h> #include <engine/graphics.h> #include <engine/textrender.h> #include <engine/shared/config.h> #include <game/generated/client_data.h> #include <game/generated/protocol.h> #include <game/client/animstate.h> #include <game/client/render.h> #include "spectator.h" #include "players.h" void CSpectator::ConKeySpectator(IConsole::IResult *pResult, void *pUserData) { CSpectator *pSelf = (CSpectator *)pUserData; if(pSelf->m_pClient->m_Snap.m_SpecInfo.m_Active && (pSelf->Client()->State() != IClient::STATE_DEMOPLAYBACK || pSelf->DemoPlayer()->GetDemoType() == IDemoPlayer::DEMOTYPE_SERVER)) pSelf->m_Active = pResult->GetInteger(0) != 0; } void CSpectator::ConSpectate(IConsole::IResult *pResult, void *pUserData) { ((CSpectator *)pUserData)->Spectate(pResult->GetInteger(0)); } void CSpectator::ConSpectateNext(IConsole::IResult *pResult, void *pUserData) { CSpectator *pSelf = (CSpectator *)pUserData; int NewSpectatorID; bool GotNewSpectatorID = false; if(pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) { for(int i = 0; i < MAX_CLIENTS; i++) { if(!pSelf->m_pClient->m_Snap.m_paPlayerInfos[i] || pSelf->m_pClient->m_Snap.m_paPlayerInfos[i]->m_Team == TEAM_SPECTATORS) continue; NewSpectatorID = i; GotNewSpectatorID = true; break; } } else { for(int i = pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID + 1; i < MAX_CLIENTS; i++) { if(!pSelf->m_pClient->m_Snap.m_paPlayerInfos[i] || pSelf->m_pClient->m_Snap.m_paPlayerInfos[i]->m_Team == TEAM_SPECTATORS) continue; NewSpectatorID = i; GotNewSpectatorID = true; break; } if(!GotNewSpectatorID) { for(int i = 0; i < pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID; i++) { if(!pSelf->m_pClient->m_Snap.m_paPlayerInfos[i] || pSelf->m_pClient->m_Snap.m_paPlayerInfos[i]->m_Team == TEAM_SPECTATORS) continue; NewSpectatorID = i; GotNewSpectatorID = true; break; } } } if(GotNewSpectatorID) pSelf->Spectate(NewSpectatorID); } void CSpectator::ConSpectatePrevious(IConsole::IResult *pResult, void *pUserData) { CSpectator *pSelf = (CSpectator *)pUserData; int NewSpectatorID; bool GotNewSpectatorID = false; if(pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) { for(int i = MAX_CLIENTS -1; i > -1; i--) { if(!pSelf->m_pClient->m_Snap.m_paPlayerInfos[i] || pSelf->m_pClient->m_Snap.m_paPlayerInfos[i]->m_Team == TEAM_SPECTATORS) continue; NewSpectatorID = i; GotNewSpectatorID = true; break; } } else { for(int i = pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID - 1; i > -1; i--) { if(!pSelf->m_pClient->m_Snap.m_paPlayerInfos[i] || pSelf->m_pClient->m_Snap.m_paPlayerInfos[i]->m_Team == TEAM_SPECTATORS) continue; NewSpectatorID = i; GotNewSpectatorID = true; break; } if(!GotNewSpectatorID) { for(int i = MAX_CLIENTS - 1; i > pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID; i--) { if(!pSelf->m_pClient->m_Snap.m_paPlayerInfos[i] || pSelf->m_pClient->m_Snap.m_paPlayerInfos[i]->m_Team == TEAM_SPECTATORS) continue; NewSpectatorID = i; GotNewSpectatorID = true; break; } } } if(GotNewSpectatorID) pSelf->Spectate(NewSpectatorID); } CSpectator::CSpectator() { OnReset(); } void CSpectator::OnConsoleInit() { Console()->Register("+spectate", "", CFGFLAG_CLIENT, ConKeySpectator, this, "Open spectator mode selector"); Console()->Register("spectate", "i", CFGFLAG_CLIENT, ConSpectate, this, "Switch spectator mode"); Console()->Register("spectate_next", "", CFGFLAG_CLIENT, ConSpectateNext, this, "Spectate the next player"); Console()->Register("spectate_previous", "", CFGFLAG_CLIENT, ConSpectatePrevious, this, "Spectate the previous player"); } bool CSpectator::OnMouseMove(float x, float y) { if(!m_Active) return false; UI()->ConvertMouseMove(&x, &y); m_SelectorMouse += vec2(x,y); return true; } void CSpectator::OnRelease() { OnReset(); } bool CSpectator::InView(const CUIRect *r, float Width, float Height) { if(m_SelectorMouse.x+Width >= r->x && m_SelectorMouse.x+Width <= r->x+r->w && m_SelectorMouse.y+Height >= r->y && m_SelectorMouse.y+Height <= r->y+r->h) return true; return false; } void CSpectator::OnRender() { if(!m_Active) { if(m_WasActive) { if(m_SelectedSpectatorID != NO_SELECTION) Spectate(m_SelectedSpectatorID); m_WasActive = false; } return; } if(m_Selected != m_pClient->m_Snap.m_SpecInfo.m_SpectatorID) { m_SelectedSpectatorID = m_Selected; Spectate(m_SelectedSpectatorID); Loading = true; } else Loading = false; if(!m_pClient->m_Snap.m_SpecInfo.m_Active) { m_Active = false; m_WasActive = false; return; } m_WasActive = true; m_SelectedSpectatorID = NO_SELECTION; // draw background CUIRect Screen = *UI()->Screen(), TopMenu, BottomMenu; Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); Screen.Margin(10.0f, &Screen); vec4 ms_ColorTabbarActive = vec4(0.0f, 0.0f, 0.0f, 0.40f); vec4 ms_ColorTabbarActive2 = vec4(1.0f, 1.0f, 1.0f, 0.40f); Screen.HSplitBottom(10*3.0f*Graphics()->ScreenAspect(), &Screen, 0); Screen.HMargin(21*3.0f*Graphics()->ScreenAspect(), &Screen); Screen.VMargin(10*3.0f*Graphics()->ScreenAspect(), &Screen); float Width = Screen.w/2-10, Height = Screen.h/2-10; m_SelectorMouse.x = clamp(m_SelectorMouse.x, -Width, Width); m_SelectorMouse.y = clamp(m_SelectorMouse.y, -Height, Height); Width += 10*3.0f*Graphics()->ScreenAspect()+10; Height += 20*3.0f*Graphics()->ScreenAspect()+10; Screen.HSplitTop(Screen.h/2-20, &TopMenu, &BottomMenu); TopMenu.HSplitBottom(5, &TopMenu, 0); { CUIRect Left, Middle, Right; int Temp = TopMenu.w/3; TopMenu.VSplitLeft(Temp, &Left, &TopMenu); TopMenu.VSplitRight(Temp, &Middle, &Right); Middle.HMargin(5, &Middle); Left.VMargin(5, &Left); Right.VMargin(5, &Right); Left.HSplitTop(10, 0, &Left); Right.HSplitTop(10, 0, &Right); if(Loading) { if(Button2vec < 0.6f) Button2vec += 0.01f; } else if(Button2vec > 0.0f) Button2vec -= 0.01f; RenderTools()->DrawUIRect(&Left, ms_ColorTabbarActive, CUI::CORNER_ALL, 10.0f); RenderTools()->DrawUIRect(&Middle, ms_ColorTabbarActive, CUI::CORNER_ALL, 10.0f); RenderTools()->DrawUIRect(&Right, ms_ColorTabbarActive, CUI::CORNER_ALL, 10.0f); if(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID >= 0) { CTeeRenderInfo TeeInfo = m_pClient->m_aClients[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID].m_RenderInfo; TeeInfo.m_Size *= 2; RenderTools()->RenderTee(CAnimState::GetIdle(), &TeeInfo, EMOTE_HAPPY, vec2(1.0f, 0.0f), vec2(Middle.x+Middle.w/2, Middle.y+Middle.h/2+10)); UI()->DoLabel(&Middle, m_pClient->m_aClients[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID].m_aName,20.0f*UI()->Scale(), 0); } CUIRect TempCui; Middle.HSplitBottom(24, &Middle, &TempCui); RenderTools()->DrawUIRect(&TempCui, ms_ColorTabbarActive, CUI::CORNER_B, 10.0f); UI()->DoLabel(&TempCui, Localize("Follower"),20.0f*UI()->Scale(), 0); int NewSpectatorID_Next = -1; bool GotNewSpectatorID_Next = false; if(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) { for(int i = 0; i < MAX_CLIENTS; i++) { if(!m_pClient->m_Snap.m_paPlayerInfos[i] || m_pClient->m_Snap.m_paPlayerInfos[i]->m_Team == TEAM_SPECTATORS) continue; NewSpectatorID_Next = i; GotNewSpectatorID_Next = true; break; } } else { for(int i = m_pClient->m_Snap.m_SpecInfo.m_SpectatorID + 1; i < MAX_CLIENTS; i++) { if(!m_pClient->m_Snap.m_paPlayerInfos[i] || m_pClient->m_Snap.m_paPlayerInfos[i]->m_Team == TEAM_SPECTATORS) continue; NewSpectatorID_Next = i; GotNewSpectatorID_Next = true; break; } if(!GotNewSpectatorID_Next) { for(int i = 0; i < m_pClient->m_Snap.m_SpecInfo.m_SpectatorID; i++) { if(!m_pClient->m_Snap.m_paPlayerInfos[i] || m_pClient->m_Snap.m_paPlayerInfos[i]->m_Team == TEAM_SPECTATORS) continue; NewSpectatorID_Next = i; GotNewSpectatorID_Next = true; break; } } } if(GotNewSpectatorID_Next) { CTeeRenderInfo TeeInfo = m_pClient->m_aClients[NewSpectatorID_Next].m_RenderInfo; TeeInfo.m_Size *= 1.5f; RenderTools()->RenderTee(CAnimState::GetIdle(), &TeeInfo, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(Right.x+Right.w/2, Right.y+Right.h/2+10)); UI()->DoLabel(&Right, m_pClient->m_aClients[NewSpectatorID_Next].m_aName,15.0f*UI()->Scale(), 0); } Right.HSplitBottom(22, &Right, &TempCui); RenderTools()->DrawUIRect(&TempCui, ms_ColorTabbarActive, CUI::CORNER_B, 10.0f); UI()->DoLabel(&TempCui, Localize("Next"),18.0f*UI()->Scale(), 0); if(InView(&Right, Width, Height)) RenderTools()->DrawUIRect(&Right, ms_ColorTabbarActive2, CUI::CORNER_T, 10.0f); if(Input()->KeyPressed(KEY_MOUSE_1) && InView(&Right, Width, Height)) RenderTools()->DrawUIRect(&Right, ms_ColorTabbarActive, CUI::CORNER_T, 10.0f); if(Input()->KeyDown(KEY_MOUSE_1) && InView(&Right, Width, Height)) { if(GotNewSpectatorID_Next) Spectate(NewSpectatorID_Next); m_Selected = NewSpectatorID_Next; } int NewSpectatorID_Prev = -1; bool GotNewSpectatorID_Prev = false; if(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) { for(int i = MAX_CLIENTS -1; i > -1; i--) { if(!m_pClient->m_Snap.m_paPlayerInfos[i] || m_pClient->m_Snap.m_paPlayerInfos[i]->m_Team == TEAM_SPECTATORS) continue; NewSpectatorID_Prev = i; GotNewSpectatorID_Prev = true; break; } } else { for(int i = m_pClient->m_Snap.m_SpecInfo.m_SpectatorID - 1; i > -1; i--) { if(!m_pClient->m_Snap.m_paPlayerInfos[i] || m_pClient->m_Snap.m_paPlayerInfos[i]->m_Team == TEAM_SPECTATORS) continue; NewSpectatorID_Prev = i; GotNewSpectatorID_Prev = true; break; } if(!GotNewSpectatorID_Prev) { for(int i = MAX_CLIENTS - 1; i > m_pClient->m_Snap.m_SpecInfo.m_SpectatorID; i--) { if(!m_pClient->m_Snap.m_paPlayerInfos[i] || m_pClient->m_Snap.m_paPlayerInfos[i]->m_Team == TEAM_SPECTATORS) continue; NewSpectatorID_Prev = i; GotNewSpectatorID_Prev = true; break; } } } if(GotNewSpectatorID_Prev) { CTeeRenderInfo TeeInfo = m_pClient->m_aClients[NewSpectatorID_Prev].m_RenderInfo; TeeInfo.m_Size *= 1.5f; RenderTools()->RenderTee(CAnimState::GetIdle(), &TeeInfo, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(Left.x+Left.w/2, Left.y+Left.h/2+10)); UI()->DoLabel(&Left, m_pClient->m_aClients[NewSpectatorID_Prev].m_aName,15.0f*UI()->Scale(), 0); } Left.HSplitBottom(22, &Left, &TempCui); RenderTools()->DrawUIRect(&TempCui, ms_ColorTabbarActive, CUI::CORNER_B, 10.0f); UI()->DoLabel(&TempCui, Localize("Previous"),18.0f*UI()->Scale(), 0); if(InView(&Left, Width, Height)) RenderTools()->DrawUIRect(&Left, ms_ColorTabbarActive2, CUI::CORNER_T, 10.0f); if(Input()->KeyPressed(KEY_MOUSE_1) && InView(&Left, Width, Height)) RenderTools()->DrawUIRect(&Left, ms_ColorTabbarActive, CUI::CORNER_T, 10.0f); if(Input()->KeyDown(KEY_MOUSE_1) && InView(&Left, Width, Height)) { if(GotNewSpectatorID_Prev) Spectate(NewSpectatorID_Prev); m_Selected = NewSpectatorID_Prev; } } float TempWidth = BottomMenu.h/2.5f, TempHeight = BottomMenu.h/2.5f; int Count = 0; for(int i = 0; i < 16; i++) { if(!m_pClient->m_Snap.m_paPlayerInfos[i] || m_pClient->m_Snap.m_paPlayerInfos[i]->m_Team == TEAM_SPECTATORS) continue; Count++; } CUIRect ButtonPlayer, BottomMenu1, BottomMenu2, Button, Button2; BottomMenu.VSplitLeft(2.0f, 0, &BottomMenu); BottomMenu.HSplitTop(TempHeight+5.0f, &BottomMenu1, &BottomMenu2); BottomMenu2.HSplitTop(5.0f, 0, &BottomMenu2); BottomMenu2.HSplitTop(TempHeight, &BottomMenu2, &Button); if(Count > 8) { BottomMenu1.VMargin((BottomMenu1.w-((TempHeight+5.0f)*8))/2, &BottomMenu1); BottomMenu2.VMargin((BottomMenu2.w-((TempHeight+5.0f)*(Count%8)))/2, &BottomMenu2); } else { BottomMenu1.VMargin((BottomMenu1.w-((TempHeight+5.0f)*Count))/2, &BottomMenu1); } Button.VSplitLeft(10.0f, 0, &Button); Button.VSplitLeft(200.0f, &Button, &Button2); Button2.VSplitRight(10.0f, &Button2, 0); Button2.VSplitRight(200.0f, 0, &Button2); vec4 ms_ColorTabbarActive3 = vec4(0.0f, 0.0f, 0.0f, Button2vec*1.6f); RenderTools()->DrawUIRect(&Button, ms_ColorTabbarActive, CUI::CORNER_ALL, 10.0f); RenderTools()->DrawUIRect(&Button2, ms_ColorTabbarActive3, CUI::CORNER_ALL, 10.0f); if(InView(&Button, Width, Height)) RenderTools()->DrawUIRect(&Button, ms_ColorTabbarActive2, CUI::CORNER_ALL, 10.0f); if(Input()->KeyPressed(KEY_MOUSE_1) && InView(&Button, Width, Height)) RenderTools()->DrawUIRect(&Button, ms_ColorTabbarActive, CUI::CORNER_ALL, 10.0f); if(Input()->KeyDown(KEY_MOUSE_1) && InView(&Button, Width, Height)) { m_SelectedSpectatorID = SPEC_FREEVIEW; Spectate(m_SelectedSpectatorID); m_Selected = -1; } if(m_Selected == -1) TextRender()->TextOutlineColor(0.0f, 0.0f, 6.0f, 0.5f); TextRender()->Text(0, Button.x+7, Button.y+2, 18.0f*UI()->Scale(), Localize("Free-View"), Button.w-4); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); TextRender()->TextColor(1.0f, 1.0f, 1.0f, Button2vec*1.6f); TextRender()->Text(0, Button2.x+10, Button2.y, 22.0f*UI()->Scale(), Localize("Loading"), Button2.w-4); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); Count = 0; for(int j = 0; j < 16; j++) { if(!m_pClient->m_Snap.m_paPlayerInfos[j] || m_pClient->m_Snap.m_paPlayerInfos[j]->m_Team == TEAM_SPECTATORS) continue; Count ++; if(Count == 1) BottomMenu = BottomMenu1; else if(Count == 9) BottomMenu = BottomMenu2; BottomMenu.VSplitLeft(TempWidth, &ButtonPlayer, &BottomMenu); BottomMenu.VSplitLeft(5.0f, 0, &BottomMenu); RenderTools()->DrawUIRect(&ButtonPlayer, ms_ColorTabbarActive2, CUI::CORNER_ALL, 10.0f); if(InView(&ButtonPlayer, Width, Height)) RenderTools()->DrawUIRect(&ButtonPlayer, ms_ColorTabbarActive2, CUI::CORNER_ALL, 10.0f); if(Input()->KeyPressed(KEY_MOUSE_1) && InView(&ButtonPlayer, Width, Height)) RenderTools()->DrawUIRect(&ButtonPlayer, ms_ColorTabbarActive, CUI::CORNER_ALL, 10.0f); if(Input()->KeyDown(KEY_MOUSE_1) && InView(&ButtonPlayer, Width, Height)) { m_SelectedSpectatorID = j; Spectate(m_SelectedSpectatorID); m_Selected = j; } if(m_Selected == j) TextRender()->TextOutlineColor(0.0f, 0.0f, 2.0f, 0.5f); TextRender()->Text(0, ButtonPlayer.x+4, ButtonPlayer.y+2, 12.0f*UI()->Scale(), m_pClient->m_aClients[j].m_aName, TempWidth-6.0f); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); CTeeRenderInfo TeeInfo = m_pClient->m_aClients[j].m_RenderInfo; TeeInfo.m_Size = TempWidth/2; RenderTools()->RenderTee(CAnimState::GetIdle(), &TeeInfo, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(ButtonPlayer.x+TempWidth/2, ButtonPlayer.y+TempWidth/2+20)); } /* // draw background float Width = 400*3.0f*Graphics()->ScreenAspect(); float Height = 400*3.0f; Graphics()->MapScreen(0, 0, Width, Height); Graphics()->BlendNormal(); Graphics()->TextureSet(-1); Graphics()->QuadsBegin(); Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.3f); RenderTools()->DrawRoundRect(Width/2.0f-300.0f, Height/2.0f-300.0f, 600.0f, 600.0f, 20.0f); Graphics()->QuadsEnd(); // clamp mouse position to selector area m_SelectorMouse.x = clamp(m_SelectorMouse.x, -280.0f, 280.0f); m_SelectorMouse.y = clamp(m_SelectorMouse.y, -280.0f, 280.0f); // draw selections float FontSize = 20.0f; float StartY = -190.0f; float LineHeight = 60.0f; bool Selected = false; if(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) { Graphics()->TextureSet(-1); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f); RenderTools()->DrawRoundRect(Width/2.0f-280.0f, Height/2.0f-280.0f, 270.0f, 60.0f, 20.0f); Graphics()->QuadsEnd(); } if(m_SelectorMouse.x >= -280.0f && m_SelectorMouse.x <= -10.0f && m_SelectorMouse.y >= -280.0f && m_SelectorMouse.y <= -220.0f) { m_SelectedSpectatorID = SPEC_FREEVIEW; Selected = true; } TextRender()->TextColor(1.0f, 1.0f, 1.0f, Selected?1.0f:0.5f); TextRender()->Text(0, Width/2.0f-240.0f, Height/2.0f-265.0f, FontSize, Localize("Free-View"), -1); float x = -270.0f, y = StartY; for(int i = 0, Count = 0; i < MAX_CLIENTS; ++i) { if(!m_pClient->m_Snap.m_paPlayerInfos[i] || m_pClient->m_Snap.m_paPlayerInfos[i]->m_Team == TEAM_SPECTATORS) continue; if(++Count%9 == 0) { x += 290.0f; y = StartY; } if(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == i) { Graphics()->TextureSet(-1); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f); RenderTools()->DrawRoundRect(Width/2.0f+x-10.0f, Height/2.0f+y-10.0f, 270.0f, 60.0f, 20.0f); Graphics()->QuadsEnd(); } Selected = false; if(m_SelectorMouse.x >= x-10.0f && m_SelectorMouse.x <= x+260.0f && m_SelectorMouse.y >= y-10.0f && m_SelectorMouse.y <= y+50.0f) { m_SelectedSpectatorID = i; Selected = true; } TextRender()->TextColor(1.0f, 1.0f, 1.0f, Selected?1.0f:0.5f); TextRender()->Text(0, Width/2.0f+x+50.0f, Height/2.0f+y+5.0f, FontSize, m_pClient->m_aClients[i].m_aName, 220.0f); // flag if(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_FLAGS && m_pClient->m_Snap.m_pGameDataObj && (m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierRed == m_pClient->m_Snap.m_paPlayerInfos[i]->m_ClientID || m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierBlue == m_pClient->m_Snap.m_paPlayerInfos[i]->m_ClientID)) { Graphics()->BlendNormal(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); RenderTools()->SelectSprite(m_pClient->m_Snap.m_paPlayerInfos[i]->m_Team==TEAM_RED ? SPRITE_FLAG_BLUE : SPRITE_FLAG_RED, SPRITE_FLAG_FLIP_X); float Size = LineHeight; IGraphics::CQuadItem QuadItem(Width/2.0f+x-LineHeight/5.0f, Height/2.0f+y-LineHeight/3.0f, Size/2.0f, Size); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } CTeeRenderInfo TeeInfo = m_pClient->m_aClients[i].m_RenderInfo; RenderTools()->RenderTee(CAnimState::GetIdle(), &TeeInfo, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(Width/2.0f+x+20.0f, Height/2.0f+y+20.0f)); y += LineHeight; } TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); */ // draw cursor Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CURSOR].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); IGraphics::CQuadItem QuadItem(m_SelectorMouse.x+Width, m_SelectorMouse.y+Height, 24.0f, 24.0f); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } void CSpectator::OnReset() { m_WasActive = false; m_Active = false; m_SelectedSpectatorID = NO_SELECTION; m_ButtonPress = 0; m_Selected = -1; Button2vec = 0.0f; Loading = false; } void CSpectator::Spectate(int SpectatorID) { if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { m_pClient->m_DemoSpecID = clamp(SpectatorID, (int)SPEC_FREEVIEW, MAX_CLIENTS-1); return; } if(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SpectatorID) return; CNetMsg_Cl_SetSpectatorMode Msg; Msg.m_SpectatorID = SpectatorID; Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); }
50908db5cdccf28965f21c656cc9d5c3fc59ff89
[ "C++" ]
1
C++
Henningstone/old-tdtw-0.6-trunk
3baade350d129bf38673cb81e39a3f002d17d440
1fcb120792bcaff7dc1654e4067b923a012d9e94
refs/heads/master
<repo_name>HR-SDC-Bridge/calvin-about<file_sep>/README.md # About Section > This service will be the about section located on the right of the product details page. It will own crucial information about each product most notably the brand, category, and price of each product. ## Related Projects - https://github.com/teamName/repo - https://github.com/teamName/repo - https://github.com/teamName/repo - https://github.com/teamName/repo ## Table of Contents 1. [Usage](#Usage) 1. [Requirements](#requirements) 1. [Development](#development) ## Usage <br> > API Usage: - GET /api/product/:id ```JSON { "_id": Integer, "brand": String, "category": String, "color": String, "price": Integer, "moreOptions": Boolean, "newItem": Boolean } ``` - example response based on this [pie plate](https://www.ikea.com/us/en/p/vardagen-pie-plate-off-white-10289307/) ```JSON { "_id": 10289307, "brand": "VARDAGEN", "category": "Pie plate", "color": "off-white", "itemPrice": 7.99, "moreOptions": false, "newItem": false } ``` <br> > CRUD Routes: <br> Endpoint | Type | Response --- | --- | --- '/api/product' | POST | Creates a new product in the database <br> ```JSON // Expected user input { "brand": String, "category": String, "color": String, "price": Number, "linkedColors": Array, "linkedSizes": Array, "newProduct": Boolean, "productAvailable": Boolean } // If user input is not provided, a random entry will be created instead ``` <br> Endpoint | Type | Response --- | --- | --- '/api/product/:id' | PUT | Updates a product in the database by ID <br> ```JSON // Expected user input { "_id": Number, "brand": String, "category": String, "color": String, "price": Number, "linkedColors": Array, "linkedSizes": Array, "newProduct": Boolean, "productAvailable": Boolean } // If user input is not provided, document will not be updated ``` <br> Endpoint | Type | Response --- | --- | --- '/api/product/:id' | GET | Reads a product in the database by ID <br> ```JSON // Expected response { "_id": Number, "brand": String, "category": String, "color": String, "price": Number, "moreOptions": Boolean, "linkedColors": Array, "linkedSizes": Array, "newProduct": Boolean, "productAvailable": Boolean, "dataQueried": Boolean } // "moreOptions" and "dataQueried" are added to the initial query ``` <br> Endpoint | Type | Response --- | --- | --- '/api/product/:id' | DELETE | Deletes a product in the database by ID <br> ```JSON ``` <br> ## Requirements An `nvmrc` file is included if using [nvm](https://github.com/creationix/nvm). - Node 6.13.0 - etc <br> ## Development ### Installing Dependencies From within the root directory: ```sh npm install -g webpack npm install ``` <file_sep>/database/product.js const dummyData = require('./dummy-data.js'); const mongoose = require('mongoose'); const Schema = mongoose.Schema; const productSchema = new Schema({ _id: Number, brand: String, category: String, color: String, price: Number, linkedColors: Array, linkedSizes: Array, newProduct: Boolean, productAvailable: Boolean }); const Products = mongoose.model('product', productSchema); // // Original seeding script // var seedDatabase = function(callback) { // mongoose.connect('mongodb://localhost/ikea', {useNewUrlParser: true, useUnifiedTopology: true}); // const database = mongoose.connection; // database.on('error', err => console.log('error connecting:', err)); // database.once('open', () => console.log('connected to database')); // database.dropDatabase() // .then(() => { // let entries = dummyData.generateRandomEntries(); // return Products.insertMany(entries); // }) // .then((results) => { // console.log('successfully seeded database'); // database.close(); // callback(null, results); // }) // .catch((err) => { // console.log('err seeding database', err); // database.close(); // callback(err, null); // }); // }; var queryDatabase = function(productId, callback) { // DECIDE WHETHER OR NOT THIS IS SMART; DO I WANT TO BE OPENNING A DATABASE CONNECTION EVERYTIME ??? mongoose.connect('mongodb://localhost/ikea', {useNewUrlParser: true, useUnifiedTopology: true}); const database = mongoose.connection; database.on('error', err => console.log('error connecting:', err)); database.once('open', () => console.log('connected to Mongo database')); Products.findById(productId, (err, results) => { if (err) { database.close(); callback(err, null); } else { database.close(); callback(null, results); } }); }; ////////// New seeding script for Mongo var seedDatabase = function(callback) { mongoose.connect('mongodb://localhost/ikea', {useNewUrlParser: true, useUnifiedTopology: true}); const database = mongoose.connection; database.on('error', err => console.log('error connecting:', err)); database.once('open', () => console.log('connected to database')); database.dropDatabase() .then(async () => { let entries = []; for (let i = 1; i <= 10000000; i++) { entries.push(dummyData.generateRandomEntry(i)); if (entries.length === 100000) { await Products.insertMany(entries); console.log(`${i} entries saved`); entries = []; } } return 'Worked'; }) .then((results) => { console.log('successfully seeded database'); database.close(); callback(null, results); }) .catch((err) => { console.log('err seeding database', err); database.close(); callback(err, null); }); }; ////////// Beginning of new CRUD queries for Mongo const createQuery = async (data) => { mongoose.connect('mongodb://localhost/ikea', {useNewUrlParser: true, useUnifiedTopology: true}); const database = mongoose.connection; database.on('error', err => console.log('error connecting:', err)); database.once('open', () => console.log('connected to database')); // Get ID of latest entry in database const lastEntry = await Products.find({}).sort({_id: -1}).limit(1); const newID = lastEntry[0]._id + 1; // If input data is empty if (Object.keys(data).length === 0) { // Use seeding script to generate data data = dummyData.generateRandomEntry(newID); } else { // Update ID before saving data._id = newID; } const newEntry = new Products(data); newEntry.save(newEntry) .then(result => { database.close(); }) .catch(err => { database.close(); console.log('Error with MongoDB create query', err); }); return data; }; const readQuery = async (id) => { mongoose.connect('mongodb://localhost/ikea', {useNewUrlParser: true, useUnifiedTopology: true}); const database = mongoose.connection; database.on('error', err => console.log('error connecting:', err)); database.once('open', () => console.log('connected to database')); // Query for product by ID const product = await Products.findById(id) .catch(err => { if (err) { console.log('Error with MongoDB read query'); } }); database.close(); return product; }; const updateQuery = async (id, data) => { // function will not do anything if data is empty if (Object.keys(data).length !== 0) { mongoose.connect('mongodb://localhost/ikea', {useNewUrlParser: true, useUnifiedTopology: true}); const database = mongoose.connection; database.on('error', err => console.log('error connecting:', err)); database.once('open', () => console.log('connected to database')); Products.updateOne({_id: id}, {$set: data}) .then(result => { database.close(); }) .catch(err => { database.close(); console.log('Error with MongoDB update query', err); }); } }; const deleteQuery = async (id) => { mongoose.connect('mongodb://localhost/ikea', {useNewUrlParser: true, useUnifiedTopology: true}); const database = mongoose.connection; database.on('error', err => console.log('error connecting:', err)); database.once('open', () => console.log('connected to database')); // Query for product by ID and then delete await Products.deleteOne({_id: id}) .then(result => { database.close(); }) .catch(err => { if (err) { database.close(); console.log('Error with MongoDB delete query', err); } }); }; module.exports = { seedDatabase, queryDatabase, createQuery, updateQuery, readQuery, deleteQuery };<file_sep>/database/postgres/postgres.js const newrelic = require('newrelic'); const {Pool} = require('pg'); const dummyData = require('../dummy-data.js'); const pool = new Pool({ user: process.env.DB_USER, password: process.env.DB_PASSWORD, host: process.env.DB_HOST, database: process.env.DB_DATABASE, port: process.env.DB_PORT }); pool.on('error', (err, client) => { console.error('Unexpected error on idle client', err); process.exit(-1); }); const schema = ` CREATE TABLE IF NOT EXISTS products ( id INTEGER NOT NULL PRIMARY KEY, brand VARCHAR(15) NOT NULL, category VARCHAR(20) NOT NULL, color VARCHAR(15) NOT NULL, price NUMERIC(4,1) NOT NULL, linkedColors INTEGER ARRAY[5], linkedSizes INTEGER ARRAY[4], newProduct BOOLEAN NOT NULL, productAvailable BOOLEAN NOT NULL ); `; const createPGQuery = async (data) => { const queryID = 'SELECT MAX(id) FROM products'; const { rows } = await pool.query(queryID); const newID = rows[0].max + 1; console.log(newID); const columnNames = '(id, brand, category, color, price, linkedColors, linkedSizes, newProduct, productAvailable)'; let columnValues; if (Object.keys(data).length === 0) { const entry = dummyData.generateRandomEntry(newID); columnValues = ` (${newID}, '${entry.brand}', '${entry.category}', '${entry.color}', ${entry.price}, '{${entry.linkedColors}}'::INTEGER[], '{${entry.linkedSizes}}'::INTEGER[], ${entry.newProduct}, ${entry.productAvailable})`; } else { columnValues = ` (${newID}, '${data.brand}', '${data.category}', '${data.color}', ${data.price}, '{${data.linkedColors}}'::INTEGER[], '{${data.linkedSizes}}'::INTEGER[], ${data.newProduct}, ${data.productAvailable})`; } const queryInsert = `INSERT INTO products ${columnNames} VALUES ${columnValues}`; await pool.query(queryInsert) .catch(err => { if (err) { console.log('Error with Postgres create query', err); } }); }; const readPGQuery = async (id) => { const query = `SELECT * FROM products WHERE id = ${id}`; const {rows} = await pool.query(query) .catch(err => { if (err) { console.log('Error with Postgres read query', err); } }); return rows[0]; // let product; // await pool.connect() // .then(async client => { // return await client.query(query) // .then(res => { // client.release(); // product = res.rows[0]; // }) // .catch(err => { // if (err) { // client.release(); // console.log('Error with Postgres read query'. err); // } // }); // }); // return product; }; const updatePGQuery = async (id, data) => { if (Object.keys(data).length === 0) { return; } const columnNames = Object.keys(data); const columnValues = Object.values(data); let queryData = ''; let nextInsert; for (let i = 0; i < columnNames.length; i++) { if (columnNames[i] === 'brand' || columnNames[i] === 'category' || columnNames[i] === 'color') { nextInsert = `${columnNames[i]} = '${columnValues[i]}'`; } else if (columnNames[i] === 'linkedSizes' || columnNames[i] === 'linkedColors') { nextInsert = `${columnNames[i]} = '{${columnValues[i]}}'::INTEGER[]`; } else { nextInsert = `${columnNames[i]} = ${columnValues[i]}`; } queryData = queryData.concat(', ', nextInsert); } queryData = queryData.substring(2); const query = `UPDATE products SET ${queryData} WHERE id = ${id}`; await pool.query(query) .catch(err => { if (err) { console.log('Error with Postgres update query', err); } }); }; const deletePGQuery = async (id) => { const query = `DELETE FROM products WHERE id = ${id}`; pool.query(query) .catch(err => { if (err) { console.log('Error with Postgres delete query', err); } }); }; module.exports = { pool, schema, createPGQuery, readPGQuery, updatePGQuery, deletePGQuery };
e1fb3f08e8df4888ccf9d508dc9572e5129fc36f
[ "Markdown", "JavaScript" ]
3
Markdown
HR-SDC-Bridge/calvin-about
8b42a11f4c74adcc284b55e1d498926586d547f8
bab03370bccbca0ab11989c449d466dc6a751409
refs/heads/master
<file_sep>import tensorflow as tf v1 = tf.Variable([1,2,3,4]) v2 = tf.Variable([5,4,3,2]) add = tf.add(v1+v2) with tf.Session() as sess: print(sess.run(add))<file_sep># tensorflow-basics Simple Tensorflow Programs for Beginners. Files Descriptions 1. print-message.py use tensorflow session to print hello world message. 2. add-constant.py use tensorflow session to add two constants.
db8a1a5be19ab1ebace3ed0a20657043ab32547a
[ "Markdown", "Python" ]
2
Python
vijay1131/tensorflow-basics
f377969e47d14fbe04e44601b815e72b75085cb7
10158b867b8f14d2e8b43e36ea24b90f911b0971